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:swordfish@example.com:3128' # here!
)

More information in our README.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2025 Yegor Bugayenko

License

MIT

Constant Summary collapse

USDT =
'0xdac17f958d2ee523a2206206994597c13d831ec7'
TRANSFER =
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
GAS_PRICE_TIP =
1_000_000_000

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, attempts: 1, fallbacks: []) ⇒ 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

  • attempts (Integer) (defaults to: 1)

    How many times to retry a failed HTTP RPC call before giving up

  • fallbacks (Array<String>) (defaults to: [])

    Alternative HTTP RPC endpoint URLs to try when the primary one fails

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

    The destination for logs

Raises:

  • (ArgumentError)


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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/erc20/wallet.rb', line 78

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

Instance Attribute Details

#chainObject (readonly)

Returns the value of attribute chain.



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

def chain
  @chain
end

#contractObject (readonly)

Returns the value of attribute contract.



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

def contract
  @contract
end

#hostObject (readonly)

Returns the value of attribute host.



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

def host
  @host
end

#http_pathObject (readonly)

Returns the value of attribute http_path.



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

def http_path
  @http_path
end

#portObject (readonly)

Returns the value of attribute port.



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

def port
  @port
end

#sslObject (readonly)

Returns the value of attribute ssl.



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

def ssl
  @ssl
end

#ws_pathObject (readonly)

Returns the value of attribute ws_path.



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

Raises:

  • (ArgumentError)


367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/erc20/wallet.rb', line 367

def accept(addresses, active = [], raw: false, delay: 1, subscription_id: rand(99_999), &)
  raise(ArgumentError, 'Addresses can\'t be nil') unless addresses
  raise(ArgumentError, 'Addresses must respond to .to_a()') unless addresses.respond_to?(:to_a)
  raise(ArgumentError, 'Active can\'t be nil') unless active
  raise(ArgumentError, 'Active must respond to .to_a()') unless active.respond_to?(:to_a)
  raise(ArgumentError, 'Active must respond to .append()') unless active.respond_to?(:append)
  raise(ArgumentError, 'Active must respond to .clear()') unless active.respond_to?(:clear)
  raise(ArgumentError, 'Delay must be an Integer') unless delay.is_a?(Integer)
  raise(ArgumentError, 'Delay must be a positive Integer or positive Float') unless delay.positive?
  raise(ArgumentError, 'Subscription ID must be an Integer') unless subscription_id.is_a?(Integer)
  raise(ArgumentError, 'Subscription ID must be a positive Integer') unless subscription_id.positive?
  EventMachine.run do
    reaccept(addresses, active, raw:, delay:, subscription_id:, &)
  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

Raises:

  • (ArgumentError)


130
131
132
133
134
135
136
137
138
# File 'lib/erc20/wallet.rb', line 130

