Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 140 additions & 2 deletions payments/toncoin.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,144 @@ title: "Toncoin payments processing"
sidebarTitle: "Toncoin"
---

import { Stub } from '/snippets/stub.jsx';
import { Aside } from "/snippets/aside.jsx";

<Stub issue="204" />
Processing Toncoin payments requires choosing between two architectural approaches: invoice-based deposits to a single address, common to all users or unique deposit addresses per user. Each approach has different security characteristics, implementation complexity, and operational requirements.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make the exposition more self-contained and given this most likely will be read by seasoned Web3 engineers, let's add a brief note that TON blockchain does not have Ethereum-like externally owned accounts and probably link to the "Coming from Ethereum" page as well.


## Deposit methods comparison

**Invoice-based flow**

```mermaid
graph LR
U1[User A] -- invoice UUID --> SW[Shared Wallet]
U2[User B] -- invoice UUID --> SW
SW --> EX[Exchange Ledger]
```

**Unique deposit address flow**

```mermaid
graph LR
U1[User A] --> W1[Wallet A]
W1 --> EX[Exchange Ledger]
U2[User B] --> W2[Wallet B]
W2 --> EX
```

**Comparison table**

| Criteria | Invoice-based deposits | Unique deposit addresses |
| ---------------------------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Security exposure | One shared hot wallet; a key leak drains the full pool | Each wallet isolates funds; compromise affects only the impacted user |
| User input requirements | User must include an invoice ID comment; missing or malformed comments need manual recovery workflows | User only needs the destination address |
| Parsing and validation | Backend parses comments on every deposit and matches to invoices | No parsing; deposit attribution is address-based |
| Deployment and storage costs | Deploy and maintain a single wallet; storage rent limited to that contract | Deploy many wallets; storage rent and deployment gas scale with user count |
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need a link to the storage rent explanation. This is more or less unique to TON blockchain

| Monitoring workload | Poll one address; comment parsing adds CPU but RPC calls stay low | Track many addresses; RPC queries and state tracking grow with the active user base |
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

link to RPC page

| Withdrawal handling | Highload wallet can batch withdrawals from one balance | Need sweeps or coordinated withdrawals from many wallets; extra gas and sequencing logic |
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

highload wallet is mentioned here for the first time -- needs a link

| Sharding behavior | All activity hits one shard; throughput limited by that shard | Wallets are distributed across shards; helps spread load |
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

link to the page explaining sharding


## Invoice-based deposits

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.

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.

Transaction comments in TON use the text message format; read more in [How TON wallets work](/standard/wallets/how-it-works).

<Aside
type="danger"
title="Funds at risk"
>
Risk: deposits without the correct invoice identifier may be lost.
Scope: incoming transfers to the shared deposit address.
Mitigation: enforce invoice format; reject or hold unmatched deposits; provide a recovery workflow; document comment entry in the UI.
Environment: validate the full flow on testnet before enabling mainnet.
</Aside>

**Advantages**:

- Single wallet simplifies key management
- Reduced gas costs for deployments
- Withdrawals can batch multiple user requests into one transaction using a Highload wallet
- The approach scales well for high transaction volumes
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sort of contradicts the sharding bottleneck clause


**Disadvantages**:

