Skip to content

πŸ“‹ Plugin Request: tonco-dex β€” TONCO DEX Integration for TeletonΒ #78

@xlabtg

Description

@xlabtg

πŸ“‹ Plugin Request: tonco-dex

🎯 Executive Summary

Create a professional plugin for full-featured interaction with TONCO DEX via the Teleton AI agent. TONCO (by CryptoAlgebra) is a next-generation AMM with concentrated liquidity, multi-asset pools, and advanced trading features.

This plugin will enable users to:

  • Execute swaps with optimal routing
  • Manage concentrated liquidity positions
  • Monitor pool statistics and fees
  • Set price alerts and automated strategies
  • All through natural language commands in Telegram

Target SDK: https://github.com/cryptoalgebra/tonco-sdk


πŸ“Œ Business Goals

Primary Objectives

  1. Seamless DEX Access β€” Trade TONCO pools directly from Telegram chat
  2. Liquidity Management β€” Add/remove liquidity, claim fees, adjust positions
  3. Advanced Analytics β€” Real-time pool data, APY, volume, impermanent loss
  4. Automation β€” Price alerts, auto-rebalance, limit orders via agent logic
  5. Security First β€” Transaction simulation, slippage protection, confirmation policies

Target Users

  • TON ecosystem traders seeking better capital efficiency
  • Liquidity providers managing concentrated positions
  • DeFi analysts tracking pool performance
  • Developers building on top of TONCO infrastructure

πŸ—οΈ Architecture Requirements

Plugin Structure

plugins/tonco-dex/
β”œβ”€β”€ manifest.json                 # Metadata, tools list, secrets schema
β”œβ”€β”€ index.js                      # Entry point: exports tools(sdk) function
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ tonco-client.js           # TONCO SDK wrapper with error handling
β”‚   β”œβ”€β”€ pool-manager.js           # Pool discovery, stats, analytics
β”‚   β”œβ”€β”€ swap-engine.js            # Swap execution, routing, slippage
β”‚   β”œβ”€β”€ position-manager.js       # Liquidity position CRUD operations
β”‚   β”œβ”€β”€ price-monitor.js          # Price alerts, oracle integration
β”‚   └── utils.js                  # Formatting, validation, helpers
β”œβ”€β”€ web-ui/
β”‚   β”œβ”€β”€ config-panel.jsx          # Plugin settings for Teleton Web UI
β”‚   β”œβ”€β”€ pool-browser.jsx          # Interactive pool explorer
β”‚   └── position-manager.jsx      # Visual LP position management
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ tonco-client.test.js      # Unit tests for SDK integration
β”‚   β”œβ”€β”€ swap-flow.test.js         # E2E swap simulation tests
β”‚   └── position-flow.test.js     # LP position lifecycle tests
β”œβ”€β”€ README.md                     # User documentation with examples
β”œβ”€β”€ CHANGELOG.md                  # Version history
└── .gitignore                    # Ignored files

Design Principles

  • Modularity β€” Each concern (swap, LP, analytics) in separate module
  • Security by Default β€” Simulation before execution, explicit confirmations
  • User-Centric β€” Natural language input, clear output, undo options
  • Extensibility β€” Architecture supports adding new TONCO features easily

πŸ”§ Tool Specifications

Category 1: Pool Discovery & Analytics (4 Tools)

Tool: tonco_list_pools

Attribute Value
Purpose Discover available TONCO liquidity pools
Input Parameters token_a (string, optional), token_b (string, optional), sort_by (enum: volume/apy/tvl), limit (int 1-50)
Output Data Array of pools with: address, tokens, tvl, volume_24h, apy, fee_tier, liquidity_depth
Side Effects None
Error Handling Network timeout, invalid token address, API rate limit

Tool: tonco_get_pool_stats

Attribute Value
Purpose Get detailed statistics for a specific pool
Input Parameters pool_address (string, required), include_historical (boolean, default: false)
Output Data Pool details: reserves, price, volume, fees_24h, apr_breakdown, liquidity_distribution, historical_chart_data (if requested)
Side Effects None
Error Handling Pool not found, invalid address format, data unavailable

Tool: tonco_calculate_swap_quote

Attribute Value
Purpose Get swap quote with price impact and route analysis
Input Parameters token_in (string), token_out (string), amount_in (number/string), slippage_tolerance (number 0-100, default: 1)
Output Data Quote: expected_out, price_impact_percent, route (pools involved), estimated_gas, minimum_received (after slippage), price_per_token
Side Effects None
Error Handling Insufficient liquidity, invalid token pair, amount too small/large

Tool: tonco_get_price_alerts

Attribute Value
Purpose List active price alerts for token pairs
Input Parameters token_pair (string, optional), status (enum: active/paused/all)
Output Data Array of alerts: id, token_pair, target_price, condition (above/below), status, created_at, triggered_count
Side Effects None
Error Handling No alerts found, invalid filter

Category 2: Swap Execution (3 Tools)

Tool: tonco_execute_swap

Attribute Value
Purpose Execute token swap on TONCO with safety checks
Input Parameters token_in, token_out, amount_in, slippage_tolerance (number), deadline_seconds (int, default: 1800), require_confirmation (boolean, default: true)
Output Data Transaction: hash, status, amount_out, actual_slippage, gas_used, block_number, explorer_url
Side Effects Blockchain transaction, wallet balance change
Error Handling Transaction reverted, slippage exceeded, insufficient balance, deadline passed, user declined confirmation

Important: This tool must:

  1. Simulate transaction before sending (via SDK)
  2. Show clear summary to user if require_confirmation: true
  3. Respect slippage_tolerance to prevent MEV attacks
  4. Log transaction details via sdk.log.info() (without sensitive data)

Tool: tonco_create_limit_order

Attribute Value
Purpose Create a limit order (executes when price condition is met)
Input Parameters token_in, token_out, trigger_price, amount_in, order_type (enum: buy/sell), expiry_timestamp (optional)
Output Data Order: id, status, created_at, trigger_condition, filled_amount, remaining_amount, explorer_url
Side Effects Smart contract interaction to register order
Error Handling Invalid price, insufficient allowance, contract error, duplicate order

Tool: tonco_cancel_order

Attribute Value
Purpose Cancel a pending limit order
Input Parameters order_id (string, required)
Output Data Result: success (boolean), transaction_hash (if applicable), message
Side Effects On-chain order cancellation
Error Handling Order not found, already filled/cancelled, not owner of order

Category 3: Liquidity Position Management (4 Tools)

Tool: tonco_get_positions

Attribute Value
Purpose List user's liquidity positions on TONCO
Input Parameters pool_address (string, optional), include_closed (boolean, default: false)
Output Data Array of positions: id, pool, token_amounts, current_value, fees_earned, apr, in_range (boolean), created_at
Side Effects None
Error Handling Wallet not connected, no positions found, API error

Tool: tonco_add_liquidity

Attribute Value
Purpose Add liquidity to a concentrated liquidity pool
Input Parameters pool_address, token_a_amount, token_b_amount, price_lower, price_upper, max_slippage (number), require_confirmation (boolean, default: true)
Output Data Position: id, pool, liquidity_added, position_range, transaction_hash, estimated_fees_24h
Side Effects Token transfers, LP NFT minted, blockchain transaction
Error Handling Insufficient balance, price range invalid, transaction reverted, user declined

Tool: tonco_remove_liquidity

Attribute Value
Purpose Remove liquidity from a position (partial or full)
Input Parameters position_id (string), liquidity_percentage (number 0-100, default: 100), min_token_a (optional), min_token_b (optional), require_confirmation (boolean)
Output Data Result: tokens_received (a and b), fees_claimed, transaction_hash, position_status (closed/active)
Side Effects LP NFT burned, tokens transferred to user
Error Handling Position not found, insufficient liquidity, slippage exceeded, user declined

Tool: tonco_claim_fees

Attribute Value
Purpose Claim accumulated trading fees from liquidity positions
Input Parameters position_id (string, required) or claim_all (boolean)
Output Data Result: tokens_claimed (array of {token, amount}), transaction_hash, total_value_usd
Side Effects Fee tokens transferred to user wallet
Error Handling No fees to claim, position not found, transaction failed

Category 4: Automation & Alerts (3 Tools)

Tool: tonco_create_price_alert

Attribute Value
Purpose Create a price alert for a token pair
Input Parameters token_pair (string), target_price (number), condition (enum: above/below/crosses), notification_method (enum: telegram/email/webhook), one_time (boolean, default: true)
Output Data Alert: id, status, created_at, trigger_condition, last_checked
Side Effects Alert registered in plugin storage, monitoring job scheduled
Error Handling Invalid price, token pair not found, duplicate alert

Tool: tonco_set_rebalance_strategy

Attribute Value
Purpose Configure auto-rebalance for liquidity positions
Input Parameters position_id, rebalance_trigger (enum: price_deviation/time_interval), threshold_value (number), new_price_range (object: lower/upper), max_gas_budget (optional)
Output Data Strategy: id, status, next_check_at, estimated_rebalance_cost
Side Effects Strategy saved, background monitor activated
Error Handling Invalid threshold, position not in range, insufficient gas budget

Tool: tonco_get_automation_status

Attribute Value
Purpose Check status of active automations (alerts, rebalancers)
Input Parameters type (enum: alert/rebalance/all), status (enum: active/paused/error)
Output Data Array of automations: id, type, config, status, last_triggered, next_check
Side Effects None
Error Handling No automations found, invalid filter

πŸ” Security Requirements

Transaction Safety

  • βœ… Simulation First: All transactions must be simulated via TONCO SDK before broadcasting
  • βœ… Slippage Protection: Enforce user-defined slippage tolerance; reject if exceeded
  • βœ… Deadline Enforcement: Include transaction deadline to prevent stale execution
  • βœ… Confirmation Policy: Respect require_confirmation flag; use sdk.llm.confirm() for explicit approval

Wallet & Key Management

  • βœ… No Key Storage: Never store private keys or seed phrases; rely on Teleton's wallet integration
  • βœ… Encrypted Secrets: Use sdk.secrets for any API keys or sensitive config
  • βœ… Address Validation: Validate all token/pool addresses against known format before use

Data Privacy

  • βœ… No Logging of Sensitive Data: Never log wallet addresses, amounts, or transaction details via sdk.log
  • βœ… Minimal Data Collection: Only collect data necessary for plugin functionality
  • βœ… User Control: Allow users to export/delete their plugin data anytime

Rate Limiting & DoS Protection

  • βœ… API Rate Limits: Respect TONCO API rate limits; implement exponential backoff
  • βœ… User-Level Throttling: Prevent spam by limiting tool calls per user per minute
  • βœ… Graceful Degradation: Return helpful errors when APIs are unavailable

βš™οΈ Configuration Requirements

Secrets Schema (manifest.json)

Secret Name Environment Variable Required Description
tonco_api_key TONCO_API_KEY No API key for premium TONCO endpoints (optional)
tonco_webhook_secret TONCO_WEBHOOK_SECRET No Secret for verifying incoming webhooks (optional)

Plugin Config Schema

Config Key Type Default Description
default_slippage number 1.0 Default slippage tolerance (%) for swaps
default_deadline integer 1800 Default transaction deadline (seconds)
require_confirmation boolean true Require explicit confirmation for transactions
auto_claim_fees boolean false Automatically claim fees when above threshold
fee_claim_threshold number 5.0 Minimum USD value to auto-claim fees
notification_channel string "telegram" Default channel for alerts (telegram/email/webhook)
preferred_pools array [] List of pool addresses to prioritize in search

🌐 Web UI Requirements

Config Panel Component

Location: web-ui/config-panel.jsx

Required Features:

  1. Display connection status to TONCO API
  2. Form for configuring default parameters (slippage, deadline, confirmation policy)
  3. Toggle for auto-claim fees with threshold input
  4. Notification channel selector (Telegram/Email/Webhook)
  5. Preferred pools manager (add/remove pool addresses)
  6. "Test Connection" button to validate API access
  7. Save/reset configuration buttons

Pool Browser Component

Location: web-ui/pool-browser.jsx

Features:

  • Searchable/filterable list of TONCO pools
  • Sort by TVL, volume, APY, fee tier
  • Click pool β†’ detailed view with charts (price history, liquidity depth)
  • Quick actions: "Swap", "Add Liquidity", "Set Alert"
  • Token pair selector with auto-complete

Position Manager Component

Location: web-ui/position-manager.jsx

Features:

  • Visual display of user's LP positions (in-range/out-of-range indicators)
  • Charts: position value over time, fees earned, impermanent loss estimate
  • Actions per position: Add/Remove liquidity, Claim fees, Adjust range, Set rebalance
  • Bulk actions: Claim all fees, Rebalance all in-range positions
  • Export positions to CSV

πŸ§ͺ Testing Requirements

Unit Tests

Framework: Vitest (preferred) or Jest

Coverage Requirements:

  • Minimum 80% coverage of critical paths
  • All tools must have at least one unit test
  • Separate tests for: SDK integration, swap logic, position management, alert system

Key Test Scenarios:

  • βœ… Swap quote calculation matches SDK output
  • βœ… Slippage protection rejects quotes exceeding tolerance
  • βœ… Position addition calculates correct liquidity range
  • βœ… Price alert triggers at correct threshold
  • βœ… Error handling for network failures, invalid inputs, contract reverts

Integration Tests

Approach: Mock TONCO SDK + forked mainnet tests via @ton/sandbox

Test Flows:

  1. Full Swap Flow: Quote β†’ Simulation β†’ Confirmation β†’ Execution β†’ Verification
  2. LP Lifecycle: Add liquidity β†’ Earn fees β†’ Claim fees β†’ Remove liquidity
  3. Alert System: Create alert β†’ Simulate price change β†’ Verify notification
  4. Error Recovery: Network timeout β†’ Retry logic β†’ Graceful failure message

Manual Testing Checklist

  • Plugin installs without errors in Teleton agent
  • All 14 tools register and are callable via sdk.plugin.call()
  • Swap simulation shows accurate price impact
  • Transaction confirmation dialog displays clear summary
  • LP position visualization matches on-chain state
  • Price alerts trigger notifications correctly
  • Web UI components render and function in Teleton WebUI
  • No sensitive data appears in logs or error messages
  • Rate limiting prevents API abuse
  • Configuration persists across agent restarts

πŸ“š Documentation Requirements

README.md Structure

Required Sections:

  1. Features β€” List of capabilities with icons
  2. Installation β€” Via Teleton Web UI and manual methods
  3. Setup β€” Connecting wallet, configuring defaults, API key (optional)
  4. Usage Examples β€” Natural language commands for each major action
  5. Configuration Options β€” Table of all config parameters
  6. Security Best Practices β€” Slippage, confirmations, key management
  7. Troubleshooting β€” Common errors and solutions
  8. Contributing β€” Guidelines for adding new tools
  9. License β€” MIT

Example Commands (for README)

πŸ’¬ "Swap 10 TON for jUSDT on TONCO with 0.5% slippage"
πŸ’¬ "Show me top 5 pools by APY containing TON"
πŸ’¬ "Add 5 TON and 100 jUSDT as liquidity between $0.95-$1.05"
πŸ’¬ "What's my total fees earned from TONCO positions?"
πŸ’¬ "Alert me if TON/jUSDT price goes above $1.10"
πŸ’¬ "Rebalance my position #abc123 to new range $0.98-$1.02"
πŸ’¬ "Claim all fees from my TONCO liquidity positions"

Code Documentation

  • JSDoc comments for all exported functions
  • Inline comments for complex logic (concentrated liquidity math, routing)
  • Clear error messages with actionable guidance

βœ… Acceptance Criteria

Functional Requirements

  • All 14 tools registered and accessible via sdk.plugin.call()
  • Swap execution includes simulation, slippage check, and optional confirmation
  • Liquidity position management supports add/remove/claim/adjust
  • Price alerts monitor and notify correctly
  • Pool discovery returns accurate, sorted results
  • Configuration persists and is respected by all tools
  • Web UI components render and function in Teleton WebUI

Technical Requirements

  • Code follows project style (ESLint + Prettier from teleton-plugins root)
  • No console.log in production β€” only sdk.log.{info,warn,error}
  • All async functions handle errors via try/catch with user-friendly messages
  • TypeScript types or JSDoc for all exported functions
  • No hardcoded secrets or sensitive data in code
  • Modular structure: separation of concerns in lib/*.js

Security Requirements

  • Transactions simulated before broadcasting
  • Slippage tolerance enforced at SDK and UI level
  • Confirmation policy respected for all state-changing operations
  • No logging of wallet addresses, amounts, or transaction hashes
  • Input validation for all user-provided parameters

Testing Requirements

  • Unit tests cover β‰₯80% of critical paths
  • Integration tests pass with mocked TONCO SDK
  • Manual testing checklist fully completed
  • No regressions in existing Teleton functionality

πŸ”— References & Resources

TONCO SDK

TONCO Protocol

Teleton Plugin Development

Related Plugins (for Architecture Reference)

  • dedust β€” Example of DEX integration
  • stonfi β€” Another DEX plugin for comparison
  • ton-wallet β€” Wallet interaction patterns

🏷️ Metadata

Field Value
Plugin ID tonco-dex
Version 1.0.0
Author xlabtg
SDK Version ^1.0.0
Priority High
Estimated Effort 4-6 weeks
Labels plugin-request, defi, dex, tonco, trading

πŸ“ Notes for AI Code Generator

Instructions for AI Assistant:

  1. Follow tool specifications exactly β€” Do not change parameter names, types, or required fields.
  2. Use Teleton Plugin SDK patterns β€” Export tools(sdk) function; each tool returns { success, data/error }.
  3. Handle errors gracefully β€” Catch all async errors, validate inputs, return structured messages.
  4. Use sdk.log for logging β€” Never console.log; never log sensitive data.
  5. Store secrets via sdk.secrets β€” Never in code, config files, or environment variables directly.
  6. Add JSDoc comments β€” Document all exported functions and complex logic.
  7. Generate tests β€” Use Vitest syntax; mock TONCO SDK with MSW or similar.
  8. Keep code modular β€” Separate concerns into lib/*.js files.
  9. Use async/await consistently β€” Avoid promise chains for readability.
  10. Add inline comments β€” Explain non-obvious logic, especially concentrated liquidity math and routing.

Recommended Implementation Order:

  1. manifest.json β€” Define metadata, tools list, secrets schema
  2. lib/tonco-client.js β€” Base SDK wrapper with error handling
  3. lib/pool-manager.js β€” Pool discovery and stats
  4. index.js β€” Export 3 core tools first (tonco_list_pools, tonco_get_pool_stats, tonco_calculate_swap_quote)
  5. tests/ β€” Unit tests for core functionality
  6. Expand to swap execution and position management
  7. Add automation/alerts tools
  8. web-ui/ β€” Config panel and pool browser components
  9. README.md β€” Documentation with examples
  10. Final testing and validation

πŸš€ Next Steps

  1. Review β€” Maintainer reviews this issue for completeness
  2. Assign β€” Assign to AI code generator or human contributor
  3. Branch β€” Create feature branch: feature/tonco-dex
  4. Scaffold β€” Generate initial code structure
  5. Iterate β€” Develop tools incrementally with testing
  6. PR β€” Submit pull request to teleton-plugins main repository
  7. Review β€” Code review and feedback incorporation
  8. Merge β€” Merge to main after approval

Created by: @xlabtg
Date: 2026-03-29
Related: TONCO SDK integration, DeFi plugin series
Status: Ready for Implementation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions