Module: Siwe::Util

Defined in:
lib/siwe/util.rb

Constant Summary collapse

NONCE_LENGTH =
17
ISO8601_REGEX =
/
  \A
  (?<date>\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))
  [Tt]
  (?:[01]\d|2[0-3]):
  [0-5]\d:
  (?:[0-5]\d|60)
  (?:\.\d+)?
  (?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)
  \z
/x

Class Method Summary collapse

Class Method Details

.address_case(addr) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/siwe/util.rb', line 54

def address_case(addr)
  return :invalid unless addr.is_a?(String) && addr.match?(/\A0x[0-9a-fA-F]{40}\z/)

  hex = addr[2..]
  return :lower if hex == hex.downcase
  return :upper if hex == hex.upcase

  eip55 = checksum_address(addr)
  eip55 == addr ? :checksum : :invalid_checksum
end

.checksum_address(addr) ⇒ Object



65
66
67
68
69
# File 'lib/siwe/util.rb', line 65

def checksum_address(addr)
  Eth::Address.new(addr).to_s
rescue StandardError
  nil
end

.generate_nonceObject



26
27
28
# File 'lib/siwe/util.rb', line 26

def generate_nonce
  SecureRandom.alphanumeric(NONCE_LENGTH)
end

.valid_address?(addr) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
# File 'lib/siwe/util.rb', line 45

def valid_address?(addr)
  return false if addr.nil? || addr.empty?

  Eth::Address.new(addr)
  true
rescue StandardError
  false
end

.valid_iso8601?(str) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/siwe/util.rb', line 30

def valid_iso8601?(str)
  return false if str.nil? || str.empty?

  m = ISO8601_REGEX.match(str)
  return false if m.nil?

  year, month, day = m[:date].split("-").map(&:to_i)
  return false unless Date.valid_date?(year, month, day)

  Time.iso8601(str)
  true
rescue ArgumentError
  false
end