Workers Reference
Detailed documentation for each Cloudflare Worker in the LazaiTrader system.
Worker Overview
| Worker | Type | Trigger | Purpose |
|---|---|---|---|
| lt_tg | HTTP | Telegram Webhook | Main bot interface |
| lt_tg_start | HTTP | Service Binding | User registration |
| lt_tg_deposit | HTTP | Service Binding | SCW deployment |
| lt_tg_withdrawal | HTTP | Service Binding | Token withdrawals |
| lt_tg_balance | HTTP | Service Binding | Balance fetching |
| lt_tg_chart | HTTP | Service Binding | Chart generation |
| lt_trader_queue | Cron | Every 1 minute | Price monitoring |
| lt_trader_execute | Queue | Queue messages | Trade execution |
| lt_balance_tracker | Cron | Every 5 minutes | Balance tracking |
lt_tg (Main Bot)
Purpose
Entry point for all Telegram interactions. Routes commands to appropriate handlers and microservices.
Files
lt_tg/
├── worker.js # Main entry point
├── helper.strategyhandlers.js # Strategy management
├── helper.withdrawalhandlers.js # Withdrawal UI
├── wrangler.toml # Configuration
└── package.json
Bindings
# D1 Database
[[d1_databases]]
binding = "DB"
# Service Bindings
[[services]]
binding = "START_WORKER"
service = "lt-tg-start"
[[services]]
binding = "DEPOSIT_WORKER"
service = "lt-tg-deposit"
# ... more services
Key Functions
// Handle incoming Telegram updates
async fetch(request, env) {
const update = await request.json();
if (update.message) {
await handleMessage(update.message, env);
}
}
// Route commands
async function handleMessage(message, env) {
const command = message.text.split(' ')[0];
switch(command) {
case '/start': return handleStart(message, env);
case '/balance': return handleBalance(message, env);
// ...
}
}
lt_tg_start (Registration)
Purpose
Handles user registration flow and wallet verification.
Input
{
"action": "start | verify_wallet",
"chatId": 123456789,
"userId": 123456789,
"username": "telegram_username",
"text": "0x..." // for verify_wallet
}
Output
{
"success": true,
"registered": true,
"awaiting": "wallet" // if awaiting input
}
Flow
- Check if user exists
- If new, create registration session
- Validate wallet address
- Create user record
- Return success
lt_tg_deposit (SCW Deployment)
Purpose
Deploys Smart Contract Wallets using deterministic CREATE2.
Input
{
"userId": 123456789,
"userWallet": "0x..."
}
Output
{
"success": true,
"scwAddress": "0x...",
"deployments": [
{
"chainId": 1088,
"chainName": "Metis",
"status": "deployed",
"txHash": "0x..."
}
]
}
Flow
- Check if user already has SCW
- If exists, return existing address
- Deploy SCW on all active chains
- Record in SCWDeployments
- Update Users.SCWAddress
lt_tg_withdrawal (Withdrawals)
Purpose
Executes withdrawals from SCW to user's EOA.
Input
{
"userId": 123456789,
"userWallet": "0x...",
"scwAddress": "0x...",
"tokenAddress": "0x...",
"chainId": 1088,
"rpcUrl": "https://..."
}
Output
{
"success": true,
"txHash": "0x...",
"amount": "100.0",
"token": "USDC"
}
Flow
- Connect to blockchain
- Call SCW.withdrawAllTokens()
- Wait for confirmation
- Record in Withdrawals table
- Return result
lt_trader_queue (Producer)
Purpose
Monitors prices and queues trades when trigger conditions are met.
Trigger
[triggers]
crons = ["* * * * *"] # Every minute
Flow
- Fetch active trading configs
- Get unique base pair symbols
- Fetch prices for each
- Check trigger conditions
- Queue trades for execution
Queue Message
{
"userId": 123,
"configId": 456,
"action": "SELL",
"triggerPrice": 3400.50,
"lastTradePrice": 3000.00,
"chain": {...},
"pair": {...}
}
lt_trader_execute (Consumer)
Purpose
Consumes queued trades and executes them via Smart Contract Wallets.
Trigger
[[queues.consumers]]
queue = "lt-trading-queue"
max_batch_size = 1
Flow
- Receive message from queue
- Re-validate trigger condition
- Calculate trade amount
- Update oracle prices (if LazaiSwap)
- Execute trade via SCW
- Record in Trades table
- Send notification
Trade Execution
// Execute on SCW
const tx = await scw.executeTrade(
dexAddress,
swapCalldata
);
await tx.wait();
lt_balance_tracker (Balance Tracker)
Purpose
Automatically tracks user balances and detects deposits.
Trigger
[triggers]
crons = ["*/5 * * * *"] # Every 5 minutes
Flow
- Fetch all active users with SCWs
- For each user/chain/token combination
- Query on-chain balance
- Insert into UserBalances (historical)
- Detect deposits by comparing to expected balance
- Record deposits in DepositTransactions
Balance Record
INSERT INTO UserBalances
(UserID, TokenID, Balance, BalanceUSDC, PriceUSDC)
VALUES (?, ?, ?, ?, ?);
lt_tg_chart (Charts)
Purpose
Generates performance charts using QuickChart.io.
Input
{
"userId": 123456789
}
Output
{
"success": true,
"chartUrl": "https://quickchart.io/...",
"stats": {
"totalTrades": 25,
"pnlPercentage": 35.0,
"tokensTraded": ["ETH", "METIS"]
}
}
Chart Features
- Price lines per token
- Buy/sell markers
- PnL in title
- Date axis
Shared Utilities
priceHelper.js
// Normalize token symbols
normalizeTokenSymbol('WETH') // Returns 'ETH'
// Get cached price
getTokenPriceUSDC(db, 'ETH', 'USDC', 5) // 5 min cache
priceParser.js
// Parse API response
parsePrice(response, 'binance') // Returns price number
tokenMappings.json
{
"symbolMap": {
"WETH": "ETH",
"M.USDC": "USDC"
},
"stablecoins": ["USDC", "USDT", "DAI"],
"chartColors": {
"ETH": "#627EEA"
}
}
Error Handling
Standard Response Format
// Success
return new Response(JSON.stringify({
success: true,
data: result
}), { status: 200 });
// Error
return new Response(JSON.stringify({
success: false,
error: 'Description',
errorCode: 'CODE'
}), { status: 400 });
Common Error Codes
| Code | Meaning |
|---|---|
| INVALID_INPUT | Bad request parameters |
| NOT_FOUND | Resource not found |
| UNAUTHORIZED | Permission denied |
| BLOCKCHAIN_ERROR | Chain interaction failed |
| DATABASE_ERROR | D1 query failed |
Configuration
Environment-Specific
# Production
[env.production]
name = "lt-tg"
# Staging
[env.staging]
name = "lt-tg-staging"
# Development
[env.development]
name = "lt-tg-dev"
Secrets
wrangler secret put BOT_TOKEN
wrangler secret put BOT_PRIVATE_KEY
wrangler secret put WORKER_SECRET