Skip to content

Ton-Pay-402/TonPay402

Repository files navigation

TonPay402

License: MIT TON Network Tests MCP

TonPay402 Infographic

πŸ€– TonPay 402: The Universal M2M Payment Rail for TON AI Agents TonPay 402 is a specialized infrastructure toolkit designed to enable secure, autonomous, and policy-driven payments for AI agents on the TON Blockchain. By leveraging the Wallet V5 (W5) standard and the x402 (HTTP 402) protocol, it provides the "financial guardrails" necessary for agents to participate in the machine economy without compromising user funds.

⚑ Unique Differentiators

TonPay402 is not just a 402 paywall gateway β€” it is a treasury policy engine for AI agents.

What you see in 10 seconds

  • βœ… On-chain spending policy enforcement (not only backend checks)
  • βœ… Human-in-the-loop approval path for risky transactions (ApprovalRequest -> Approve/Reject)
  • βœ… Whitelist bypass for trusted targets (agent can pay approved oracles/APIs without daily cap)
  • βœ… Emergency Kill-Switch (owner can instantly pause all agent payment execution)
  • βœ… Durable approval state + idempotent handling (restart-safe bot workflows)
  • βœ… End-to-end audit correlation via requestId + approval refs + status transitions

TonPay402 vs Generic 402 Gateway Model

Capability Generic 402 Gateway TonPay402
Core flow Paywall access (pay -> token) Policy-checked treasury execution
Over-limit handling Usually reject/fail Emit ApprovalRequest + human approval path
Emergency response Usually off-chain/manual On-chain EmergencyStop / ResumeOperations controls
Trusted vendor fast lane Rare Whitelist-based limit bypass for approved recipients
Approval lifecycle Minimal/manual pending -> approved/rejected/failed persisted state
Auditability Basic payment logs Correlated requestId + approval records + status trail
Agent safety Limited On-chain spend limits + explicit HITL escalation

Positioning

TonPay402 is a policy engine for agent treasuries, not only a payment gateway.

  • Focus: autonomous spend with hard guardrails + human escalation
  • Primary user: operators of AI agents that need both automation and accountability
  • Core promise: programmable spending policies, approval lifecycle, and audit traceability

πŸš€ Problem

The "Toddler with a Credit Card" Dilemma AI Agents are becoming autonomous economic actorsβ€”buying API credits, renting GPU power, or hiring other sub-agents. However, giving an LLM-based agent full access to a seed phrase is an extreme security risk . Current solutions either:

Risk total drainage via prompt injection or logic bugs.

Require constant human approval, defeating the purpose of autonomy.

βœ… Solution

TonPay402 provides a supervised spending stack for agents:

  • On-chain policy contract for daily budget controls
  • Whitelist policy for trusted recipients (oracle/API fast lane)
  • MCP tool interface for agent-native execution
  • Telegram HITL approvals for exceptional payments
  • Persistent audit state for production-safe operations
  • Wallet V5R1 runtime signers in MCP server (agent) and Telegram bot (owner)

πŸ—οΈ Architecture

AI Reasoning Layer: The agent identifies a need (e.g., "I need a weather forecast API"). x402 Challenge: The service provider issues an HTTP 402 challenge (Price, Address, Network). SDK Policy Check: The TonPay 402 SDK checks the request against on-chain policies. W5 Execution: If within limits, the Wallet V5 Extension authorizes an internal_signed message to execute the payment.

Human Escalation: If the limit is exceeded, an event is emitted to the Telegram Bot, providing the user with "Approve/Reject" buttons.

Overview

TonPay402 combines:

  • A Tact smart contract that enforces spending guardrails.
  • An MCP server that lets AI agents call payment tools.
  • A Telegram bot that catches over-limit approval requests and lets an owner approve/reject.

Repository Structure

  • contracts/ β€” Tact contract source (ton_pay402.tact)
  • tests/ β€” sandbox tests for payment policy behavior
  • scripts/ β€” deploy script(s)
  • build/ β€” generated wrappers/artifacts
  • mcp-server/ β€” MCP runtime + Telegram approval bot

