Class: ERC20::Wallet

Inherits:
Object
  • Object
show all
Defined in:
lib/erc20/wallet.rb

Overview

A wallet with ERC20 tokens on Ethereum.

Objects of this class are thread-safe.

In order to check the balance of ERC20 address:

require 'erc20'
w = ERC20::Wallet.new(
  contract: ERC20::Wallet.USDT, # hex of it
  host: 'mainnet.infura.io',
  http_path: '/v3/<your-infura-key>',
  ws_path: '/ws/v3/<your-infura-key>',
  log: $stdout
)
usdt = w.balance(address)

In order to send a payment:

hex = w.pay(private_key, to_address, amount)

In order to catch incoming payments to a set of addresses:

addresses = ['0x...', '0x...']
w.accept(addresses) do |event|
  puts event[:txt] # hash of transaction
  puts event[:amount] # how much, in tokens (1000000 = $1 USDT)
  puts event[:from] # who sent the payment
  puts event[:to] # who was the receiver
end

To connect to the server via HTTP proxy with basic authentication:

w = ERC20::Wallet.new(
  host: 'go.getblock.io',
  http_path: '/<your-rpc-getblock-key>',
  ws_path: '/<your-ws-getblock-key>',
  proxy: 'http://jeffrey:[email protected]:3128' # here!
)

More information in our README.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2025 Yegor Bugayenko

License

MIT

Constant Summary collapse

USDT =

Address of USDT contract.

'0xdac17f958d2ee523a2206206994597c13d831ec7'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(contract: USDT, chain: 1, log: $stdout, host: nil, port: 443, http_path: '/', ws_path: '/', ssl: true, proxy: nil) ⇒ Wallet

Constructor.

Parameters:

  • contract (String) (defaults to: USDT)

    Hex of the contract in Ethereum

  • chain (Integer) (defaults to: 1)

    The ID of the chain (1 for mainnet)

  • host (String) (defaults to: nil)

    The host to connect to

  • port (Integer) (defaults to: 443)

    TCP port to use

  • http_path (String) (defaults to: '/')

    The path in the connection URL, for HTTP RPC

  • ws_path (String) (defaults to: '/')

    The path in the connection URL, for Websockets

  • ssl (Boolean) (defaults to: true)

    Should we use SSL (for https and wss)

  • proxy (String) (defaults to: nil)

    The URL of the proxy to use

  • log (Object) (defaults to: $stdout)

    The destination for logs



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/erc20/wallet.rb', line 76

def initialize(contract: USDT, chain: 1, log: $stdout,
               host: nil, port: 443, http_path: '/', ws_path: '/',
               ssl: true, proxy: nil)
  raise 'Contract can\'t be nil' unless contract
  raise 'Contract must be a String' unless contract.is_a?(String)
  raise 'Invalid format of the contract' unless /^0x[0-9a-fA-F]{40}$/.match?(contract)
  @contract = contract
  raise 'Host can\'t be nil' unless host
  raise 'Host must be a String' unless host.is_a?(String)
  @host = host
  raise 'Port can\'t be nil' unless port
  raise 'Port must be an Integer' unless port.is_a?(Integer)
  raise 'Port must be a positive Integer' unless port.positive?
  @port = port
  raise 'Ssl can\'t be nil' if ssl.nil?
  @ssl = ssl
  raise 'Http_path can\'t be nil' unless http_path
  raise 'Http_path must be a String' unless http_path.is_a?(String)
  @http_path = http_path
  raise 'Ws_path can\'t be nil' unless ws_path
  raise 'Ws_path must be a String' unless ws_path.is_a?(String)
  @ws_path = ws_path
  raise 'Log can\'t be nil' unless log
  @log = log
  raise 'Chain can\'t be nil' unless chain
  raise 'Chain must be an Integer' unless chain.is_a?(Integer)
  raise 'Chain must be a positive Integer' unless chain.positive?
  @chain = chain
  @proxy = proxy
  @mutex = Mutex.new
end

Instance Attribute Details

#chainObject (readonly)

These properties are read-only:



64
65
66
# File 'lib/erc20/wallet.rb', line 64

def chain
  @chain
end

#contractObject (readonly)

These properties are read-only:



64
65
66
# File 'lib/erc20/wallet.rb', line 64

def contract
  @contract
end

#hostObject (readonly)

These properties are read-only:



64
65
66
# File 'lib/erc20/wallet.rb', line 64

def host
  @host
end

#http_pathObject (readonly)

These properties are read-only:



64
65
66
# File 'lib/erc20/wallet.rb', line 64

def http_path
  @http_path
end

#portObject (readonly)

These properties are read-only:



64
65
66
# File 'lib/erc20/wallet.rb', line 64

def port
  @port
end

#sslObject (readonly)

These properties are read-only:



64
65
66
# File 'lib/erc20/wallet.rb', line 64

def ssl
  @ssl
end

#ws_pathObject (readonly)

These properties are read-only:



64
65
66
# File 'lib/erc20/wallet.rb', line 64

def ws_path
  @ws_path
end

Instance Method Details

#accept(addresses, active = [], raw: false, delay: 1, subscription_id: rand(99_999)) ⇒ Object

Wait for incoming transactions and let the block know when they arrive. It’s a blocking call, it’s better to run it in a separate thread. It will never finish. In order to stop it, you should do Thread.kill.

The array with the list of addresses (addresses) may change its content on-the-fly. The accept() method will eth_subscribe to the addresses that are added and will eth_unsubscribe from those that are removed. Once we actually start listening, the active array will be updated with the list of addresses.

The addresses must have to_a() implemented. This method will be called every delay seconds. It is expected that it returns the list of Ethereum public addresses that must be monitored.

The active must have append() and to_a() implemented. This array maintains the list of addresses that were mentioned in incoming transactions. This array is used mostly for testing. It is suggested to always provide an empty array.

Parameters:

  • addresses (Array<String>)

    Addresses to monitor

  • active (Array) (defaults to: [])

    List of addresses that we are actually listening to

  • raw (Boolean) (defaults to: false)

    TRUE if you need to get JSON events as they arrive from Websockets

  • delay (Integer) (defaults to: 1)

    How many seconds to wait between eth_subscribe calls

  • subscription_id (Integer) (defaults to: rand(99_999))

    Unique ID of the subscription



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/erc20/wallet.rb', line 311

def accept(addresses, active = [], raw: false, delay: 1, subscription_id: rand(99_999))
  raise 'Addresses can\'t be nil' unless addresses
  raise 'Addresses must respond to .to_a()' unless addresses.respond_to?(:to_a)
  raise 'Active can\'t be nil' unless active
  raise 'Active must respond to .append()' unless active.respond_to?(:append)
  raise 'Delay must be an Integer' unless delay.is_a?(Integer)
  raise 'Delay must be a positive Integer' unless delay.positive?
  raise 'Subscription ID must be an Integer' unless subscription_id.is_a?(Integer)
  raise 'Subscription ID must be a positive Integer' unless subscription_id.positive?
  EventMachine.run do
    u = url(http: false)
    log_it(:debug, "Connecting to #{u.hostname}:#{u.port}...")
    ws = Faye::WebSocket::Client.new(u.to_s, [], proxy: @proxy ? { origin: @proxy } : {})
    contract = @contract
    attempt = []
    log_url = "ws#{@ssl ? 's' : ''}://#{u.hostname}:#{u.port}"
    ws.on(:open) do
      safe do
        verbose do
          log_it(:debug, "Connected to #{log_url}")
        end
      end
    end
    ws.on(:message) do |msg|
      safe do
        verbose do
          data = to_json(msg)
          if data['id']
            before = active.to_a
            attempt.each do |a|
              active.append(a) unless before.include?(a)
            end
            log_it(
              :debug,
              "Subscribed ##{subscription_id} to #{active.to_a.size} addresses at #{log_url}: " \
              "#{active.to_a.map { |a| a[0..6] }.join(', ')}"
            )
          elsif data['method'] == 'eth_subscription' && data.dig('params', 'result')
            event = data['params']['result']
            if raw
              log_it(:debug, "New event arrived from #{event['address']}")
            else
              event = {
                amount: event['data'].to_i(16),
                from: "0x#{event['topics'][1][26..].downcase}",
                to: "0x#{event['topics'][2][26..].downcase}",
                txn: event['transactionHash'].downcase
              }
              log_it(
                :debug,
                "Payment of #{event[:amount]} tokens arrived " \
                "from #{event[:from]} to #{event[:to]} in #{event[:txn]}"
              )
            end
            yield event
          end
        end
      end
    end
    ws.on(:close) do
      safe do
        verbose do
          log_it(:debug, "Disconnected from #{log_url}")
        end
      end
    end
    ws.on(:error) do |e|
      safe do
        verbose do
          log_it(:debug, "Error at #{log_url}: #{e.message}")
        end
      end
    end
    EventMachine.add_periodic_timer(delay) do
      next if active.to_a.sort == addresses.to_a.sort
      attempt = addresses.to_a
      ws.send(
        {
          jsonrpc: '2.0',
          id: subscription_id,
          method: 'eth_subscribe',
          params: [
            'logs',
            {
              address: contract,
              topics: [
                '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
                nil,
                addresses.to_a.map { |a| "0x000000000000000000000000#{a[2..]}" }
              ]
            }
          ]
        }.to_json
      )
      log_it(
        :debug,
        "Requested to subscribe ##{subscription_id} to #{addresses.to_a.size} addresses at #{log_url}: " \
        "#{addresses.to_a.map { |a| a[0..6] }.join(', ')}"
      )
    end
  end
