Ethereum ERC20 Manipulations in Ruby


This small Ruby gem
makes manipulations with Ethereum ERC20 tokens
as simple as possible, when you have a provider of
JSON-RPC and WebSockets Ethereum APIs, such as
Infura, GetBlock, or Alchemy.
Install it like this:
gem install erc20
Or simply add this to your Gemfile:
gem 'erc20'
Then, make an instance of the main class and use to read
balances, send and receive payments:
require 'erc20'
w = ERC20::Wallet.new(
contract: ERC20::Wallet.USDT,
host: 'mainnet.infura.io',
http_path: '/v3/<your-infura-key>',
ws_path: '/ws/v3/<your-infura-key>',
log: $stdout
)
usdt = w.balance(address)
hex = w.pay(private_key, to_address, amount)
addresses = ['0x...', '0x...']
w.accept(addresses) do |event|
puts event[:txn]
puts event[:amount]
puts event[:from]
puts event[:to]
end
You can also check ETH balance and send ETH transactions:
eth = w.eth_balance(address)
hex = w.eth_pay(private_key, to_address, amount)
To check the price of a gas unit and the expected cost of a payment:
units = w.gas_estimate(from, to, amount)
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:swordfish@example.com:3128'
)
You can use squid-proxy Docker image to set up your own HTTP proxy server.
Of course, this library works with Polygon, Optimism,
and other EVM compatible blockchains.
How to use in command line
This gem also provides a command line tool for sending ETH and ERC20 payments
and checking balances.
First, you install it, via gem:
gem install erc20
Then, run it:
erc20 --help
Usage should be straightforward. If you have questions, please submit an issue.
How to use in tests
You can use the ERC20::FakeWallet class that behaves exactly like
ERC20::Wallet, but doesn't make any network connections to the provider.
Additionally, it records all requests 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 your 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.