- Access leak to the single hot wallet could lead to all user funds loss
- Users must correctly input the invoice identifier, and mistakes result in lost or misdirected funds
- Comment parsing adds complexity
- Some user wallet applications don't support comments, limiting accessibility
- Single wallet network load [won't be sharded](/foundations/shards)

Reference education-only implementation: [Invoice-based Toncoin deposits](https://github.com/ton-org/docs-examples/blob/processing/guidebook/payment-processing/src/deposits/invoices.ts).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Reference education-only implementation: [Invoice-based Toncoin deposits](https://github.com/ton-org/docs-examples/blob/processing/guidebook/payment-processing/src/deposits/invoices.ts).
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).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add an "Aside" to mark this as "not production-ready code, use only for educational purposes"


## Unique deposit addresses

Unique address deposits generate 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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Unique address deposits generate 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.
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.


Implementation requires a wallet generation strategy. The most common approach uses a deterministic scheme based on a master seed and user identifiers. For V4 and V5 wallets, use different `subwallet_id` combinations. Alternatively, generate unique keypair per user, though this increases key management complexity.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Unclear what it means "master seed" and "user identifiers". Are these public keys (for user IDs)? Or something else?
  • V4 and V5 -- cross-links needed
  • subwallet_id -- link to the section explaining this concept (also, let's run this by other developers, because subwallet IDs can also be used for other purposes)
  • "keypair" -- link to the usage example


<Aside
type="danger"
title="Funds at risk"
>
Risk: funds sent to a non‑existent or wrong address are irrecoverable.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to link to the account status page

Scope: deposit address derivation and the first transfer to an un-deployed wallet.
Mitigation: derive addresses deterministically; verify checksum/ownership; send a small test transfer on testnet; use non‑bounceable for the first deposit; deploy immediately after receipt.
Environment: validate the full flow on testnet before using mainnet.
</Aside>

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 un-deployed address, send the transaction in non-bounceable mode. 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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

link to the place the distinction between bounceable and unbounceable messages is explained


Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's mention here in an "Aside" that sending unbounceable messages to nonexistent accounts without testing it first is particularly bad

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.

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.

<Aside
type="danger"
title="Keys and funds at risk"
>
Risk: leaked or mishandled private keys enable wallet takeover and fund loss.
Scope: generation, storage, and access to per-user wallet keys and deployment workflow.
Mitigation: encrypt keys at rest; restrict access; rotate keys; monitor deployment status; verify destination addresses before crediting deposits.
Environment: validate key management and deployment flow on testnet before mainnet.
</Aside>

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.

**Advantages**:

- No comment parsing removes a major source of user error
- Better security since each user has a unique keypair
- Transaction monitoring is straightforward - any incoming transaction to a user's address is their deposit

**Disadvantages**:

- Higher operational complexity managing multiple wallets
- Deployment costs multiply by the number of users
- Withdrawal processing requires coordination across wallets
- Storage fees apply to each deployed contract (currently \~0.001 TON per year per contract)

Reference education-only implementation: [Unique address Toncoin deposits](https://github.com/ton-org/docs-examples/blob/processing/guidebook/payment-processing/src/deposits/unique-addresses.ts).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Reference education-only implementation: [Unique address Toncoin deposits](https://github.com/ton-org/docs-examples/blob/processing/guidebook/payment-processing/src/deposits/unique-addresses.ts).
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).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, let's add an "Aside" to mark this as "not production-ready code, use only for educational purposes"


## Withdrawal batching

[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.

## Common abuse patterns

- Reusing a previously settled invoice identifier to trigger duplicate credits when the backend does not invalidate the invoice after first use.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- Reusing a previously settled invoice identifier to trigger duplicate credits when the backend does not invalidate the invoice after first use.
- Reusing a previously settled invoice identifier to trigger duplicate credits when the backend does not invalidate the invoice after the first use.

- Changing the Toncoin amount but leaving the original invoice identifier to obtain services at a lower price if expected amounts are not enforced.
- Crafting comments that mimic another users invoice identifier in order to hijack their pending credit.
- Submitting large numbers of dust payments to inflate processing costs or exhaust rate limits on transaction polling.

## Monitoring best practices

Implement exponential backoff for RPC failures. Network issues or node maintenance can interrupt transaction polling. When `getTransactions` fails, wait before retrying with increasing delays to avoid overwhelming the endpoint.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to link to the definition of getTransactions


Store transaction state persistently. Record the last processed `lt` value and transaction hash to resume monitoring after restarts without reprocessing transactions. This prevents duplicate deposit credits.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

explain lt means "logic time" and link to the corresponding page


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.

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.