How It Works

  1. Agent calls MCP tool execute_m2m_payment.
  2. MCP server sends ExecutePayment to contract using the agent wallet.
  3. Contract behavior:
    • If emergency mode is active: blocks all agent-initiated payments.
    • If target is whitelisted: executes transfer without consuming daily limit.
    • If target is not whitelisted and within limit: executes transfer.
    • If target is not whitelisted and over limit (agent path): emits ApprovalRequest and does not transfer.
  4. Telegram bot polls contract transactions, decodes ApprovalRequest, and notifies owner.
  5. Owner taps Approve (owner wallet sends ExecutePayment) or Reject.

Approval Lifecycle & Audit State

TonPay402 tracks manual-approval requests through a durable lifecycle in the bot state file:

  • pending β€” request detected from chain and awaiting decision
  • approved β€” owner approved and submission was sent
  • rejected β€” owner explicitly rejected
  • failed β€” approval action failed during submission

Each request is identified by a stable approval reference and can be correlated with client-side requestId in MCP payment submissions.

Smart Contract Policy

Current policy in contracts/ton_pay402.tact:

  • Access control: only owner or agent can call ExecutePayment
  • Owner-only emergency controls: EmergencyStop and ResumeOperations
  • Daily spend limit with 24h reset
  • Owner-managed whitelist for trusted recipients
  • Whitelisted targets bypass daily-limit accounting for agent payments
  • Over-limit agent request escalates to manual approval path
  • Owner can execute approved payment manually

Wallet Version Status

  • βœ… Runtime signing is implemented with WalletContractV5R1 in:
    • mcp-server/index.ts (agent signer)
    • mcp-server/bot.ts (owner signer)
  • ⏳ Roadmap item "Mainnet Deployment with Wallet V5 integration" still refers to production rollout hardening, not basic signer support.

Prerequisites

  • Node.js 20+
  • npm
  • TON testnet wallets (agent + owner) with balance for gas
  • Telegram bot token (from @BotFather)

Setup

1) Install root dependencies

npm install

2) Build contract wrappers

npx blueprint build

3) Run contract tests

npx blueprint test

4) Configure MCP server + bot

cd mcp-server
npm install
cp .env.example .env

Fill .env values:

  • TON_NETWORK (testnet or mainnet)
  • ENABLE_MAINNET_MODE (set true to allow mainnet runtime)
  • TON_API_KEY (optional)
  • EXECUTION_BUFFER_TON
  • CONTRACT_ADDRESS
  • AGENT_MNEMONIC
  • AGENT_WALLET_WORKCHAIN
  • X402_FACILITATOR_URL (optional; when set, MCP calls facilitator before on-chain submit)
  • X402_FACILITATOR_API_KEY (optional bearer token for facilitator)
  • X402_FACILITATOR_TIMEOUT_MS (optional, default 15000)
  • X402_FACILITATOR_RETRY_ATTEMPTS (optional, default 0)
  • X402_FACILITATOR_RETRY_BACKOFF_MS (optional, default 300)
  • X402_FACILITATOR_FAIL_OPEN (optional, default false; if true, payment can continue when facilitator call fails)
  • BROKER_STATE_FILE (persistent broker envelope state, default broker-state.json)
  • OWNER_MNEMONIC
  • OWNER_WALLET_WORKCHAIN
  • TELEGRAM_BOT_TOKEN
  • TELEGRAM_CHAT_ID
  • APPROVAL_POLL_INTERVAL_MS
  • APPROVAL_STATE_FILE (persistent bot state file, default approval-state.json)
  • BOOTSTRAP_HISTORY_LIMIT (how many recent txs to mark as seen on first startup)
  • REQUEST_AUDIT_FILE (shared MCP/bot request audit log, default request-audit.json)

Never commit real mnemonics or bot secrets.

For deployment script (scripts/deployTonPay402.ts) also provide:

  • AGENT_ADDRESS (agent wallet address to be authorized by contract)
  • DAILY_LIMIT_TON (optional, default 10)

