Ethers Flow
Enhanced blockchain interaction using Ethers.js for EVM-compatible chains.
How to Use
Input Requirements
To interact with smart contracts, you need:
- Contract Address: The smart contract you want to interact with
- Message: Natural language description of what you want to do
- Private Key: Your wallet private key (for transactions)
- RPC URL: Blockchain network endpoint
Input Format
Send natural language messages describing blockchain operations:
Example inputs:"Check USDC balance of 0x742d35Cc..."
"Transfer 100 USDC to 0x1234567..."
"Approve Uniswap to spend 1000 USDC"
"Swap 1 ETH for USDC on Uniswap"
"Deploy ERC20 token with name MyToken"
Output Format
Returns structured data including:
- Transaction Hash: For write operations
- Transaction Status: Success/failure with details
- Gas Used: Gas consumption information
- Return Values: For read operations (balances, data, etc.)
- Error Messages: If operation fails
Example Usage
Check Token Balance
Input: "Check USDC balance of 0x742d35Cc6634C0532925a3b8D65f68dF15D4E5b7"
Required Variables:
{
"contractAddress": "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a",
"operation": "read"
}
Output:
{
"balance": "1500.50",
"decimals": 6,
"symbol": "USDC",
"status": "success"
}
Transfer Tokens
Input: "Transfer 100 USDC to 0x1234567890123456789012345678901234567890"
Required Variables:
{
"contractAddress": "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a",
"operation": "write"
}
Output:
{
"transactionHash": "0xabc123...",
"status": "confirmed",
"gasUsed": "65000",
"blockNumber": 18500000
}
DeFi Operations
Input: "Swap 1 ETH for USDC on Uniswap with 0.5% slippage"
Required Variables:
{
"contractAddress": "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D",
"tokenIn": "0x0000000000000000000000000000000000000000",
"tokenOut": "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a",
"amountIn": "1000000000000000000",
"slippage": 0.5,
"operation": "write"
}
Output:
{
"transactionHash": "0xdef456...",
"amountOut": "2450.30",
"status": "confirmed",
"gasUsed": "150000"
}
Use Cases
- DeFi Operations: Swapping, lending, yield farming
- Token Management: Transfers, approvals, balance checks
- Smart Contract Interaction: Call any contract function
- Transaction Monitoring: Track transaction status
- Portfolio Management: Monitor and manage crypto holdings
Technical Details
Overview
The Ethers Flow provides powerful blockchain interaction capabilities using ethers.js with AI-powered function selection. It enables natural language smart contract interactions, transaction monitoring, and automated DeFi operations within the SkynetXBT framework.
Features
- Natural Language Interface: Interact with smart contracts using plain English
- AI-Powered Function Selection: Automatically selects appropriate contract functions
- Multi-Chain Support: Works with any EVM-compatible blockchain
- Transaction Monitoring: Real-time transaction status tracking
- Gas Optimization: Automatic gas estimation and optimization
- Contract Deployment: Deploy contracts programmatically
- Event Listening: Monitor contract events in real-time
- Batch Operations: Execute multiple transactions efficiently
Installation
npm install @skynetxbt/flow-ethers
Dependencies
@skynetxbt/core
- Core framework functionalityethers
- Ethereum JavaScript library@skynetxbt/plugin-llm
- AI-powered function selection
Configuration
Environment Variables
# Required
AGENT_PRIVATE_KEY=your_private_key_here
RPC_URL=https://mainnet.infura.io/v3/your_key
# Optional
CHAIN_ID=1
GAS_LIMIT=500000
GAS_PRICE_MULTIPLIER=1.1
CONFIRMATION_BLOCKS=1
Basic Setup
import { EthersFlow } from "@skynetxbt/flow-ethers";
const ethersFlow = new EthersFlow({
privateKey: process.env.AGENT_PRIVATE_KEY!,
rpcUrl: process.env.RPC_URL!,
chainId: 1, // Ethereum mainnet
gasLimit: 500000,
gasPriceMultiplier: 1.1
});
Advanced Usage Examples
Basic Contract Interaction
const result = await ethersFlow.execute({
agentId: { generation: 0, familyCode: "defi", serialNumber: "001" },
userPublicKey: "user123",
message: "Check USDC balance of 0x742d35Cc6634C0532925a3b8D65f68dF15D4E5b7",
variables: {
contractAddress: "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a", // USDC
operation: "read"
}
});
Natural Language Transactions
// Transfer tokens
await ethersFlow.execute({
agentId: { generation: 0, familyCode: "transfer", serialNumber: "001" },
userPublicKey: "user123",
message: "Transfer 100 USDC to 0x1234567890123456789012345678901234567890",
variables: {
contractAddress: "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a",
operation: "write"
}
});
// Approve token spending
await ethersFlow.execute({
agentId: { generation: 0, familyCode: "approve", serialNumber: "001" },
userPublicKey: "user123",
message: "Approve Uniswap router to spend 1000 USDC",
variables: {
contractAddress: "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a",
spenderAddress: "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D",
operation: "write"
}
});
Configuration Options
EthersConfig Interface
interface EthersConfig {
privateKey: string; // Private key for transactions
rpcUrl: string; // RPC endpoint URL
chainId?: number; // Chain ID (default: 1)
gasLimit?: number; // Default gas limit
gasPriceMultiplier?: number; // Gas price multiplier
confirmationBlocks?: number; // Blocks to wait for confirmation
timeout?: number; // Transaction timeout (ms)
retryAttempts?: number; // Number of retry attempts
customContracts?: ContractConfig[]; // Custom contract configurations
}
interface ContractConfig {
address: string;
abi: any[];
name: string;
description?: string;
}
Advanced Features
Contract Deployment
await ethersFlow.execute({
agentId: { generation: 0, familyCode: "deploy", serialNumber: "001" },
userPublicKey: "deployer123",
message: "Deploy ERC20 token with name 'MyToken', symbol 'MTK', and 1M supply",
variables: {
operation: "deploy",
contractType: "ERC20",
constructorArgs: ["MyToken", "MTK", "1000000000000000000000000"],
bytecode: "0x608060405234801561001057600080fd5b50..." // Contract bytecode
}
});
Event Monitoring
await ethersFlow.execute({
agentId: { generation: 0, familyCode: "monitor", serialNumber: "001" },
userPublicKey: "monitor123",
message: "Monitor Transfer events on USDC contract",
variables: {
contractAddress: "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a",
eventName: "Transfer",
operation: "listen",
filters: {
from: "0x742d35Cc6634C0532925a3b8D65f68dF15D4E5b7"
}
}
});
Batch Transactions
await ethersFlow.execute({
agentId: { generation: 0, familyCode: "batch", serialNumber: "001" },
userPublicKey: "user123",
message: "Execute batch: approve USDC, then swap on Uniswap",
variables: {
operation: "batch",
transactions: [
{
contractAddress: "0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a",
functionName: "approve",
args: ["0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", "1000000000"]
},
{
contractAddress: "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D",
functionName: "swapExactTokensForTokens",
args: ["1000000000", "950000000", ["0xA0b86a33E6441c8C9b4b3d0c7d2b3b1f1d1e1f1a", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"], "0x742d35Cc6634C0532925a3b8D65f68dF15D4E5b7", "1700000000"]
}
]
}
});
AI-Powered Function Selection
The flow uses AI to automatically select the appropriate contract function based on natural language input:
// AI interprets these messages and selects correct functions:
"Check my USDC balance"
// → balanceOf(address)
"Transfer 100 tokens to Alice"
// → transfer(address, uint256)
"Approve Uniswap to spend my tokens"
// → approve(address, uint256)
"Swap ETH for USDC"
// → swapExactETHForTokens(...) or similar Uniswap function
"Stake 1000 tokens in the pool"
// → stake(uint256) or deposit(uint256)
Integration Examples
With General Agent Flow
import { LLMAgentFlow } from "@skynetxbt/flow-llm-agent";
const aiAgent = new LLMAgentFlow(config);
const ethersFlow = new EthersFlow(config);
// AI analyzes user intent, then executes blockchain operation
async function handleDeFiRequest(userMessage: string) {
// Get AI analysis
const analysis = await aiAgent.execute({
agentId: { generation: 0, familyCode: "analysis", serialNumber: "001" },
userPublicKey: "user123",
message: `Analyze this DeFi request: "${userMessage}"`,
variables: {}
});
// Execute blockchain operation
const result = await ethersFlow.execute({
agentId: { generation: 0, familyCode: "defi", serialNumber: "001" },
userPublicKey: "user123",
message: userMessage,
variables: { analysis }
});
return result;
}
With Telegram Flow
import { TelegramFlow } from "@skynetxbt/flow-telegram";
const telegramFlow = new TelegramFlow(config);
// Send transaction notifications via Telegram
async function notifyTransaction(txHash: string, operation: string) {
const message = `
✅ *Transaction Confirmed*
Operation: ${operation}
Hash: \`${txHash}\`
Status: Confirmed
[View on Etherscan](https://etherscan.io/tx/${txHash})
`;
await telegramFlow.execute({
agentId: { generation: 0, familyCode: "notification", serialNumber: "001" },
userPublicKey: "notifications",
message: message,
variables: {
broadcast: true,
messageType: "markdown"
}
});
}
Error Handling
try {
const result = await ethersFlow.execute(context);
console.log('Transaction successful:', result);
} catch (error) {
if (error.code === 'INSUFFICIENT_FUNDS') {
console.error('Insufficient balance for transaction');
} else if (error.code === 'NETWORK_ERROR') {
console.error('Network connection failed');
} else if (error.code === 'CONTRACT_ERROR') {
console.error('Smart contract execution failed:', error.reason);
} else if (error.code === 'GAS_ESTIMATION_FAILED') {
console.error('Could not estimate gas for transaction');
} else {
console.error('Unexpected error:', error.message);
}
}
Security Best Practices
1. Private Key Management
// Use environment variables
const privateKey = process.env.AGENT_PRIVATE_KEY;
// Never log private keys
console.log('Using wallet:', wallet.address); // ✅ Safe
console.log('Private key:', privateKey); // ❌ Never do this
2. Transaction Validation
// Validate transaction parameters before execution
function validateTransaction(to: string, value: string, data: string) {
if (!ethers.utils.isAddress(to)) {
throw new Error('Invalid recipient address');
}
if (BigNumber.from(value).lt(0)) {
throw new Error('Invalid transaction value');
}
// Additional validation logic
}
Performance Optimization
1. Connection Pooling
// Reuse provider connections
const providers = new Map<string, ethers.providers.JsonRpcProvider>();
function getProvider(rpcUrl: string): ethers.providers.JsonRpcProvider {
if (!providers.has(rpcUrl)) {
providers.set(rpcUrl, new ethers.providers.JsonRpcProvider(rpcUrl));
}
return providers.get(rpcUrl)!;
}
2. Contract Caching
// Cache contract instances
const contractCache = new Map<string, ethers.Contract>();
function getContract(address: string, abi: any[], provider: any): ethers.Contract {
const key = `${address}-${provider.connection.url}`;
if (!contractCache.has(key)) {
contractCache.set(key, new ethers.Contract(address, abi, provider));
}
return contractCache.get(key)!;
}
Troubleshooting
Common Issues
Transaction fails with "out of gas"- Increase gas limit
- Check contract logic for infinite loops
- Verify input parameters
- Check wallet balance
- Account for gas costs
- Verify token allowances
- Verify contract ABI
- Check function name spelling
- Ensure contract is deployed
- Check RPC endpoint status
- Verify network connectivity
- Try alternative RPC providers
Getting Help
For specific queries about blockchain interactions or smart contract operations, refer to the Ethers.js documentation or contact support.