π€ 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.
TonPay402 is not just a 402 paywall gateway β it is a treasury policy engine for AI agents.
- β 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
| 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 |
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
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.
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)
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.
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.
contracts/β Tact contract source (ton_pay402.tact)tests/β sandbox tests for payment policy behaviorscripts/β deploy script(s)build/β generated wrappers/artifactsmcp-server/β MCP runtime + Telegram approval bot
- Agent calls MCP tool
execute_m2m_payment. - MCP server sends
ExecutePaymentto contract using the agent wallet. - 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
ApprovalRequestand does not transfer.
- Telegram bot polls contract transactions, decodes
ApprovalRequest, and notifies owner. - Owner taps Approve (owner wallet sends
ExecutePayment) or Reject.
TonPay402 tracks manual-approval requests through a durable lifecycle in the bot state file:
pendingβ request detected from chain and awaiting decisionapprovedβ owner approved and submission was sentrejectedβ owner explicitly rejectedfailedβ 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.
Current policy in contracts/ton_pay402.tact:
- Access control: only
owneroragentcan callExecutePayment - Owner-only emergency controls:
EmergencyStopandResumeOperations - 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
- β
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.
- Node.js 20+
- npm
- TON testnet wallets (agent + owner) with balance for gas
- Telegram bot token (from
@BotFather)
npm installnpx blueprint buildnpx blueprint testcd mcp-server
npm install
cp .env.example .envFill .env values:
TON_NETWORK(testnetormainnet)ENABLE_MAINNET_MODE(settrueto allow mainnet runtime)TON_API_KEY(optional)EXECUTION_BUFFER_TONCONTRACT_ADDRESSAGENT_MNEMONICAGENT_WALLET_WORKCHAINX402_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, default15000)X402_FACILITATOR_RETRY_ATTEMPTS(optional, default0)X402_FACILITATOR_RETRY_BACKOFF_MS(optional, default300)X402_FACILITATOR_FAIL_OPEN(optional, defaultfalse; iftrue, payment can continue when facilitator call fails)BROKER_STATE_FILE(persistent broker envelope state, defaultbroker-state.json)OWNER_MNEMONICOWNER_WALLET_WORKCHAINTELEGRAM_BOT_TOKENTELEGRAM_CHAT_IDAPPROVAL_POLL_INTERVAL_MSAPPROVAL_STATE_FILE(persistent bot state file, defaultapproval-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, defaultrequest-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, default10)
- Build and test locally:
npm install
npx blueprint build
npx blueprint test- Deploy contract to testnet (owner wallet from Blueprint + env agent address):
AGENT_ADDRESS="EQ..." DAILY_LIMIT_TON="10" npx blueprint run deployTonPay402 --testnet-
Put deployed address into
mcp-server/.envasCONTRACT_ADDRESSand set the rest of required values. -
Start MCP server and Telegram bot (separate terminals):
cd mcp-server
npm run start:mcpcd mcp-server
npm run start:bot-
Practical checks:
- Within limit payment: call
execute_m2m_paymentwith a small amount and verify transfer succeeds. - Over-limit payment: call
execute_m2m_paymentabove 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_URLand 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.
- Within limit payment: call
-
Verify persisted audit/state artifacts:
request-audit.jsonapproval-state.jsonbroker-state.json
From mcp-server/:
npm run start:mcpIn a second terminal:
npm run start:bot-
get_allowance- Input:
contractAddress - Output: remaining allowance in TON
- Input:
-
execute_m2m_payment- Input:
contractAddress,targetAddress,amountInTon, optionalrequestId, optionalfacilitatorContext - Sends
ExecutePaymentfrom agent wallet - If
X402_FACILITATOR_URLis 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
- Input:
-
create_envelope- Input:
envelopeId,totalBudgetTon,periodSeconds - Creates shared off-chain budget envelope for multiple agents
- Input:
-
assign_agent_to_envelope- Input:
envelopeId,agentId - Grants an agent identity permission to spend from that envelope
- Input:
-
get_envelope_allowance- Input:
envelopeId - Output: remaining envelope budget in TON
- Input:
-
execute_envelope_payment- Input:
envelopeId,agentId,contractAddress,targetAddress,amountInTon, optionalrequestId, optionalfacilitatorContext - Reserves envelope budget first, then executes normal on-chain payment path
- Rolls back envelope reservation automatically if on-chain submit fails
- Input:
- 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_FILEsince it stores approval/audit state. - Back up and protect
REQUEST_AUDIT_FILEsince it linksrequestIdto approval outcomes. - Consider indexed/event-driven ingestion (webhook/indexer) instead of pure polling.
- Contract tests are in
tests/TonPay402.spec.ts. - MCP server implementation:
mcp-server/index.ts. - Telegram approval flow:
mcp-server/bot.ts.
- 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.
This project is licensed under the MIT License.
