Etherium ERC20 Manipulations in Ruby
This small Ruby gem makes manipulations with Etherium tokens as simple as they can be, if you have a provider of JSON-RPC and WebSockets Etherium APIs, for example Infura, GetBlock, or Alchemy:
# Create a wallet:
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
)
# Check how many ERC20 tokens are on the given address:
usdt = w.balance(address)
# Send a few ERC20 tokens to someone and get transaction hash:
hex = w.pay(private_key, to_address, amount)
# Stay waiting, and trigger the block when new ERC20 payments show up:
addresses = ['0x...', '0x...'] # only wait for payments to these addresses
w.accept(addresses) do |event|
puts event[:txn] # 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
It's also possible to check ETH balance and send ETH transaction:
# Check how many ETHs are there on the given address:
eth = w.eth_balance(address)
# Send a few ETHs to someone and get transaction hash:
hex = w.eth_pay(private_key, to_address, amount)
To check the price of a gas unit and the expected cost of a payment:
# How many gas units required to send this payment:
units = w.gas_estimate(from, to, amount)
# What is the price of a gas unit, in gwei:
gwei = w.gas_price
To generate a new private key, use eth:
require 'eth'
key = Eth::Key.new.private_hex
To convert a private key to a public address:
public_hex = Eth::Key.new(priv: key).address
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!
)
You can use squid-proxy image to set up your own HTTP proxy server.
Of course, this library works with Polygon, Optimism, and other forks of Etherium.
How to use in tests
You can use ERC20::FakeWallet
class that behaves exactly like
ERC20::Wallet
, but doesn't make any network connections to the provider.
Also, it remembers all requests that were sent to it:
require 'erc20'
w = ERC20::FakeWallet.new
w.pay(priv, address, 42_000)
assert w.history.include?({ method: :pay, priv:, address:, amount: 42_000 })
How to contribute
Read these guidelines. Make sure you build is green before you contribute your pull request. You will need to have Ruby 3.2+ and Bundler installed. Then:
bundle update
bundle exec rake
If it's clean and you don't see any error messages, submit your pull request.