Examples
Production-ready code snippets for common automation patterns. All examples use real contract addresses and tested configurations.
Basic Setup
Initialize ZapChain with your Web3 instance:
import { Web3 } from 'web3';
import { ZapChainPlugin, LocalStorageAdapter } from 'zapchain';
// Connect to your RPC provider
const web3 = new Web3('wss://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY');
// Initialize with recommended production settings
const zapChain = new ZapChainPlugin({
storage: new LocalStorageAdapter(),
pollInterval: 12000, // 12 seconds (1 block)
enableLogging: true,
useWebSocket: true // v2.0: Real-time block monitoring
});
// Register plugin
web3.registerPlugin(zapChain);
// Initialize and start monitoring
await zapChain.init();
console.log('ZapChain ready');Balance Monitoring
Monitor wallet balances and trigger actions when thresholds are crossed.
Auto-Stake When Balance Exceeds Threshold
Automatically stake ETH to a Lido contract when your wallet balance exceeds 5 ETH:
const LIDO_STETH = '0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84';
const ruleId = await web3.zapChain.createRule({
name: 'Auto-stake to Lido',
conditions: [{
type: 'balance',
operator: '>',
value: web3.utils.toWei('5', 'ether')
}],
actions: [{
type: 'contract_call',
contractAddress: LIDO_STETH,
abi: [{
name: 'submit',
type: 'function',
stateMutability: 'payable',
inputs: [{ name: '_referral', type: 'address' }],
outputs: [{ name: '', type: 'uint256' }]
}],
functionName: 'submit',
args: ['0x0000000000000000000000000000000000000000'],
value: web3.utils.toWei('4', 'ether')
}],
config: {
maxExecutions: 10,
cooldownSeconds: 86400, // 24 hours
simulateFirst: true
}
});
await web3.zapChain.enableRule(ruleId);ERC-20 Token Balance Monitoring
Trigger when your USDC balance exceeds a threshold:
const USDC = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
await web3.zapChain.createRule({
name: 'High USDC balance alert',
conditions: [{
type: 'balance',
tokenAddress: USDC,
operator: '>',
value: '10000000000' // 10,000 USDC (6 decimals)
}],
actions: [{
type: 'notification',
webhookUrl: 'https://your-api.com/alerts',
method: 'POST',
payload: { event: 'high_usdc_balance', threshold: 10000 }
}]
});Native Transfers v2.0
Send ETH directly without contract ABIs. Perfect for auto-sweeping and treasury management.
Auto-Sweep to Cold Wallet
Automatically transfer excess ETH to your cold storage:
const COLD_WALLET = '0xYourColdWalletAddress';
const HOT_WALLET_MIN = web3.utils.toWei('0.5', 'ether');
await web3.zapChain.createRule({
name: 'Auto-sweep to cold storage',
conditions: [{
type: 'balance',
operator: '>',
value: web3.utils.toWei('2', 'ether')
}],
actions: [{
type: 'native_transfer',
to: COLD_WALLET,
value: web3.utils.toWei('1.5', 'ether') // Keep 0.5 ETH for gas
}],
config: {
requireSignature: true,
simulateFirst: true,
maxExecutions: 100,
cooldownSeconds: 3600 // 1 hour minimum between sweeps
}
});Split Payments
Distribute incoming funds to multiple addresses:
await web3.zapChain.createRule({
name: 'Revenue split - 70/30',
conditions: [{
type: 'balance',
operator: '>',
value: web3.utils.toWei('1', 'ether')
}],
actions: [
{
type: 'native_transfer',
to: '0xFounderAddress',
value: web3.utils.toWei('0.7', 'ether')
},
{
type: 'native_transfer',
to: '0xTreasuryAddress',
value: web3.utils.toWei('0.3', 'ether')
}
],
config: { simulateFirst: true }
});Gas Price Optimization
Execute transactions only when gas prices are favorable.
Low Gas Execution
Wait for gas below 25 gwei before executing expensive operations:
const AAVE_POOL = '0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2';
await web3.zapChain.createRule({
name: 'Claim AAVE rewards on low gas',
conditions: [{
type: 'gas_price',
operator: '<',
value: '25' // 25 gwei
}],
actions: [{
type: 'contract_call',
contractAddress: AAVE_POOL,
abi: [{
name: 'claimAllRewards',
type: 'function',
inputs: [
{ name: 'assets', type: 'address[]' },
{ name: 'to', type: 'address' }
],
outputs: [
{ name: 'rewardsList', type: 'address[]' },
{ name: 'claimedAmounts', type: 'uint256[]' }
]
}],
functionName: 'claimAllRewards',
args: [
['0x...'], // Your aToken addresses
'0xYourWallet'
]
}],
config: {
pollInterval: 1000, // Check every second
simulateFirst: true
}
});Webhook Notifications
Send alerts to external services when conditions are met.
Telegram Bot Alert
Send a Telegram message when you receive tokens:
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const CHAT_ID = process.env.TELEGRAM_CHAT_ID;
await web3.zapChain.createRule({
name: 'Telegram payment alert',
conditions: [{
type: 'token_transfer',
direction: 'received',
tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
minAmount: '100000000' // $100
}],
actions: [{
type: 'notification',
webhookUrl: `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`,
method: 'POST',
payload: {
chat_id: CHAT_ID,
text: '💰 Payment received: $100+ USDC',
parse_mode: 'HTML'
}
}]
});Discord Webhook
await web3.zapChain.createRule({
name: 'Discord balance alert',
conditions: [{
type: 'balance',
operator: '<',
value: web3.utils.toWei('0.1', 'ether')
}],
actions: [{
type: 'notification',
webhookUrl: 'https://discord.com/api/webhooks/YOUR_WEBHOOK_ID/YOUR_TOKEN',
method: 'POST',
payload: {
content: '⚠️ Low ETH balance alert!',
embeds: [{
title: 'Wallet Balance Low',
description: 'Balance dropped below 0.1 ETH',
color: 16711680 // Red
}]
}
}]
});Scheduled Tasks
Execute actions at fixed time intervals.
Daily Reward Claim
await web3.zapChain.createRule({
name: 'Daily staking rewards',
conditions: [{
type: 'scheduled',
intervalSeconds: 86400 // 24 hours
}],
actions: [{
type: 'contract_call',
contractAddress: '0xStakingContract',
abi: [{
name: 'claimRewards',
type: 'function',
inputs: [],
outputs: []
}],
functionName: 'claimRewards',
args: []
}],
config: {
simulateFirst: true,
maxExecutions: 365 // Run for 1 year max
}
});Advanced Patterns
Debugging with Execution Logs
Check why rules aren't executing using the verbose logging system:
// Get all execution logs
const logs = web3.zapChain.getExecutionLogs();
// Filter for skipped executions
const skipped = logs.filter(log => log.status === 'SKIPPED');
skipped.forEach(log => {
console.log(`Rule "${log.ruleName}" skipped: ${log.skipReason}`);
// Possible reasons:
// - KILL_SWITCH_ACTIVE
// - COOLDOWN_ACTIVE
// - MAX_EXECUTIONS_REACHED
// - SIGNATURE_INVALID
// - SIMULATION_FAILED
// - CONDITIONS_NOT_MET
});Emergency Stop
// Pause all automation immediately
await web3.zapChain.setKillSwitch(true);
// Check status
console.log('Kill switch active:', web3.zapChain.isKillSwitchActive());
// Resume when ready
await web3.zapChain.setKillSwitch(false);Rule Simulation Before Enabling
// Create rule but don't enable yet
const ruleId = await web3.zapChain.createRule({
name: 'Test rule',
// ... conditions and actions
});
// Simulate to check for errors
const result = await web3.zapChain.simulateRule(ruleId);
if (result.success) {
console.log('Estimated gas:', result.gasEstimate);
await web3.zapChain.enableRule(ruleId);
} else {
console.error('Simulation failed:', result.error);
await web3.zapChain.deleteRule(ruleId);
}