Ethereum and ERC20 payment method for the wallet library. Using lib-wallet-indexer-eth and Web3 backend.
This library is part of the Wallet SDK See the module in action here
- π Secure wallet management for Ethereum and ERC20 tokens
- π Transaction syncing and balance tracking
- π Address generation and validation
- πΈ Send and receive transactions
- βΈοΈ Pausable sync process
- π Transaction history retrieval
This module requires an indexer server. See lib-wallet-indexer
// Start with a storage engine
const storeEngine = new WalletStoreHyperbee({
store_path: './db'
})
await storeEngine.init()
// Generate a seed or use a mnemonic phrase
const seed = await BIP39Seed.generate(/** Can enter mnemonic phrase here too */)
// Setting up ERC20 tokens
const USDT = currencyFac({
name: 'USDT',
base_name: 'USDT',
contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
decimal_places: 6
})
// Connect to a provider
const provider = await Provider({
web3: 'localhost:8888', // URI to Web3 provider
indexer: 'localhost:8000/rpc', // URI to lib-wallet-indexer-eth rpc
indexerWs: 'localhost:8000/ws', // URI to lib-wallet-indexer-eth ws
})
// Start provider
await provider.init()
// Start new eth wallet
const ethPay = new EthereumPay({
asset_name: 'eth', // Unique key for the assets
provider, // Ethereum provider
key_manager: , // Handles address generation library from seed
store: storeEngine, // Storage engine for the wallet
tokens: [ // List of tokens that the wallet will support
new ERC20({
currency: USDT
})
]
})
// Start wallet
await ethPay.initialize({})
// Listen to each path that has transactions
ethPay.on('synced-path', (path) => {
// syncing hd path
})
// Parse blockchain for transactions to your wallet
const pay = await ethPay.syncTransactions({
reset: false, // Passing true will resync from scratch
token: "USDT" // Passing token name will sync token transaction
})
// Pause the sync process
await ethPay.pauseSync()
// Get a new address
const { address } = await ethPay.getNewAddress()
// Get token balance
const addrBalance = await ethPay.getBalance({
token: "USDT" // send token name to get balance of token
}, address)
// Get total balance across all addresses
const walletBalance = await ethPay.getBalance({})
// Send ETH to an address
const result = await ethPay.sendTransaction({
address: '0xaaa...', // ETH address of the recipient
amount: '1', // Value of amount
unit: 'main', // unit of amount: main = ETH and base = wei unit
})
// Get a list of transactions
await ethPay.getTransactions({
token : "USDT",
}, (txs) => {
//iterate through entire tx history
})
// Is address a valid Ethereum address?
const isvalid = await ethPay.isValidAddress('0xaaa...')
// Destroy instance of the wallet
await ethPay.destroy()
- Description: Initializes the wallet, setting up the key manager, HD wallet, and state database.
- Return Value: A Promise that resolves when initialization is complete.
- Parameters:
ctx
: Context object for initialization (optional).
Example usage:
await wallet.initialize();
- Description: Generates a new Ethereum address for the wallet.
- Return Value: A Promise that resolves to an object containing the new address details.
Example usage:
const newAddress = await wallet.getNewAddress();
console.log(newAddress); // Output: { address: '0x...', path: 'm/44'/60'/0'/0/0', ... }
- Description: Retrieves the transaction history for the wallet or a specific token.
- Return Value: A Promise that resolves when all transactions have been processed.
- Parameters:
opts
(optional): An object containing options.token
(optional): Name of the token for token transaction history.
fn
: Callback function to handle each block of transactions.
Example usage:
await wallet.getTransactions({}, (block) => {
console.log(block); // Output: Array of transactions in this block
});
- Description: Retrieves the balance of an address or the entire wallet.
- Return Value: A Promise that resolves to a Balance object.
- Parameters:
opts
(optional): An object containing options.token
(optional): Name of the token to get balance for.
addr
(optional): Specific address to get balance for.
Example usage:
const totalBalance = await wallet.getBalance({});
console.log(totalBalance); // Output: Balance object for the entire wallet
const addressBalance = await wallet.getBalance({}, '0x1234...');
console.log(addressBalance); // Output: Balance object for the specific address
const tokenBalance = await wallet.getBalance({ token: 'USDT' });
console.log(tokenBalance); // Output: Balance object for the specified token
- Description: Synchronizes transactions for the wallet, updating balances and transaction history.
- Return Value: A Promise that resolves when synchronization is complete.
- Parameters:
opts
(optional): An object containing options.reset
(optional): If true, resets all state and resyncs.token
(optional): Name of the token to sync transactions for.
Example usage:
await wallet.syncTransactions({ reset: true });
- Description: Sends a transaction from the wallet.
- Return Value: A Promise that resolves when the transaction is confirmed.
- Parameters:
opts
(optional): An object containing options.token
(optional): Name of the token to send.
outgoing
: An object containing transaction details.amount
: Number of units being sent.unit
: Unit of amount ('main' or 'base').address
: Address of the receiver.sender
(optional): Address of the sender.gasLimit
(optional): ETH gas limit.gasPrice
(optional): ETH gas price.
Example usage:
const txPromise = wallet.sendTransaction({}, {
amount: 1,
unit: 'main',
address: '0x5678...'
});
txPromise.broadcasted((tx) => {
console.log('Transaction broadcasted:', tx);
});
const confirmedTx = await txPromise;
console.log('Transaction confirmed:', confirmedTx);
- Description: Checks if the given address is a valid Ethereum address.
- Return Value: A boolean indicating whether the address is valid.
- Parameters:
address
: The Ethereum address to validate.
Example usage:
const isValid = wallet.isValidAddress('0x1234...');
console.log(isValid); // Output: true or false
- Description: Pauses the synchronization process.
- Return Value: A Promise that resolves when synchronization is paused.
Example usage:
await wallet.pauseSync();
- Description: Resumes the synchronization process.
- Return Value: A Promise that resolves when synchronization is resumed.
Example usage:
await wallet.resumeSync();
- Initialize storage engine
- Generate or use existing seed
- Set up ERC20 tokens (if needed)
- Connect to provider
- Create and initialize EthereumPay instance
- Setup local Ethereum Hardhat enviroment
- Clone the repository:
- Install dependencies:
npm install
- Run various tests:
npm run test:pay
- This package includes extensive integration tests.
- We use Brittle for testing.
- Integration tests require an Ethereum node connected to a testnet or local network.
- To set up the testing environment, see: Test tools repo
To run tests, check package.json
for the various test scripts. You can run them using:
npm run test:*