Skip to content

Commit 5fc220d

Browse files
authored
feat: add toncoin processing (#1101)
1 parent 2a8c11d commit 5fc220d

File tree

1 file changed

+167
-2
lines changed

1 file changed

+167
-2
lines changed

payments/toncoin.mdx

Lines changed: 167 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,171 @@ title: "Toncoin payments processing"
33
sidebarTitle: "Toncoin"
44
---
55

6-
import { Stub } from '/snippets/stub.jsx';
6+
import { Aside } from "/snippets/aside.jsx";
77

8-
<Stub issue="204" />
8+
Processing Toncoin payments requires choosing between two architectural approaches:
9+
10+
- invoice-based deposits to a single address, common to all users
11+
- unique deposit addresses per user.
12+
13+
<Aside type="tip">
14+
Wallets in Ton are smart-contracts, not external accounts [like in Ethereum](/from-ethereum#account-model). Each wallet has its own address, code, and storage. Deposits are incoming messages to these wallet contracts.
15+
</Aside>
16+
17+
<Aside
18+
type="caution"
19+
>
20+
Do not send funds to a wallet address that you cannot initialize. Derive addresses deterministically based on contracts [initial state](/foundations/addresses/overview).
21+
</Aside>
22+
23+
## Deposit methods comparison
24+
25+
**Invoice-based flow**
26+
27+
```mermaid
28+
graph LR
29+
U1[User A] -- invoice UUID --> SW[Shared Wallet]
30+
U2[User B] -- invoice UUID --> SW
31+
SW --> EX[Exchange Ledger]
32+
```
33+
34+
**Unique deposit address flow**
35+
36+
```mermaid
37+
graph LR
38+
U1[User A] --> W1[Wallet A]
39+
W1 --> EX[Exchange Ledger]
40+
U2[User B] --> W2[Wallet B]
41+
W2 --> EX
42+
```
43+
44+
**Comparison table**
45+
46+
| Criteria | Invoice-based deposits | Unique deposit addresses |
47+
| ---------------------------- | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
48+
| Security exposure | One shared hot wallet; a key leak drains the full pool | Each wallet isolates funds; compromise affects only the impacted user |
49+
| User input requirements | User must include an invoice ID comment; missing or malformed comments need manual recovery workflows | User only needs the destination address |
50+
| Parsing and validation | Backend parses comments on every deposit and matches to invoices | No parsing; deposit attribution is address-based |
51+
| Deployment and storage costs | Deploy and maintain a single wallet; [storage rent](/foundations/fees#storage-fee) limited to that contract | Deploy many wallets; storage rent and deployment gas scale with user count |
52+
| Monitoring workload | Poll one address; comment parsing adds CPU but [RPC calls](/ecosystem/api/overview) stay low | Track many addresses; RPC queries and state tracking grow with the active user base |
53+
| Withdrawal handling | [Highload wallet](/standard/wallets/highload/overview) can batch withdrawals from one balance | Need sweeps or coordinated withdrawals from many wallets; extra gas and sequencing logic |
54+
| Sharding behavior | All activity hits [one shard](/foundations/shards); throughput limited by that shard | Wallets are distributed across shards; helps spread load |
55+
56+
## Invoice-based deposits
57+
58+
Invoice-based processing uses one wallet address to receive payments from all users. Each payment includes a unique identifier in the transaction comment field, allowing the service to attribute deposits to specific users.
59+
60+
The implementation deploys one wallet contract (typically [Highload](/standard/wallets/highload/overview)) and generates unique invoice identifiers for each deposit. Users send Toncoin to this shared address with their invoice identifier as the comment. The service polls the wallet's transaction history, extracts comments from incoming messages, matches them against stored invoices, and credits user accounts accordingly.
61+
62+
Transaction comments in TON use the text message format; read more in [How TON wallets work](/standard/wallets/how-it-works).
63+
64+
<Aside
65+
type="danger"
66+
title="Funds at risk"
67+
>
68+
Risk: deposits without the correct invoice identifier may be lost.
69+
Scope: incoming transfers to the shared deposit address.
70+
Mitigation: enforce invoice format; reject or hold unmatched deposits; provide a recovery workflow; document comment entry in the UI.
71+
Environment: validate the full flow on testnet before enabling mainnet.
72+
</Aside>
73+
74+
**Advantages**:
75+
76+
- Single wallet simplifies key management
77+
- Reduced gas costs for deployments
78+
- Withdrawals can batch multiple user requests into one transaction using a Highload wallet
79+
80+
**Disadvantages**:
81+
82+
- Access leak to the single hot wallet could lead to all user funds loss
83+
- Users must correctly input the invoice identifier, and mistakes result in lost or misdirected funds
84+
- Comment parsing adds complexity
85+
- Some user wallet applications don't support comments, limiting accessibility
86+
- Single wallet network load [won't be sharded](/foundations/shards)
87+
88+
<Aside type="note">
89+
Not production-ready code, use only for educational purposes
90+
</Aside>
91+
92+
To understand this approach in greater detail, see the following TypeScript implementation: [Invoice-based Toncoin deposits](https://github.com/ton-org/docs-examples/blob/processing/guidebook/payment-processing/src/deposits/invoices.ts).
93+
94+
## Unique deposit addresses
95+
96+
Unique address deposits use a separate wallet contract for each user. The user deposits to their dedicated address, and the service monitors all deployed wallets for incoming transactions. No comment parsing is required since each address maps to exactly one user.
97+
98+
Implementation requires a wallet generation strategy. A common approach uses a deterministic scheme based on a single master [keypair](/standard/wallets/mnemonics) and user identifiers, deriving unique addresses for V4 and V5 wallets using different [`subwallet_id`](/standard/wallets/how-it-works#subwallet-id) values. Alternatively, generate a unique keypair per user, though this increases key management complexity.
99+
100+
<Aside
101+
type="danger"
102+
title="Funds at risk"
103+
>
104+
Funds sent to a [non-existent or wrong address](/foundations/addresses/overview) are irrecoverable. Derive addresses deterministically and double check.
105+
</Aside>
106+
107+
Wallet deployment happens lazily when users first request their deposit address. Generate the address deterministically without deploying the contract. When the user sends their first deposit to the not deployed address, send the transaction in [non-bounceable mode](/foundations/messages/overview). The contract doesn't exist yet, so bounceable messages would return the funds. After the first deposit arrives, deploy the contract using funds from that deposit or from an external source.
108+
109+
<Aside>
110+
Sending non-bounceable messages to nonexistent accounts without testing it first is particularly bad practice. Always test to ensure the address is correct and the deployment flow works as expected.
111+
</Aside>
112+
113+
Monitor all user wallets by maintaining a list of deployed addresses and polling their transactions. For large user bases, this becomes resource-intensive. Optimization strategies include monitoring only active wallets (those with recent deposits), using batched RPC calls to check multiple wallets per request.
114+
115+
TON's sharding mechanism splits the network across multiple chains based on address prefixes. The shard prefix comes from the first bits of the address hash. Deploying wallets in the same shard reduces cross-shard communication overhead.
116+
117+
<Aside
118+
type="danger"
119+
title="Keys and funds at risk"
120+
>
121+
Risk: leaked or mishandled private keys enable wallet takeover and fund loss.
122+
Scope: generation, storage, and access to per-user wallet keys and deployment workflow.
123+
Mitigation: encrypt keys at rest; restrict access; rotate keys; monitor deployment status; verify destination addresses before crediting deposits.
124+
Environment: validate key management and deployment flow on testnet before mainnet.
125+
</Aside>
126+
127+
Withdrawal processing must gather funds from multiple wallets. Either maintain a minimum balance in each wallet for gas fees or implement a fund collection system that periodically sweeps deposits to a central hot wallet. Highload wallets handle batch withdrawals efficiently, while standard V4/V5 wallets process messages sequentially using `seqno`, creating bottlenecks under high load.
128+
129+
**Advantages**:
130+
131+
- No comment parsing removes a major source of user error
132+
- Better security since each user has a unique keypair
133+
- Transaction monitoring is straightforward - any incoming transaction to a user's address is their deposit
134+
135+
**Disadvantages**:
136+
137+
- Higher operational complexity managing multiple wallets
138+
- Deployment costs multiply by the number of users
139+
- Withdrawal processing requires coordination across wallets
140+
- Storage fees apply to each deployed contract (currently \~0.001 TON per year per contract)
141+
142+
<Aside type="note">
143+
Not production-ready code, use only for educational purposes
144+
</Aside>
145+
146+
To understand this approach in greater detail, see the following TypeScript implementation: [Unique address Toncoin deposits](https://github.com/ton-org/docs-examples/blob/processing/guidebook/payment-processing/src/deposits/unique-addresses.ts).
147+
148+
## Withdrawal batching
149+
150+
<Aside
151+
type="caution"
152+
>
153+
When withdrawing, do not send funds to a wallet address that you cannot initialize later, based on contracts [initial state](/foundations/addresses/overview).
154+
</Aside>
155+
156+
[Highload wallets](/standard/wallets/highload/overview) support parallel message processing by storing processed request identifiers instead of sequential `seqno`. This enables batching multiple withdrawals into one transaction, reducing fees and improving throughput.
157+
158+
## Common abuse patterns
159+
160+
- Reusing a previously settled invoice identifier to trigger duplicate credits when the backend does not invalidate the invoice after the first use.
161+
- Changing the Toncoin amount but leaving the original invoice identifier to obtain services at a lower price if expected amounts are not enforced.
162+
- Crafting comments that mimic another users invoice identifier in order to hijack their pending credit.
163+
- Submitting large numbers of dust payments to inflate processing costs or exhaust rate limits on transaction polling.
164+
165+
## Monitoring best practices
166+
167+
Implement exponential backoff for RPC failures. Network issues or node maintenance can interrupt transaction polling. When [`getTransactions`](/ecosystem/api/toncenter/v2/accounts/list-account-transactions) fails, wait before retrying with increasing delays to avoid overwhelming the endpoint.
168+
169+
Store transaction state persistently. Record the last processed `lt` value (`lt` here is logical time) and transaction hash to resume monitoring after restarts without reprocessing transactions. This prevents duplicate deposit credits.
170+
171+
Use multiple RPC endpoints for reliability. TON has several public API providers and liteserver networks. Implement fallback logic to switch endpoints if the primary becomes unavailable. Compare results across endpoints to detect potential inconsistencies.
172+
173+
Log all processing decisions including deposit credits, withdrawal submissions, and failed transactions. These logs are essential for debugging user reports and auditing system behavior. Include transaction hashes, logical times, amounts, and user identifiers in logs.

0 commit comments

Comments
 (0)