-
Notifications
You must be signed in to change notification settings - Fork 1
Description
Objective
Build the AI tool that enables users to create TWAP orders through natural conversation, handling the full flow from order specification to session approval to order activation.
Background
Users should be able to request TWAP orders naturally, like "Buy $1000 ETH over the next 24 hours" or "Sell 10 SOL gradually over 2 days". The AI needs to:
- Parse user intent and extract parameters
- Validate parameters
- Guide through wallet setup if needed
- Create session key and get approval
- Create TWAP order
- Provide status updates
Acceptance Criteria
- AI tool definition for TWAP order creation
- Natural language parsing for TWAP parameters (amount, token, duration, intervals)
- Validation of parameters (minimum amounts, supported tokens, reasonable durations)
- Integration with embedded wallet creation flow
- Integration with fund transfer flow
- Integration with session key approval flow
- Order creation via backend API
- Confirmation and status tracking in chat
- Support for order status queries ("How's my TWAP order?")
- Support for order cancellation ("Cancel my ETH purchase")
User Experience Flow
User: "Buy $1000 worth of ETH over the next 24 hours"
AI: "I'll set up a TWAP order to buy ETH with $1000 over 24 hours.
Order Details:
• Buy: ETH
• Spend: 1000 USDC
• Duration: 24 hours
• Frequency: ~$41.67 every hour (24 trades)
• Network: Arbitrum
[If no embedded wallet] First, let's create a smart wallet...
[If wallet not funded] Transfer $1000 USDC to your smart wallet...
[If no session key] Approve session key for automated execution...
Ready to activate this order?"
User: "Yes"
AI: "TWAP order activated!
Order ID: #ABC123
I'll execute trades automatically over the next 24 hours.
You can check progress anytime by saying 'show my TWAP order'
or cancel with 'cancel TWAP order #ABC123'"
Technical Context
AI Tool Definition:
interface CreateTwapOrderTool {
name: 'create_twap_order'
description: 'Create a TWAP (Time-Weighted Average Price) order to buy or sell tokens gradually over time'
parameters: {
action: 'buy' | 'sell'
tokenIn: string // symbol or address
tokenOut: string // symbol or address
amount: string // human-readable amount
duration: string // "24 hours", "2 days", etc.
intervalCount?: number // optional, default to reasonable value
network?: string // optional, default to current
}
}Parameter Parsing:
AI should handle flexible input:
- "Buy $1000 ETH over 24 hours"
- "Sell 10 SOL gradually over 2 days"
- "TWAP 5000 USDC into BTC over 1 week"
Extract:
- Action (buy/sell)
- Amount
- Token in/out
- Duration
- Network (from context or ask)
Validation:
- Minimum order size (e.g., $100 to make gas costs reasonable)
- Supported tokens (must have liquidity)
- Duration limits (minimum 1 hour, maximum 30 days?)
- Interval calculation (at least 10 minutes between trades)
- User has sufficient balance
Tool Execution Flow:
async function executeTwapOrderTool(params) {
// 1. Parse and validate parameters
const orderParams = parseAndValidate(params)
// 2. Check wallet status
const walletStatus = await checkWalletStatus(userId)
if (!walletStatus.hasEmbeddedWallet) {
return { needsEmbeddedWallet: true }
}
if (walletStatus.balance < orderParams.amount) {
return { needsFunding: true, requiredAmount: orderParams.amount }
}
// 3. Create/check session key
const sessionKey = await getOrCreateSessionKey({
userId,
permissions: calculateSessionPermissions(orderParams)
})
if (!sessionKey.approved) {
return { needsSessionApproval: true, sessionKey }
}
// 4. Create TWAP order via backend API
const order = await api.createTwapOrder({
sessionKeyId: sessionKey.id,
...orderParams
})
return {
success: true,
orderId: order.id,
summary: formatOrderSummary(order)
}
}Session Permissions for TWAP
Calculate appropriate session key permissions based on order:
{
contractAddress: SWAP_ROUTER_ADDRESS, // Uniswap, 0x, etc.
allowedFunctions: ['swap', 'exactInputSingle'],
maxPerTransaction: orderParams.amountPerInterval * 1.1, // +10% buffer for slippage
maxTotalAmount: orderParams.totalAmount * 1.05, // +5% buffer
duration: orderParams.duration + 3600, // +1 hour buffer
rateLimit: {
count: 1,
period: orderParams.intervalSeconds * 0.9 // Slightly faster than needed
}
}Order Status & Tracking
Status Queries:
Support natural language status checks:
- "How's my TWAP order?"
- "Show my ETH purchase"
- "What's the status of order #ABC123"
Response should include:
- Progress (5 of 24 trades completed)
- Amount executed so far
- Average price achieved
- Estimated completion time
- Recent executions (with tx hashes)
Order Management:
Support cancellation:
- "Cancel my TWAP order"
- "Stop buying ETH"
- "Cancel order #ABC123"
Cancellation:
- Confirms with user
- Stops future executions
- Shows summary of completed trades
- Funds remain in wallet
Error Handling
Common Issues:
- Insufficient balance
- Token not supported
- Duration too short/long
- Network doesn't support automation
- Session expired during order
- Trade execution failed (slippage, liquidity)
For each:
- Clear error message
- Suggest solution
- Offer alternatives
UI Considerations
Order Confirmation:
Show clear summary before activation:
- Total amount
- Per-trade amount
- Number of trades
- Duration
- Estimated gas costs (if not sponsored)
Progress Updates:
Optionally notify user:
- When order starts
- Milestone progress (25%, 50%, 75%, 100%)
- If execution fails
- When order completes
Testing Scenarios
- Create TWAP order with all parameters specified
- Create with minimal parameters (AI infers defaults)
- Create without embedded wallet (triggers creation)
- Create without funds (triggers transfer)
- Create without session key (triggers approval)
- Query order status during execution
- Cancel order mid-execution
- Multiple concurrent TWAP orders
- Order fails mid-execution (handle gracefully)
Files to Create/Modify
- AI tool definition for TWAP orders
- Tool execution logic (similar to swap/send hooks)
- Backend API client functions
- Chat prompt updates to include TWAP guidance
- Order status formatting utilities
Dependencies
- Requires "Implement TWAP Order Backend Executor"
- Requires "Build Session Key Approval Flow in Chat Interface"
- Requires "Implement Fund Transfer Flow from BYO to Embedded Wallet"
Metadata
Metadata
Assignees
Labels
Type
Projects
Status