Practical Testnet Smoke Test

  1. Build and test locally:
npm install
npx blueprint build
npx blueprint test
  1. Deploy contract to testnet (owner wallet from Blueprint + env agent address):
AGENT_ADDRESS="EQ..." DAILY_LIMIT_TON="10" npx blueprint run deployTonPay402 --testnet
  1. Put deployed address into mcp-server/.env as CONTRACT_ADDRESS and set the rest of required values.

  2. Start MCP server and Telegram bot (separate terminals):

cd mcp-server
npm run start:mcp
cd mcp-server
npm run start:bot
  1. Practical checks:

    • Within limit payment: call execute_m2m_payment with a small amount and verify transfer succeeds.
    • Over-limit payment: call execute_m2m_payment above daily limit and verify Telegram approval prompt appears.
    • Approve path: tap Approve in Telegram and verify owner-submitted transfer succeeds.
    • Reject path: trigger another over-limit request, tap Reject, and verify status is persisted as rejected.
    • Facilitator path (optional): set X402_FACILITATOR_URL and verify returned target/amount overrides are used.
    • Broker path: create envelope, assign agent, execute envelope payment, and confirm budget decreases.
    • Broker rollback path: force on-chain submit failure and confirm envelope budget is rolled back.
  2. Verify persisted audit/state artifacts:

    • request-audit.json
    • approval-state.json
    • broker-state.json

Running

From mcp-server/:

npm run start:mcp

In a second terminal:

npm run start:bot

MCP Tools

  • get_allowance

    • Input: contractAddress
    • Output: remaining allowance in TON
  • execute_m2m_payment

    • Input: contractAddress, targetAddress, amountInTon, optional requestId, optional facilitatorContext
    • Sends ExecutePayment from agent wallet
    • If X402_FACILITATOR_URL is configured, MCP first calls AEON/x402 facilitator and can apply returned target/amount/reference before submitting on-chain
    • Over-limit requests are escalated by contract and picked up by Telegram bot
  • create_envelope

    • Input: envelopeId, totalBudgetTon, periodSeconds
    • Creates shared off-chain budget envelope for multiple agents
  • assign_agent_to_envelope

    • Input: envelopeId, agentId
    • Grants an agent identity permission to spend from that envelope
  • get_envelope_allowance

    • Input: envelopeId
    • Output: remaining envelope budget in TON
  • execute_envelope_payment

    • Input: envelopeId, agentId, contractAddress, targetAddress, amountInTon, optional requestId, optional facilitatorContext
    • Reserves envelope budget first, then executes normal on-chain payment path
    • Rolls back envelope reservation automatically if on-chain submit fails

Security Notes

  • Use separate mnemonics for owner and agent wallets.
  • Keep owner mnemonic only in secure runtime environments.
  • Restrict Telegram bot usage to the owner chat ID.
  • Back up and protect APPROVAL_STATE_FILE since it stores approval/audit state.
  • Back up and protect REQUEST_AUDIT_FILE since it links requestId to approval outcomes.
  • Consider indexed/event-driven ingestion (webhook/indexer) instead of pure polling.

Development Notes

  • Contract tests are in tests/TonPay402.spec.ts.
  • MCP server implementation: mcp-server/index.ts.
  • Telegram approval flow: mcp-server/bot.ts.

πŸ—ΊοΈ Roadmap

  • Core Tact Contract for Policy Management.
  • MCP Server for LLM tool-calling.
  • Wallet V5R1 runtime signer support (MCP agent + Telegram owner).
  • Integration with AEON/x402 facilitators .
  • Multi-agent "Broker" for shared budget envelopes .
  • Mainnet rollout hardening for Wallet V5 architecture.

License

This project is licensed under the MIT License.

About

TonPay 402 is a specialized infrastructure toolkit designed to enable secure, autonomous, and policy-driven payments for AI agents on the TON Blockchain. By leveraging the Wallet V5 (W5) standard and the x402 (HTTP 402) protocol

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors