Class: InfuraRuby::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/infura_ruby/client.rb

Defined Under Namespace

Classes: InfuraCallError, InvalidEthereumAddressError

Constant Summary collapse

ETHEREUM_ADDRESS_REGEX =
/^0x[0-9a-fA-F]{40}$/
NETWORK_URLS =

Infura URLs for each network.

{
  main:      'https://mainnet.infura.io',
  test:      'https://ropsten.infura.io',
  consensys: 'https://consensysnet.inufra.io'
}.freeze
JSON_RPC_METHODS =
[
  'eth_getBalance'
].freeze
BLOCK_PARAMETERS =
[
  /^0x[0-9a-fA-F]{1,}$/, # an integer block number (hex string)
  /^earliest$/,          # for the earliest/genesis block
  /^latest$/,            # for the latest mined block
  /^pending$/            # for the pending state/transactions
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(api_key:, network: :main) ⇒ Client

Returns a new instance of Client.



29
30
31
32
33
34
35
# File 'lib/infura_ruby/client.rb', line 29

def initialize(api_key:, network: :main)
  validate_api_key(api_key)
  validate_network(network)

  @api_key = api_key
  @network = network
end

Instance Method Details

#get_balance(address, tag: 'latest') ⇒ Object

TODO: move calls out of client - worth doing when we have > 1. Returns balance of address in wei as integer.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/infura_ruby/client.rb', line 39

def get_balance(address, tag: 'latest')
  validate_address(address)
  validate_block_tag(tag)

  resp = conn.post do |req|
    req.headers['Content-Type'] = 'application/json'
    req.body = json_rpc(method: 'eth_getBalance', params: [address, tag]).to_json
  end
  resp_body  = JSON.parse(resp.body)

  if resp_body['error']
    raise InfuraCallError.new(
      "Error (#{resp_body['error']['code']}): Infura API call "\
      "eth_getBalance gave message: '#{resp_body['error']['message']}'"
    )
  else
    wei_amount_hex_string = resp_body['result']
    wei_amount_hex_string.to_i(16)
  end
end