Skip to content

raopremrao/ZapChain

Repository files navigation

ZapChain

Automated wallet interactions for Web3.js v4
Create programmable rules to automate blockchain interactions based on periodic state checks

npm version License: MIT

πŸš€ 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

  1. Always simulate first - Enable simulateFirst: true
  2. Use execution caps - Set maxExecutions and cooldownSeconds
  3. Require signatures - Enable requireSignature: true for sensitive operations
  4. Test on testnet - Validate rules on Sepolia before mainnet
  5. Monitor execution logs - Review getExecutionLogs() regularly
  6. 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 started
  • rule-1-stake-excess.ts - Auto-staking
  • rule-2-gas-price.ts - Gas-optimized execution
  • rule-3-token-received.ts - Token transfer monitoring
  • rule-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

⚠️ 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

About

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages