web3-funds-collector
v1.0.0
Published
Web3 Ethereum library for automated ERC20 token transfers with intelligent gas management
Maintainers
Readme
Fund Centralizing
A professional Web3 Ethereum library for automated ERC20 token transfers with intelligent gas management. Built following SOLID principles for enterprise-grade reliability.
🎯 Purpose
This library solves the common problem of transferring ERC20 tokens from wallets that lack native currency (ETH, MATIC, BNB, etc.) for gas fees. It automatically handles gas funding from a dedicated gas wallet before executing token transfers.
✨ Features
- Automatic Gas Management: Transfers 1.5x of estimated gas to handle network traffic variations
- Developer-Defined Networks: Complete control over RPC endpoints and network configurations
- Smart Gas Detection: Skips gas transfer if source wallet already has sufficient balance
- ERC20 Token Support: Complete ERC20 token operations (transfer, balance checks, token info)
- SOLID Architecture: Clean, maintainable code following best practices
- Type-Safe: Built with ethers.js for reliable blockchain interactions
- Detailed Logging: Real-time progress updates during operations
📦 Installation
npm install fund-centralizing🚀 Quick Start
const FundCentralizing = require('fund-centralizing');
// Initialize with your network configuration
const fundManager = new FundCentralizing({
network: {
chainId: 137,
name: 'Polygon Mainnet',
rpcUrl: 'https://polygon-rpc.com', // Your RPC endpoint
nativeCurrency: {
name: 'MATIC',
symbol: 'MATIC',
decimals: 18
}
},
sourcePrivateKey: process.env.SOURCE_PRIVATE_KEY, // Wallet with tokens
gasWalletPrivateKey: process.env.GAS_WALLET_PRIVATE_KEY // Wallet with native coins
});
// Transfer tokens
const result = await fundManager.transferToken({
tokenAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174', // USDC on Polygon
destinationAddress: '0xRecipientAddress',
amount: '100' // 100 USDC
});
console.log('Transfer successful!', result);🔧 Configuration
Network Configuration (Required)
Developers must provide complete network configuration:
{
network: {
chainId: 137, // Network chain ID
name: 'Polygon Mainnet', // Network name
rpcUrl: 'https://your-rpc.com', // Your RPC endpoint
nativeCurrency: {
name: 'MATIC', // Native currency name
symbol: 'MATIC', // Native currency symbol
decimals: 18 // Native currency decimals
}
},
sourcePrivateKey: '0x...', // Source wallet private key
gasWalletPrivateKey: '0x...' // Gas wallet private key
}Using Example Network Configs
For convenience, the library provides example configurations:
const fundManager = new FundCentralizing({
network: FundCentralizing.EXAMPLE_NETWORKS.polygon,
sourcePrivateKey: process.env.SOURCE_PRIVATE_KEY,
gasWalletPrivateKey: process.env.GAS_WALLET_PRIVATE_KEY
});Available Example Networks:
FundCentralizing.EXAMPLE_NETWORKS.ethereum- Ethereum MainnetFundCentralizing.EXAMPLE_NETWORKS.polygon- Polygon MainnetFundCentralizing.EXAMPLE_NETWORKS.bsc- BSC MainnetFundCentralizing.EXAMPLE_NETWORKS.arbitrum- Arbitrum OneFundCentralizing.EXAMPLE_NETWORKS.optimism- Optimism MainnetFundCentralizing.EXAMPLE_NETWORKS.avalanche- Avalanche C-Chain
Environment Variables
Create a .env file:
SOURCE_PRIVATE_KEY=0xyour_source_wallet_private_key
GAS_WALLET_PRIVATE_KEY=0xyour_gas_wallet_private_key
TOKEN_ADDRESS=0xTokenContractAddress
DESTINATION_ADDRESS=0xRecipientAddress
TRANSFER_AMOUNT=100📚 API Reference
transferToken(config)
Main method to transfer ERC20 tokens with automatic gas management.
Parameters:
tokenAddress(string): ERC20 token contract addressdestinationAddress(string): Recipient wallet addressamount(string): Amount to transfer in token units (e.g., "100" for 100 USDC)
Returns: Promise with transfer details
Example:
const result = await fundManager.transferToken({
tokenAddress: '0x...',
destinationAddress: '0x...',
amount: '100'
});Gas Buffer: The library automatically transfers 1.5x of the estimated gas cost to handle network traffic fluctuations.
getTokenBalance(tokenAddress, walletAddress)
Get ERC20 token balance for any address.
const balance = await fundManager.getTokenBalance(
'0xTokenAddress',
'0xWalletAddress'
);
console.log(balance.balanceFormatted); // "100.50"
console.log(balance.symbol); // "USDC"getNativeBalance(walletAddress)
Get native currency balance (ETH, MATIC, BNB, etc.) for any address.
const balance = await fundManager.getNativeBalance('0xWalletAddress');
console.log(balance); // "1.234567890123456789"getWalletAddresses()
Get configured wallet addresses and network info.
const info = fundManager.getWalletAddresses();
// {
// sourceWallet: '0x...',
// gasWallet: '0x...',
// network: {
// name: 'Polygon Mainnet',
// chainId: 137,
// rpcUrl: 'https://...'
// }
// }Static Property: EXAMPLE_NETWORKS
Access pre-configured example network configurations.
const networks = FundCentralizing.EXAMPLE_NETWORKS;
// {
// ethereum: { chainId: 1, name: 'Ethereum Mainnet', ... },
// polygon: { chainId: 137, name: 'Polygon Mainnet', ... },
// bsc: { chainId: 56, name: 'BSC Mainnet', ... },
// ...
// }🌐 Network Configuration Examples
Ethereum Mainnet
{
chainId: 1,
name: 'Ethereum Mainnet',
rpcUrl: 'https://eth.llamarpc.com',
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }
}Polygon Mainnet
{
chainId: 137,
name: 'Polygon Mainnet',
rpcUrl: 'https://polygon-rpc.com',
nativeCurrency: { name: 'MATIC', symbol: 'MATIC', decimals: 18 }
}BSC Mainnet
{
chainId: 56,
name: 'BSC Mainnet',
rpcUrl: 'https://bsc-dataseed1.binance.org',
nativeCurrency: { name: 'BNB', symbol: 'BNB', decimals: 18 }
}Custom/Testnet
{
chainId: 80001,
name: 'Polygon Mumbai Testnet',
rpcUrl: 'https://rpc-mumbai.maticvigil.com',
nativeCurrency: { name: 'MATIC', symbol: 'MATIC', decimals: 18 }
}🏗️ Architecture
The library follows SOLID principles:
Single Responsibility: Each service handles one specific concern
WalletManager: Wallet creation and managementTokenService: ERC20 token operationsGasEstimator: Gas estimation and calculationTransactionService: Transaction execution
Open/Closed: Easy to extend with any network configuration
Dependency Injection: Services are injected for testability
Interface Segregation: Focused, minimal interfaces
📖 Complete Examples
Example 1: Basic Transfer on Polygon
const FundCentralizing = require('fund-centralizing');
const fundManager = new FundCentralizing({
network: {
chainId: 137,
name: 'Polygon Mainnet',
rpcUrl: 'https://polygon-rpc.com',
nativeCurrency: { name: 'MATIC', symbol: 'MATIC', decimals: 18 }
},
sourcePrivateKey: process.env.SOURCE_PRIVATE_KEY,
gasWalletPrivateKey: process.env.GAS_WALLET_PRIVATE_KEY
});
const result = await fundManager.transferToken({
tokenAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174', // USDC
destinationAddress: '0xRecipientAddress',
amount: '100'
});Example 2: Using Example Networks
const fundManager = new FundCentralizing({
network: FundCentralizing.EXAMPLE_NETWORKS.ethereum,
sourcePrivateKey: process.env.SOURCE_PRIVATE_KEY,
gasWalletPrivateKey: process.env.GAS_WALLET_PRIVATE_KEY
});Example 3: Custom RPC Endpoint
const fundManager = new FundCentralizing({
network: {
chainId: 137,
name: 'Polygon Mainnet',
rpcUrl: 'https://my-custom-rpc.com/polygon', // Your private RPC
nativeCurrency: { name: 'MATIC', symbol: 'MATIC', decimals: 18 }
},
sourcePrivateKey: process.env.SOURCE_PRIVATE_KEY,
gasWalletPrivateKey: process.env.GAS_WALLET_PRIVATE_KEY
});Example 4: Check Balances Before Transfer
// Get wallet info
const info = fundManager.getWalletAddresses();
console.log('Network:', info.network.name);
console.log('Source:', info.sourceWallet);
// Check token balance
const tokenBal = await fundManager.getTokenBalance(
'0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174',
info.sourceWallet
);
console.log(`Token: ${tokenBal.balanceFormatted} ${tokenBal.symbol}`);
// Check native balance
const nativeBal = await fundManager.getNativeBalance(info.sourceWallet);
console.log(`Native: ${nativeBal} MATIC`);🔒 Security
- Never commit private keys to version control
- Use environment variables for sensitive data
- Keep
.envfile in.gitignore - Use hardware wallets or secure key management in production
🐛 Error Handling
The library provides detailed error messages:
try {
await fundManager.transferToken({...});
} catch (error) {
console.error('Transfer failed:', error.message);
// Handle specific errors
}📝 Process Flow
- Initialize with network config and wallet private keys
- Validate configuration and token parameters
- Fetch token information (decimals, symbol, name)
- Check source wallet token balance
- Estimate gas required for token transfer
- Check if source wallet has sufficient gas
- If insufficient gas:
- Transfer 1.5x estimated gas from gas wallet to source wallet
- 50% buffer accounts for network traffic fluctuations
- If sufficient gas: Skip gas transfer
- Execute token transfer from source to destination
- Return detailed results with transaction hashes
⚡ Gas Management
The library uses a 1.5x gas buffer strategy:
- Base Estimation: Calculates exact gas needed for ERC20 transfer
- Buffer Applied: Transfers 150% of estimated amount
- Why 1.5x?: Protects against gas price spikes during network congestion
- Leftover Gas: Remains in source wallet for future transactions
Example:
Estimated gas cost: 0.001 ETH
Amount transferred: 0.0015 ETH (1.5x buffer)
Buffer protection: 0.0005 ETH extra for price fluctuations🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
ISC
🔗 Resources
📧 Support
For issues and questions, please open an issue on GitHub.