def balance(address)
  raise(ArgumentError, 'Address can\'t be nil') unless address
  raise(ArgumentError, 'Address must be a String') unless address.is_a?(String)
  raise(ArgumentError, 'Invalid format of the address') unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  data = "0x70a08231000000000000000000000000#{address[2..].downcase}"
  b = with_jsonrpc { |jr| jr.eth_call({ to: @contract, data: data }, 'latest') }[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:

  • address (String)

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

Returns:

  • (Integer)

    Balance, in ETH

Raises:

  • (ArgumentError)


147
148
149
150
151
152
153
154
# File 'lib/erc20/wallet.rb', line 147

def eth_balance(address)
  raise(ArgumentError, 'Address can\'t be nil') unless address
  raise(ArgumentError, 'Address must be a String') unless address.is_a?(String)
  raise(ArgumentError, 'Invalid format of the address') unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  b = with_jsonrpc { |jr| jr.eth_getBalance(address, 'latest') }[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

Raises:

  • (ArgumentError)


303
304
305
306
307
308
309
310
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
# File 'lib/erc20/wallet.rb', line 303

def eth_pay(priv, address, amount, price: gas_price)
  raise(ArgumentError, 'Private key can\'t be nil') unless priv
  raise(ArgumentError, 'Private key must be a String') unless priv.is_a?(String)
  raise(ArgumentError, 'Invalid format of private key') unless /^[0-9a-fA-F]{64}$/.match?(priv)
  raise(ArgumentError, 'Address can\'t be nil') unless address
  raise(ArgumentError, 'Address must be a String') unless address.is_a?(String)
  raise(ArgumentError, 'Invalid format of the address') unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  raise(ArgumentError, 'Amount can\'t be nil') unless amount
  raise(ArgumentError, "Amount (#{amount}) must be an Integer") unless amount.is_a?(Integer)
  raise(ArgumentError, "Amount (#{amount}) must be a positive Integer") unless amount.positive?
  if price
    raise(ArgumentError, 'Gas price must be an Integer') unless price.is_a?(Integer)
    raise(ArgumentError, '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
      with_jsonrpc do |jr|
        tx = Eth::Tx.new(
          {
            chain_id: @chain,
            nonce: jr.eth_getTransactionCount(from, 'pending').to_i(16),
            gas_price: price,
            gas_limit: 22_000,
            to: address,
            value: amount
          }
        )
        tx.sign(key)
        hex = "0x#{tx.hex}"
        log_it(:debug, "Sending ETH transaction #{hex}")
        jr.eth_sendRawTransaction(hex)
      end
    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

Raises:

  • (ArgumentError)


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/erc20/wallet.rb', line 186

def gas_estimate(from, to, amount)
  raise(ArgumentError, 'Address can\'t be nil') unless from
  raise(ArgumentError, 'Address must be a String') unless from.is_a?(String)
  raise(ArgumentError, 'Invalid format of the address') unless /^0x[0-9a-fA-F]{40}$/.match?(from)
  raise(ArgumentError, 'Address can\'t be nil') unless to
  raise(ArgumentError, 'Address must be a String') unless to.is_a?(String)
  raise(ArgumentError, 'Invalid format of the address') unless /^0x[0-9a-fA-F]{40}$/.match?(to)
  raise(ArgumentError, 'Amount can\'t be nil') unless amount
  raise(ArgumentError, "Amount (#{amount}) must be an Integer") unless amount.is_a?(Integer)
  raise(ArgumentError, "Amount (#{amount}) must be a positive Integer") unless amount.positive?
  gas =
    with_jsonrpc do |jr|
      jr.eth_estimateGas({ from:, to: @contract, data: to_pay_data(to, amount) }, 'latest').to_i(16)
    end
  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 wei?

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 wei (1 gwei = 0.000000001 ETH). Higher gas prices incentivize miners to include your transaction sooner, while lower prices may result in longer confirmation times.

The returned price is not the bare EIP-1559 base fee. The base fee alone leaves a zero miner tip (+tip = gasPrice - baseFee = 0+), so proposers have no incentive to include the transaction, and it becomes unmineable the moment the base fee rises (it may grow up to 12.5% per block). To make the price mineable, we double the base fee (a buffer that absorbs several blocks of base-fee growth) and add a priority tip (GAS_PRICE_TIP).

Returns:

  • (Integer)

    Price of gas unit, in wei (1 gwei = 0.000000001 ETH)

Raises:

  • (StandardError)


223
224
225
226
227
228
229
230
231
232
233
# File 'lib/erc20/wallet.rb', line 223

def gas_price
  block =
    with_jsonrpc do |jr|
      jr.eth_getBlockByNumber('latest', false)
    end
  raise(StandardError, "Can't get gas price, try again later") if block.nil?
  base = block['baseFeePerGas'].to_i(16)
  price = (base * 2) + GAS_PRICE_TIP
  log_it(:debug, "The base fee is #{base} wei, the cost of one gas unit is #{price} wei")
  price
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

Raises:

  • (ArgumentError)


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
285
286
287
288
289
290
291
292
293
294
# File 'lib/erc20/wallet.rb', line 251

def pay(priv, address, amount, limit: nil, price: gas_price)
  raise(ArgumentError, 'Private key can\'t be nil') unless priv
  raise(ArgumentError, 'Private key must be a String') unless priv.is_a?(String)
  raise(ArgumentError, 'Invalid format of private key') unless /^[0-9a-fA-F]{64}$/.match?(priv)
  raise(ArgumentError, 'Address can\'t be nil') unless address
  raise(ArgumentError, 'Address must be a String') unless address.is_a?(String)
  raise(ArgumentError, 'Invalid format of the address') unless /^0x[0-9a-fA-F]{40}$/.match?(address)
  raise(ArgumentError, 'Amount can\'t be nil') unless amount
  raise(ArgumentError, "Amount (#{amount}) must be an Integer") unless amount.is_a?(Integer)
  raise(ArgumentError, "Amount (#{amount}) must be a positive Integer") unless amount.positive?
  if limit
    raise(ArgumentError, 'Gas limit must be an Integer') unless limit.is_a?(Integer)
    raise(ArgumentError, "Gas limit #{limit} is below #{Eth::Tx::DEFAULT_GAS_LIMIT}") if limit < Eth::Tx::DEFAULT_GAS_LIMIT
    raise(ArgumentError, "Gas limit #{limit} is above #{Eth::Tx::BLOCK_GAS_LIMIT}") if limit > Eth::Tx::BLOCK_GAS_LIMIT
  end
  if price
    raise(ArgumentError, 'Gas price must be an Integer') unless price.is_a?(Integer)
    raise(ArgumentError, '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
      with_jsonrpc do |jr|
        tx = Eth::Tx.new(
          {
            nonce: jr.eth_getTransactionCount(from, 'pending').to_i(16),
            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}"
        log_it(:debug, "Sending ERC20 transaction #{hex}")
        jr.eth_sendRawTransaction(hex)
      end
    end
  log_it(:debug, "Sent #{amount} ERC20 tokens from #{from} to #{address}: #{tnx}")
  tnx.downcase
end

#sum_of(txn) ⇒ Integer

Get ERC20 amount (in tokens) that was sent in the given transaction.

Parameters:

  • txn (String)

    Hex of transaction

Returns:

  • (Integer)

    Balance, in ERC20 tokens

Raises:

  • (ArgumentError)


160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/erc20/wallet.rb', line 160

def sum_of(txn)
  raise(ArgumentError, 'Transaction hash can\'t be nil') unless txn
  raise(ArgumentError, 'Transaction hash must be a String') unless txn.is_a?(String)
  raise(ArgumentError, 'Invalid format of the transaction hash') unless /^0x[0-9a-fA-F]{64}$/.match?(txn)
  receipt =
    with_jsonrpc do |jr|
      jr.eth_getTransactionReceipt(txn)
    end
  raise(StandardError, "Transaction not found: #{txn}") if receipt.nil?
  logs = receipt['logs'] || []
  logs.each do |log|
    next unless log['topics'] && log['topics'][0] == TRANSFER
    next unless log['address'].downcase == @contract.downcase
    amount = log['data'].to_i(16)
    log_it(:debug, "Found transfer of #{amount} tokens in transaction #{txn}")
    return amount
  end
  raise(StandardError, "No transfer event found in transaction #{txn}")
end