end

#balance(address) ⇒ Integer

Get ERC20 balance of a public address (it’s not the same as ETH balance!).

An address in Ethereum may have many balances. One of them is the main balance in ETH crypto. Another balance is the one kept by the ERC20 contract in its own ledger in root storage. This balance is checked by this method.

Parameters:

  • address (String)

    Public key, in hex, starting from ‘0x’

Returns:

  • (Integer)

    Balance, in tokens



116
117
118
119
120
121
122
123
124
125
126
# File 'lib/erc20/wallet.rb', line 116

def balance(address)
  raise 'Address can\'t be nil' unless address
  raise 'Address must be a String' unless address.is_a?(String)
  raise 'Invalid format of the address' unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  func = '70a08231' # balanceOf
  data = "0x#{func}000000000000000000000000#{address[2..].downcase}"
  r = jsonrpc.eth_call({ to: @contract, data: data }, 'latest')
  b = r[2..].to_i(16)
  log_it(:debug, "The balance of #{address} is #{b} ERC20 tokens")
  b
end

#eth_balance(address) ⇒ Integer

Get ETH balance of a public address.

An address in Ethereum may have many balances. One of them is the main balance in ETH crypto. This balance is checked by this method.

Parameters:

  • hex (String)

    Public key, in hex, starting from ‘0x’

Returns:

  • (Integer)

    Balance, in ETH



135
136
137
138
139
140
141
142
143
# File 'lib/erc20/wallet.rb', line 135

def eth_balance(address)
  raise 'Address can\'t be nil' unless address
  raise 'Address must be a String' unless address.is_a?(String)
  raise 'Invalid format of the address' unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  r = jsonrpc.eth_getBalance(address, 'latest')
  b = r[2..].to_i(16)
  log_it(:debug, "The balance of #{address} is #{b} ETHs")
  b
end

#eth_pay(priv, address, amount, price: gas_price) ⇒ String

Send a single ETH payment from a private address to a public one.

Parameters:

  • priv (String)

    Private key, in hex

  • address (String)

    Public key, in hex

  • amount (Integer)

    The amount of ETH to send

  • price (Integer) (defaults to: gas_price)

    How much gas you pay per computation unit

Returns:

  • (String)

    Transaction hash



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/erc20/wallet.rb', line 249

def eth_pay(priv, address, amount, price: gas_price)
  raise 'Private key can\'t be nil' unless priv
  raise 'Private key must be a String' unless priv.is_a?(String)
  raise 'Invalid format of private key' unless /^[0-9a-fA-F]{64}$/.match?(priv)
  raise 'Address can\'t be nil' unless address
  raise 'Address must be a String' unless address.is_a?(String)
  raise 'Invalid format of the address' unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  raise 'Amount can\'t be nil' unless amount
  raise "Amount (#{amount}) must be an Integer" unless amount.is_a?(Integer)
  raise "Amount (#{amount}) must be a positive Integer" unless amount.positive?
  if price
    raise 'Gas price must be an Integer' unless price.is_a?(Integer)
    raise 'Gas price must be a positive Integer' unless price.positive?
  end
  key = Eth::Key.new(priv: priv)
  from = key.address.to_s
  tnx =
    @mutex.synchronize do
      nonce = jsonrpc.eth_getTransactionCount(from, 'pending').to_i(16)
      tx = Eth::Tx.new(
        {
          chain_id: @chain,
          nonce:,
          gas_price: price,
          gas_limit: 22_000,
          to: address,
          value: amount
        }
      )
      tx.sign(key)
      hex = "0x#{tx.hex}"
      jsonrpc.eth_sendRawTransaction(hex)
    end
  log_it(:debug, "Sent #{amount} ETHs from #{from} to #{address}: #{tnx}")
  tnx.downcase
end

#gas_estimate(from, to, amount) ⇒ Integer

How many gas units are required to send an ERC20 transaction.

Parameters:

  • from (String)

    The sending address, in hex

  • to (String)

    The receiving address, in hex

  • amount (Integer)

    How many ERC20 tokens to send

Returns:

  • (Integer)

    Number of gas units required



151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/erc20/wallet.rb', line 151

def gas_estimate(from, to, amount)
  raise 'Address can\'t be nil' unless from
  raise 'Address must be a String' unless from.is_a?(String)
  raise 'Invalid format of the address' unless /^0x[0-9a-fA-F]{40}$/.match?(from)
  raise 'Address can\'t be nil' unless to
  raise 'Address must be a String' unless to.is_a?(String)
  raise 'Invalid format of the address' unless /^0x[0-9a-fA-F]{40}$/.match?(to)
  raise 'Amount can\'t be nil' unless amount
  raise "Amount (#{amount}) must be an Integer" unless amount.is_a?(Integer)
  raise "Amount (#{amount}) must be a positive Integer" unless amount.positive?
  gas = jsonrpc.eth_estimateGas({ from:, to: @contract, data: to_pay_data(to, amount) }, 'latest').to_i(16)
  log_it(:debug, "It would take #{gas} gas units to send #{amount} tokens from #{from} to #{to}")
  gas
end

#gas_priceInteger

What is the price of gas unit in gwei?

In Ethereum, gas is a unit that measures the computational work required to execute operations on the network. Every transaction and smart contract interaction consumes gas. Gas price is the amount of ETH you’re willing to pay for each unit of gas, denominated in gwei (1 gwei = 0.000000001 ETH). Higher gas prices incentivize miners to include your transaction sooner, while lower prices may result in longer confirmation times.

Returns:

  • (Integer)

    Price of gas unit, in gwei (0.000000001 ETH)



176
177
178
179
180
181
182
# File 'lib/erc20/wallet.rb', line 176

def gas_price
  block = jsonrpc.eth_getBlockByNumber('latest', false)
  raise "Can't get gas price, try again later" if block.nil?
  gwei = block['baseFeePerGas'].to_i(16)
  log_it(:debug, "The cost of one gas unit is #{gwei} gwei")
  gwei
end

#pay(priv, address, amount, limit: nil, price: gas_price) ⇒ String

Send a single ERC20 payment from a private address to a public one.

ERC20 payments differ fundamentally from native ETH transfers. While ETH transfers simply move the cryptocurrency directly between addresses, ERC20 token transfers are actually interactions with a smart contract. When you transfer ERC20 tokens, you’re not sending anything directly to another user - instead, you’re calling the token contract’s transfer function, which updates its internal ledger to decrease your balance and increase the recipient’s balance. This requires more gas than ETH transfers since it involves executing contract code.

Parameters:

  • priv (String)

    Private key, in hex

  • address (String)

    Public key, in hex

  • amount (Integer)

    The amount of ERC20 tokens to send

  • limit (Integer) (defaults to: nil)

    How much gas you’re ready to spend

  • price (Integer) (defaults to: gas_price)

    How much gas you pay per computation unit

Returns:

  • (String)

    Transaction hash



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/erc20/wallet.rb', line 200

def pay(priv, address, amount, limit: nil, price: gas_price)
  raise 'Private key can\'t be nil' unless priv
  raise 'Private key must be a String' unless priv.is_a?(String)
  raise 'Invalid format of private key' unless /^[0-9a-fA-F]{64}$/.match?(priv)
  raise 'Address can\'t be nil' unless address
  raise 'Address must be a String' unless address.is_a?(String)
  raise 'Invalid format of the address' unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  raise 'Amount can\'t be nil' unless amount
  raise "Amount (#{amount}) must be an Integer" unless amount.is_a?(Integer)
  raise "Amount (#{amount}) must be a positive Integer" unless amount.positive?
  if limit
    raise 'Gas limit must be an Integer' unless limit.is_a?(Integer)
    raise 'Gas limit must be a positive Integer' unless limit.positive?
  end
  if price
    raise 'Gas price must be an Integer' unless price.is_a?(Integer)
    raise 'Gas price must be a positive Integer' unless price.positive?
  end
  key = Eth::Key.new(priv: priv)
  from = key.address.to_s
  tnx =
    @mutex.synchronize do
      nonce = jsonrpc.eth_getTransactionCount(from, 'pending').to_i(16)
      tx = Eth::Tx.new(
        {
          nonce:,
          gas_price: price,
          gas_limit: limit || gas_estimate(from, address, amount),
          to: @contract,
          value: 0,
          data: to_pay_data(address, amount),
          chain_id: @chain
        }
      )
      tx.sign(key)
      hex = "0x#{tx.hex}"
      jsonrpc.eth_sendRawTransaction(hex)
    end
  log_it(:debug, "Sent #{amount} ERC20 tokens from #{from} to #{address}: #{tnx}")
  tnx.downcase
end