Class: Eth::Address

Inherits:
Object
  • Object
show all
Defined in:
lib/eth/address.rb

Overview

The Address class to handle checksummed Ethereum addresses.

Defined Under Namespace

Classes: CheckSumError

Constant Summary collapse

ZERO =

The literal zero address 0x0.

"0x0000000000000000000000000000000000000000"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(address) ⇒ Address

Constructor of the Eth::Address class. Creates a new hex prefixed address.

Parameters:

  • address (String)

    hex string representing an ethereum address.



34
35
36
37
38
39
40
41
42
# File 'lib/eth/address.rb', line 34

def initialize(address)
  unless Util.hex? address
    raise CheckSumError, "Unknown address type #{address}!"
  end
  @address = Util.prefix_hex address
  unless self.valid?
    raise CheckSumError, "Invalid address provided #{address}"
  end
end

Instance Attribute Details

#addressObject (readonly)

The prefixed and checksummed Ethereum address.



28
29
30
# File 'lib/eth/address.rb', line 28

def address
  @address
end

Instance Method Details

#checksummedString Also known as: to_s

Generate a checksummed address.

Returns:

  • (String)

    prefixed hexstring representing an checksummed address.

Raises:



67
68
69
70
71
72
73
74
75
# File 'lib/eth/address.rb', line 67

def checksummed
  raise CheckSumError, "Invalid address: #{address}" unless matches_any_format?

  cased = unprefixed.chars.zip(checksum.chars).map do |char, check|
    check.match(/[0-7]/) ? char.downcase : char.upcase
  end

  Util.prefix_hex cased.join
end

#valid?Boolean

Checks that the address is valid.

Returns:

  • (Boolean)

    true if valid address.



47
48
49
50
51
52
53
54
55
# File 'lib/eth/address.rb', line 47

def valid?
  if !matches_any_format?
    false
  elsif not_checksummed?
    true
  else
    checksum_matches?
  end
end

#zero?Boolean

Checks that the address is the zero address.

Returns:

  • (Boolean)

    true if the address is the zero address.



60
61
62
# File 'lib/eth/address.rb', line 60

def zero?
  address == ZERO
end