zapchain
v2.0.0
Published
Event-driven wallet automation plugin for Web3.js v4 - Create programmable rules to automate blockchain interactions
Maintainers
Readme
ZapChain
Automated wallet interactions for Web3.js v4
Create programmable rules to automate blockchain interactions based on periodic state checks
🚀 Features
- ⚡ Automated Execution - Reliable task execution based on state changes
- 🔗 Multi-Chain Support - Works on Ethereum, Polygon, Arbitrum, Optimism, and Sepolia
- 🛡️ Built-in Security - Internal transaction stimulation, execution caps, and emergency kill-switch
- 🎯 4 Condition Types - Balance, token transfers, gas price, and time-based triggers
- 🔧 2 Action Types - Webhooks and smart contract calls
- 🔌 Web3.js v4 Plugin - Seamless integration with your existing Web3 stack
📦 Installation
npm install zapchain web3@^4.0.0⚡ Quick Start
import { Web3 } from 'web3';
import { ZapChainPlugin } from 'zapchain';
// Initialize Web3 with your provider
const web3 = new Web3('YOUR_RPC_URL');
// Register ZapChain plugin
const zapChain = new ZapChainPlugin();
web3.registerPlugin(zapChain);
await zapChain.init(); // Starts the polling service (12s interval)
// Create an automation rule
const ruleId = await zapChain.createRule({
name: 'Auto-stake when balance exceeds 2 ETH',
chain: 1, // Ethereum
enabled: true,
conditions: [{
type: 'balance',
operator: '>',
value: web3.utils.toWei('2', 'ether')
}],
actions: [{
type: 'contract_call',
contractAddress: '0xYourStakingContract',
abi: [...],
functionName: 'stake',
args: [],
value: web3.utils.toWei('1', 'ether')
}],
config: {
requireSignature: true,
simulateFirst: true,
cooldownSeconds: 3600
}
});
console.log(`Rule created: ${ruleId}`);📚 Core Concepts
Conditions
Define when your rule should trigger:
| Type | Description | Example |
|------|-------------|---------|
| balance | Native or ERC20 token balances | Balance > 1 ETH |
| token_transfer | Incoming/outgoing token transfers | Received USDC >= $100 |
| gas_price | Current gas price thresholds | Gas < 20 gwei |
| scheduled | Time-based triggers | Every 24 hours |
Actions
Define what happens when conditions are met:
| Type | Description | Use Case |
|------|-------------|----------|
| notification | HTTP POST webhook | Alerts, logging, integration |
| contract_call | Execute smart contract function | Stake, claim, swap, etc. |
Security Features
- 🔒 Internal Simulation - Validates via eth_call before broadcasting
- 📊 Execution Caps - Limit max executions and cooldowns
- 🛑 Kill Switch - Emergency stop all automation
- ✍️ Rule Signing - Cryptographic authorization
🎯 Use Cases
1. Auto-Staking
Automatically stake tokens when balance exceeds threshold:
await zapChain.createRule({
name: 'Auto-stake excess ETH',
conditions: [{
type: 'balance',
operator: '>',
value: web3.utils.toWei('2', 'ether')
}],
actions: [{
type: 'contract_call',
contractAddress: STAKING_CONTRACT,
functionName: 'stake',
value: web3.utils.toWei('1', 'ether')
}]
});2. Low Gas Execution
Execute transactions only when gas is cheap:
await zapChain.createRule({
name: 'Execute when gas < 20 gwei',
conditions: [{
type: 'gas_price',
operator: '<',
value: '20' // gwei
}],
actions: [{
type: 'contract_call',
functionName: 'claimRewards'
}]
});3. Token Alerts
Get notified when receiving tokens:
await zapChain.createRule({
name: 'USDC received alert',
conditions: [{
type: 'token_transfer',
direction: 'received',
tokenAddress: USDC_ADDRESS,
minAmount: '100000000' // $100 USDC
}],
actions: [{
type: 'notification',
webhookUrl: 'https://your-app.com/webhook',
payload: { event: 'usdc_received' }
}]
});4. Scheduled Tasks
Daily rewards claiming:
await zapChain.createRule({
name: 'Daily rewards claim',
conditions: [{
type: 'scheduled',
intervalSeconds: 86400 // 24 hours
}],
actions: [{
type: 'contract_call',
functionName: 'claimRewards'
}]
});🔧 API Reference
Plugin Methods
init(): Promise<void>
Initialize the plugin and start monitoring.
createRule(rule: Partial<RuleDefinition>): Promise<string>
Create a new automation rule. Returns rule ID.
enableRule(ruleId: string): Promise<void>
Enable a disabled rule.
disableRule(ruleId: string): Promise<void>
Temporarily disable a rule.
deleteRule(ruleId: string): Promise<void>
Permanently delete a rule.
listRules(): Promise<RuleInfo[]>
Get all rules with their status.
getRule(ruleId: string): Promise<RuleDefinition | undefined>
Get detailed rule information.
getExecutionLogs(ruleId?: string): ExecutionLog[]
View execution history.
setKillSwitch(enabled: boolean): Promise<void>
Emergency stop/resume all automation.
Configuration Options
new ZapChainPlugin({
storage: new InMemoryStorage(), // or LocalStorageAdapter()
enableLogging: true
})🛡️ Security Best Practices
- Always simulate first - Enable
simulateFirst: true - Use execution caps - Set
maxExecutionsandcooldownSeconds - Require signatures - Enable
requireSignature: truefor sensitive operations - Test on testnet - Validate rules on Sepolia before mainnet
- Monitor execution logs - Review
getExecutionLogs()regularly - Keep kill-switch ready - Know how to call
setKillSwitch(true)
🌐 Supported Networks
| Network | Chain ID | Status | |---------|----------|--------| | Ethereum | 1 | ✅ Supported | | Polygon | 137 | ✅ Supported | | Arbitrum | 42161 | ✅ Supported | | Optimism | 10 | ✅ Supported | | Sepolia | 11155111 | ✅ Supported |
📖 Complete Examples
See the examples/ directory for:
basic-usage.ts- Getting startedrule-1-stake-excess.ts- Auto-stakingrule-2-gas-price.ts- Gas-optimized executionrule-3-token-received.ts- Token transfer monitoringrule-4-scheduled.ts- Time-based automation
🧪 Testing
# Run unit tests
npm test
# Run with coverage
npm run test:coverage
# Test on Sepolia testnet
cp .env.example .env
# Add your Alchemy API key and wallet address
npx ts-node test-sepolia.ts🤝 Contributing
Contributions welcome! Please read CONTRIBUTING.md first.
📝 License
MIT © ZapChain Contributors
🔗 Links
- Documentation: Full API Docs
- Examples: Usage Examples
- Issues: GitHub Issues
- Discord: Join Community
⚠️ Disclaimer
This software is provided "as is" without warranty. Use at your own risk. Always test thoroughly on testnets before using with real funds.
Made with ❤️ for the Web3 community
