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



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
107
# File 'lib/erc20/wallet.rb', line 77

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:



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

def chain
  @chain
end

#contractObject (readonly)

These properties are read-only:



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

def contract
  @contract
end

#hostObject (readonly)

These properties are read-only:



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

def host
  @host
end

#http_pathObject (readonly)

These properties are read-only:



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

def http_path
  @http_path
end

#portObject (readonly)

These properties are read-only:



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

def port
  @port
end

#sslObject (readonly)

These properties are read-only:



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

def ssl
  @ssl
end

#ws_pathObject (readonly)

These properties are read-only:



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

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



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/erc20/wallet.rb', line 353

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 .to_a()' unless active.respond_to?(:to_a)
  raise 'Active must respond to .append()' unless active.respond_to?(:append)
  raise 'Active must respond to .clear()' unless active.respond_to?(:clear)
  raise 'Delay must be an Integer' unless delay.is_a?(Integer)
  raise 'Delay must be a positive Integer or positive Float' 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
    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



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

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 =
    with_jsonrpc do |jr|
      jr.eth_call({ to: @contract, data: data }, 'latest')
    end
  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:

  • address (String)

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

Returns:

  • (Integer)

    Balance, in ETH



139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/erc20/wallet.rb', line 139

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 =
    with_jsonrpc do |jr|
      jr.eth_getBalance(address, 'latest')
    end
  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



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/erc20/wallet.rb', line 289

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
      with_jsonrpc do |jr|
        nonce = jr.eth_getTransactionCount(from, 'pending').to_i(16)
        h = {
          chain_id: @chain,
          nonce:,
          gas_price: price,
          gas_limit: 22_000,
          to: address,
          value: amount
        }
        tx = Eth::Tx.new(h)
        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



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

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 =
    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 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)



211
212
213
214
215
216
217
218
219
220
# File 'lib/erc20/wallet.rb', line 211

def gas_price
  block =
    with_jsonrpc do |jr|
      jr.eth_getBlockByNumber('latest', false)
    end
  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



238
239
240
241
242
243
244
245
246
247
248
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
# File 'lib/erc20/wallet.rb', line 238

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
      with_jsonrpc do |jr|
        nonce = jr.eth_getTransactionCount(from, 'pending').to_i(16)
        h = {
          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 = Eth::Tx.new(h)
        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



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/erc20/wallet.rb', line 156

def sum_of(txn)
  raise 'Transaction hash can\'t be nil' unless txn
  raise 'Transaction hash must be a String' unless txn.is_a?(String)
  raise '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 "Transaction not found: #{txn}" if receipt.nil?
  logs = receipt['logs'] || []
  transfer_event = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
  logs.each do |log|
    next unless log['topics'] && log['topics'][0] == transfer_event
    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 "No transfer event found in transaction #{txn}"
end