Class: ERC20::Wallet
- Inherits:
-
Object
- Object
- ERC20::Wallet
- 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
-
#chain ⇒ Object
readonly
These properties are read-only:.
-
#contract ⇒ Object
readonly
These properties are read-only:.
-
#host ⇒ Object
readonly
These properties are read-only:.
-
#http_path ⇒ Object
readonly
These properties are read-only:.
-
#port ⇒ Object
readonly
These properties are read-only:.
-
#ssl ⇒ Object
readonly
These properties are read-only:.
-
#ws_path ⇒ Object
readonly
These properties are read-only:.
Instance Method Summary collapse
-
#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.
-
#balance(address) ⇒ Integer
Get ERC20 balance of a public address (it’s not the same as ETH balance!).
-
#eth_balance(address) ⇒ Integer
Get ETH balance of a public address.
-
#eth_pay(priv, address, amount, price: gas_price) ⇒ String
Send a single ETH payment from a private address to a public one.
-
#gas_estimate(from, to, amount) ⇒ Integer
How much gas units is required in order to send ERC20 transaction.
-
#gas_price ⇒ Integer
What is the price of gas unit in gwei?.
-
#initialize(contract: USDT, chain: 1, log: $stdout, host: nil, port: 443, http_path: '/', ws_path: '/', ssl: true, proxy: nil) ⇒ Wallet
constructor
Constructor.
-
#pay(priv, address, amount, limit: nil, price: gas_price) ⇒ String
Send a single ERC20 payment from a private address to a public one.
Constructor Details
#initialize(contract: USDT, chain: 1, log: $stdout, host: nil, port: 443, http_path: '/', ws_path: '/', ssl: true, proxy: nil) ⇒ Wallet
Constructor.
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
#chain ⇒ Object (readonly)
These properties are read-only:
64 65 66 |
# File 'lib/erc20/wallet.rb', line 64 def chain @chain end |
#contract ⇒ Object (readonly)
These properties are read-only:
64 65 66 |
# File 'lib/erc20/wallet.rb', line 64 def contract @contract end |
#host ⇒ Object (readonly)
These properties are read-only:
64 65 66 |
# File 'lib/erc20/wallet.rb', line 64 def host @host end |
#http_path ⇒ Object (readonly)
These properties are read-only:
64 65 66 |
# File 'lib/erc20/wallet.rb', line 64 def http_path @http_path end |
#port ⇒ Object (readonly)
These properties are read-only:
64 65 66 |
# File 'lib/erc20/wallet.rb', line 64 def port @port end |
#ssl ⇒ Object (readonly)
These properties are read-only:
64 65 66 |
# File 'lib/erc20/wallet.rb', line 64 def ssl @ssl end |
#ws_path ⇒ Object (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.
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.}") 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.
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.
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.
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.
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_price ⇒ Integer
What is the price of gas unit in gwei?
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.
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 |