class InfuraRuby::Client
Constants
- BLOCK_PARAMETERS
- ETHEREUM_ADDRESS_REGEX
- JSON_RPC_METHODS
- NETWORK_URLS
Infura URLs for each network.
Public Class Methods
new(api_key:, network: :main)
click to toggle source
# 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
Public Instance Methods
get_balance(address, tag: 'latest')
click to toggle source
TODO: move calls out of client - worth doing when we have > 1. Returns balance of address in wei as integer.
# 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
Private Instance Methods
conn()
click to toggle source
# File lib/infura_ruby/client.rb, line 92 def conn @conn ||= Faraday.new( url: "#{NETWORK_URLS[@network]}/#{@api_key}", ) end
json_rpc(method:, params:)
click to toggle source
TODO: this JSON RPC object should be a whole object / gem.
# File lib/infura_ruby/client.rb, line 63 def json_rpc(method:, params:) validate_json_rpc_method(method) { "jsonrpc" => "2.0", "method" => method, "params" => params, "id" => 1 } end
validate_address(address)
click to toggle source
# File lib/infura_ruby/client.rb, line 80 def validate_address(address) if ETHEREUM_ADDRESS_REGEX !~ address raise InvalidEthereumAddressError.new("'#{address}' is not a valid ethereum address.") end end
validate_api_key(api_key)
click to toggle source
# File lib/infura_ruby/client.rb, line 98 def validate_api_key(api_key) raise InvalidApiKeyError unless /^[a-zA-Z0-9]{20}$/ =~ api_key end
validate_block_tag(tag)
click to toggle source
# File lib/infura_ruby/client.rb, line 74 def validate_block_tag(tag) if BLOCK_PARAMETERS.none? { |regex| regex =~ tag.to_s } raise NotImplementedError.new("Block parameter tag '#{tag}' does not exist.") end end
validate_json_rpc_method(method)
click to toggle source
# File lib/infura_ruby/client.rb, line 86 def validate_json_rpc_method(method) if !JSON_RPC_METHODS.include?(method) raise NotImplementedError.new("JSON RPC method '#{method}' does not exist.") end end
validate_network(network)
click to toggle source
# File lib/infura_ruby/client.rb, line 102 def validate_network(network) raise InvalidNetworkError if NETWORK_URLS[network].nil? end