Class: ERC20::Wallet

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

Overview

A wallet with ERC20 tokens on Etherium.

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 Etherium

  • 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-fly. The accept() method will eht_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. The active must have append() implemented. Only these methods will be called.

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



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

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 'Amount must be an Integer' unless delay.is_a?(Integer)
  raise 'Amount 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.debug("Connecting to #{u.hostname}:#{u.port}...")
    ws = Faye::WebSocket::Client.new(u.to_s, [], proxy: @proxy ? { origin: @proxy } : {})
    log = @log
    contract = @contract
    attempt = []
    log_url = "ws#{@ssl ? 's' : ''}://#{u.hostname}:#{u.port}"
    ws.on(:open) do
      verbose do
        log.debug("Connected to #{log_url}")
      end
    end
    ws.on(:message) do |msg|
      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.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.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.debug(
              "Payment of #{event[:amount]} tokens arrived" \
              "from #{event[:from]} to #{event[:to]} in #{event[:txn]}"
            )
          end
          yield event
        end
      end
    end
    ws.on(:close) do
      verbose do
        log.debug("Disconnected from #{log_url}")
      end
    end
    ws.on(:error) do |e|
      verbose do
        log.debug("Error at #{log_url}: #{e.message}")
      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.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 Etherium may have many balances. One of them is the main balance in ETH crypto. Another balance is the one kept by ERC20 contract in its own ledge 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.debug("Balance of #{address} is #{b} ERC20 tokens")
  b
end

#eth_balance(address) ⇒ Integer

Get ETH balance of a public address.

An address in Etherium 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.debug("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 ERC20 tokens to send

  • limit (Integer)

    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



232
233
234
235
236
237
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
# File 'lib/erc20/wallet.rb', line 232

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.debug("Sent #{amount} ETHs from #{from} to #{address}: #{tnx}")
  tnx.downcase
end

#gas_estimate(from, to, amount) ⇒ Integer

How much gas units is required in order to send ERC20 transaction.

Parameters:

  • from (String)

    The departing address, in hex

  • to (String)

    Arriving address, in hex

  • amount (Integer)

    How many ERC20 tokens to send

Returns:

  • (Integer)

    How many 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.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?

Returns:

  • (Integer)

    Price of gas unit, in gwei (0.000000001 ETH)



168
169
170
171
172
# File 'lib/erc20/wallet.rb', line 168

def gas_price
  gwei = jsonrpc.eth_getBlockByNumber('latest', false)['baseFeePerGas'].to_i(16)
  @log.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.

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



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/erc20/wallet.rb', line 182

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.debug("Sent #{amount} ERC20 tokens from #{from} to #{address}: #{tnx}")
  tnx.downcase
end