Jetton Processing
Best Practices on Jettons Processing
Jettons are tokens on TON Blockchain - one can consider them similarly to ERC-20 tokens on Ethereum.
TON transactions are irreversible after just one confirmation. For the best UX/UI avoid additional waiting.
Withdrawal
Highload Wallet v3 - this is TON Blockchain latest solution which is the gold standard for jetton withdrawals. It allows you to take advantage of batched withdrawals.
Batched withdrawals - Meaning that multiple withdrawals are sent in batches, allowing for quick and cheap withdrawals.
Deposits
It is suggested to set several MEMO deposit wallets for better performance.
Memo Deposits - This allows you to keep one deposit wallet, and users add a memo in order to be identified by your system. This means that you don’t need to scan the entire blockchain, but is slightly less easy for users.
Memo-less deposits - This solution also exists, but is more difficult to integrate. However, we can assist with this, if you would prefer to take this route. Please notify us before deciding to implement this approach.
Additional Info
It is expected that every service in the Ecosystem will set the forward_ton_amount
to 0.000000001 TON (1 nanoton) when a jetton withdrawal is made in order to send a Jetton Notify upon successful transfer, otherwise the transfer will not be standard compliant and will not be able to be processed by other CEXes and services.
-
Please find the JS lib example - tonweb - which is the official JS library from the TON Foundation.
-
If you want to use Java, you can look into ton4j.
-
For Go, one should consider tonutils-go. At the moment, we recommend the JS lib.
Content List
In following docs offers details about Jettons architecture generally, as well as core concepts of TON which may be different from EVM-like and other blockchains. This is crucial reading in order for one to grasp a good understanding of TON, and will greatly help you.
This document describes the following in order:
- Overview
- Architecture
- Jetton Master Contract (Token Minter)
- Jetton Wallet Contract (User Wallet)
- Message Layouts
- Jetton Processing (off-chain)
- Jetton Processing (on-chain)
- Wallet processing
- Best Practices
Overview
TON transactions are irreversible after just one confirmation. For clear understanding, the reader should be familiar with the basic principles of asset processing described in this section of our documentation. In particular, it is important to be familiar with contracts, wallets, messages and deployment process.
For the best user experience, it is suggested to avoid waiting on additional blocks once transactions are finalized on the TON Blockchain. Read more in the Catchain.pdf.
Quick jump to the core description of jetton processing:
Centralized ProcessingOn-Chain Processing
TON Blockchain and its underlying ecosystem classifies fungible tokens (FTs) as jettons. Because sharding is applied on TON Blockchain, our implementation of fungible tokens is unique when compared to similar blockchain models.
In this analysis, we take a deeper dive into the formal standards detailing jetton behavior and metadata. A less formal sharding-focused overview of jetton architecture can be found in our anatomy of jettons blog post.
We have also provided specific details discussing our third-party open-source TON Payment Processor (bicycle) which allows users to deposit and withdraw both Toncoin and jettons using a separate deposit address without using a text memo.
Jetton Architecture
Standardized tokens on TON are implemented using a set of smart contracts, including:
- Jetton master smart contract
- Jetton wallet smart contracts
Jetton master smart contract
The jetton master smart contract stores general information about the jetton (including the total supply, a metadata link, or the metadata itself).
It is possible for any user to create a counterfeit clone of a valuable jetton (using an arbitrary name, ticker, image, etc.) that is nearly identical to the original. Thankfully, counterfeit jettons are distinguishable by their addresses and can be identified quite easily.
Jettons with the symbol
==TON
or those that contain system notification messages, such as:
ERROR
, SYSTEM
, and others. Be sure to check that jettons are displayed in your interface in such a way that they cannot
be mixed with TON transfers, system notifications, etc.. At times, even the symbol
,name
and image
will be created to look nearly identical to the original with the hopes of misleading users.
To eliminate the possibility of fraud for TON users, please look up the original jetton address (Jetton master contract) for specific jetton types or follow the project’s official social media channel or website to find the correct information. Check assets to eliminate the possibility of fraud with Tonkeeper ton-assets list.
Retrieving Jetton data
To retrieve more specific Jetton data use contract's get method get_jetton_data()
.
This method returns the following data:
Name | Type | Description |
---|---|---|
total_supply | int | the total number of issued jettons measured in indivisible units. |
mintable | int | details whether new jettons can be minted or not. This value is either -1 (can be minted) or 0 (cannot be minted). |
admin_address | slice | |
jetton_content | cell | data in accordance with TEP-64, check jetton metadata parsing page for more. |
jetton_wallet_code | cell |
It is also possible to use the method /jetton/masters
from the Toncenter API to retrieve the already decoded Jetton data and metadata. We have also developed methods for (js) tonweb and (js) ton-core/ton, (go) tongo and (go) tonutils-go, (python) pytonlib and many other SDKs.
Example of using Tonweb to run a get method and get url for off-chain metadata:
import TonWeb from "tonweb";
const tonweb = new TonWeb();
const jettonMinter = new TonWeb.token.jetton.JettonMinter(tonweb.provider, {address: "<JETTON_MASTER_ADDRESS>"});
const data = await jettonMinter.getJettonData();
console.log('Total supply:', data.totalSupply.toString());
console.log('URI to off-chain metadata:', data.jettonContentUri);
Jetton minter
As mentioned before, jettons can be either mintable
or non-mintable
.
If they are non-mintable, the logic becomes simple—there is no way to mint additional tokens. To mint jettons for the first time, refer to the Mint your first jetton page.
If the jettons are mintable, there is a special function in the minter contract to mint additional jettons. This function can be called by sending an internal message
with a specified opcode from the admin address.
If the jetton admin wants to restrict jetton creation, there are three ways to do it:
- If you can't or do not want to update the contract's code, the admin needs to transfer ownership from the current admin to the zero address. This will leave the contract without a valid admin, thus preventing anyone from minting jettons. However, it will also prevent any changes to the jetton metadata.
- If you have access to source code and can change it, you can create a method in the contract that sets a flag to abort any minting process after it is called, and add a statement to check this flag in the mint function.
- If you can update contract's code, you can add restrictions by updating the code of the already deployed contract.
Jetton wallet smart contract
Jetton wallet
contracts are used to send, receive, and burn jettons. Each jetton wallet contract stores wallet balance information for specific users.
In specific instances, jetton wallets are used for individual jetton holders for each jetton type.
Jetton wallets
should not be confused with wallet’s meant for blockchain interaction and storing
only the Toncoin asset (e.g., v3R2 wallets, highload wallets, and others),
which is responsible for supporting and managing only a specific jetton type.
Jetton Wallet Deployment
When transferring jettons
between wallets, transactions (messages) require a certain amount of TON
as payment for network gas fees and the execution of actions according to the Jetton wallet contract's code.
This means that the recipient does not need to deploy a jetton wallet prior to receiving jettons.
The recipient's jetton wallet will be deployed automatically as long as the sender holds enough TON
in the wallet to pay the required gas fees.
Retrieving Jetton wallet addresses for a given user
To retrieve a jetton wallet
address
using an owner address
(a TON Wallet address),
the Jetton master contract
provides the get method get_wallet_address(slice owner_address)
.
- API
- js
Run
get_wallet_address(slice owner_address)
through/runGetMethod
method from the Toncenter API. In real cases (not test ones) it is important to always check that wallet indeed is attributed to desired Jetton Master. Check code example for more.
import TonWeb from 'tonweb';
const tonweb = new TonWeb();
const jettonMinter = new TonWeb.token.jetton.JettonMinter(tonweb.provider, { address: '<JETTON_MASTER_ADDRESS>' });
const jettonWalletAddress = await jettonMinter.getJettonWalletAddress(new TonWeb.utils.Address('<OWNER_WALLET_ADDRESS>'));
// It is important to always check that wallet indeed is attributed to desired Jetton Master:
const jettonWallet = new TonWeb.token.jetton.JettonWallet(tonweb.provider, {
address: jettonWalletAddress
});
const jettonData = await jettonWallet.getData();
if (jettonData.jettonMinterAddress.toString(false) !== jettonMinter.address.toString(false)) {
throw new Error('jetton minter address from jetton wallet doesnt match config');
}
console.log('Jetton wallet address:', jettonWalletAddress.toString(true, true, true));
For more examples read the TON Cookbook.
Retrieving data for a specific Jetton wallet
To retrieve the wallet’s account balance, owner identification information, and other info related to a specific jetton wallet contract use the get_wallet_data()
get method within the jetton wallet contract.
This method returns the following data:
Name | Type |
---|---|
balance | int |
owner | slice |
jetton | slice |
jetton_wallet_code | cell |
- API
- js
Use the
/jetton/wallets
get method from the Toncenter API to retrieve previously decoded jetton wallet data.
import TonWeb from "tonweb";
const tonweb = new TonWeb();
const walletAddress = "EQBYc3DSi36qur7-DLDYd-AmRRb4-zk6VkzX0etv5Pa-Bq4Y";
const jettonWallet = new TonWeb.token.jetton.JettonWallet(tonweb.provider,{address: walletAddress});
const data = await jettonWallet.getData();
console.log('Jetton balance:', data.balance.toString());
console.log('Jetton owner address:', data.ownerAddress.toString(true, true, true));
// It is important to always check that Jetton Master indeed recognize wallet
const jettonMinter = new TonWeb.token.jetton.JettonMinter(tonweb.provider, {address: data.jettonMinterAddress.toString(false)});
const expectedJettonWalletAddress = await jettonMinter.getJettonWalletAddress(data.ownerAddress.toString(false));
if (expectedJettonWalletAddress.toString(false) !== new TonWeb.utils.Address(walletAddress).toString(false)) {
throw new Error('jetton minter does not recognize the wallet');
}
console.log('Jetton master address:', data.jettonMinterAddress.toString(true, true, true));
Message Layouts
Read more about Messages here.
Communication between Jetton wallets and TON wallets occurs through the following communication sequence:
Message 0
Sender -> sender's jetton wallet
. Transfer message contains the following data:
Name | Type | Description |
---|---|---|
query_id | uint64 | Allows applications to link three messaging types Transfer , Transfer notification and Excesses to each other. For this process to be carried out correctly it is recommended to always use a unique query id. |
amount | coins | Total ton coin amount, that will be send with message. |
destination | address | Address of the new owner of the jettons |
response_destination | address | Wallet address used to return remained ton coins with excesses message. |
custom_payload | maybe cell | Size always is >= 1 bit. Custom data (which is used by either sender or receiver jetton wallet for inner logic). |
forward_ton_amount | coins | Must be > 0 if you want to send transfer notification message with forward payload . It's a part of amount value and must be lesser than amount |
forward_payload | maybe cell | Size always is >= 1 bit. If first 32 bits = 0x0 it's just a simple message. |
Message 2'
payee's jetton wallet -> payee
. Transfer notification message. Only sent if forward_ton_amount
not zero. Contains the following data:
Name | Type |
---|---|
query_id | uint64 |
amount | coins |
sender | address |
forward_payload | cell |
Here sender
address is an address of Alice's Jetton wallet
.
Message 2''
payee's jetton wallet -> Sender
. Excess message body. Only sent if any ton coins are left after paying the fees. Contains the following data:
Name | Type |
---|---|
query_id | uint64 |
A detailed description of the jetton wallet contract fields can be found in the TEP-74 Jetton standard
interface description.
How to send Jetton transfers with comments and notifications
This transfer require some ton coins for fees and transfer notification message.
To send comment you need to set up forward payload
. Set first 32 bits to 0x0 and append your text, forward payload
is sent in jetton notify 0x7362d09c
internal message. It will be generated only if forward_ton_amount
> 0.
Recommended forward_ton_amount
for jetton transfer with comment is 1 nanoton.
Finally, to retrieve Excess 0xd53276db
message you must set up response destination
.
Sometimes, you may encounter an error 709
when sending a jetton. This error indicates that the amount of Toncoin attached to the message is not sufficient to send it. Make sure that Toncoin > to_nano(TRANSFER_CONSUMPTION) + forward_ton_amount
, which is typically >0.04 unless the forward payload is very large. The commission depends on various factors, including the Jetton code details and whether a new Jetton wallet needs to be deployed for the recipient.
It is recommended to add a margin of Toncoin to the message and set your address as the response_destination
to retrieve Excess 0xd53276db
messages. For instance, you can add 0.05 TON to the message, while setting the forward_ton_amount
to 1 nanoton (this amount of TON will be attached to the jetton notify 0x7362d09c
message).
You may also encounter the error cskip_no_gas
, which indicates that the jettons were successfully transferred, but no other calculations were performed. This is a common situation when the value of forward_ton_amount
is equal to 1 nanoton.
Check best practices for "send jettons with comments" example.
Jetton off-chain processing
TON transactions are irreversible after just one confirmation. For the best user experience, it is suggested to avoid waiting on additional blocks once transactions are finalized on the TON Blockchain. Read more in the Catchain.pdf.
There are two ways to accept Jettons:
- within a centralized hot wallet.
- using a wallet with a separate address for each individual user.
For security reasons it is preferable to be in possession of separate hot wallets for separate Jettons (many wallets for each asset type).
When processing funds, it is also recommended to provide a cold wallet for storing excess funds which do not participate in the automatic deposit and withdrawal processes.
Adding new Jettons for asset processing and initial verification
- Find correct smart contract address.
- Get metadata.
- Check for a scam.
Identification of an unknown Jetton when receiving a transfer notification message
If a transfer notification message is received within your wallet regarding an unknown Jetton, then your wallet has been created to hold the specific Jetton.
The sender address of the internal message containing the Transfer notification
body is the address of the new Jetton wallet.
It should not to be confused with the sender
field in the Transfer notification
body.
- Retrieve the Jetton master address for the new Jetton wallet by getting wallet data.
- Retrieve the Jetton wallet address for your wallet address (as an owner) using the Jetton master contract: How to retrieve Jetton wallet address for a given user
- Compare the address returned by the master contract and the actual address of the wallet token. If they match, it’s ideal. If not, then you likely received a scam token that is counterfeit.
- Retrieve Jetton metadata: How to receive Jetton metadata.
- Check the
symbol
andname
fields for signs of a scam. Warn the user if necessary. Adding a new Jettons for processing and initial checks.
Accepting Jettons from users through a centralized wallet
To prevent a bottleneck in incoming transactions to a single wallet, it is suggested to accept deposits across multiple wallets and to expand the number of these wallets as needed.
It is expected that every service in the Ecosystem will set the forward_ton_amount
to 0.000000001 TON (1 nanoton) when a jetton withdrawal is made in order to send a Jetton Notify upon successful transfer, otherwise the transfer will not be standard compliant and will not be able to be processed by other CEXes and services.
In this scenario, the payment service creates a unique memo identifier for each sender disclosing the address of the centralized wallet and the amounts being sent. The sender sends the tokens to the specified centralized address with the obligatory memo in the comment.
Pros of this method: this method is very simple because there are no additional fees when accepting tokens and they are retrieved directly in the hot wallet.
Cons of this method: this method requires that all users attach a comment to the transfer which can lead to a greater number of deposit mistakes (forgotten memos, incorrect memos, etc.), meaning a higher workload for support staff.
Tonweb examples:
- Accepting Jetton deposits to an individual HOT wallet with comments (memo)
- Jettons withdrawals example
Preparations
- Prepare a list of accepted Jettons (Jetton master addresses).
- Deploy hot wallet (using v3R2 if no Jetton withdrawals are expected; highload v3 - if Jetton withdrawals are expected). Wallet deployment.
- Perform a test Jetton transfer using the hot wallet address to initialize the wallet.
Processing incoming Jettons
- Load the list of accepted Jettons.
- Retrieve a Jetton wallet address for your deployed hot wallet.
- Retrieve a Jetton master address for each Jetton wallet using getting wallet data.
- Compare the addresses of the Jetton master contracts from step 1. and step 3 (directly above). If the addresses do not match, a Jetton address verification error must be reported.
- Retrieve a list of the most recent unprocessed transactions using a hot wallet account and iterate it (by sorting through each transaction one by one). See: Checking contract's transactions.
- Check the input message (in_msg) for transactions and retrieve the source address from the input message. Tonweb example
- If the source address matches the address within a Jetton wallet, then it is necessary to continue processing the transaction. If not, then skip processing the transaction and check the next transaction.
- Ensure that the message body is not empty and that the first 32 bits of the message match the
transfer notification
op code0x7362d09c
. Tonweb example If the message body is empty or the op code is invalid - skip the transaction. - Read the message body’s other data, including the
query_id
,amount
,sender
,forward_payload
. Jetton contracts message layouts, Tonweb example - Try to retrieve text comments from the
forward_payload
data. The first 32 bits must match the text comment op code0x00000000
and the remaining - UTF-8 encoded text. Tonweb example - If the
forward_payload
data is empty or the op code is invalid - skip the transaction. - Compare the received comment with the saved memos. If there is a match (user identification is always possible) - deposit the transfer.
- Restart from step 5 and repeat the process until you have walked through the entire list of transactions.
Accepting Jettons from user deposit addresses
To accept Jettons from user deposit addresses, it is necessary that the payment service creates its own individual address (deposit) for each participant sending funds. The service provision in this case involves the execution of several parallel processes including creating new deposits, scanning blocks for transactions, withdrawing funds from deposits to a hot wallet, and so on.
Because a hot wallet can make use of one Jetton wallet for each Jetton type, it is necessary to create multiple
wallets to initiate deposits. In order to create a large number of wallets, but at the same time manage them with
one seed phrase (or private key), it is necessary to specify a different subwallet_id
when creating a wallet.
On TON, the functionality required to create a subwallet is supported by version v3 wallets and higher.
Creating a subwallet in Tonweb
const WalletClass = tonweb.wallet.all['v3R2'];
const wallet = new WalletClass(tonweb.provider, {
publicKey: keyPair.publicKey,
wc: 0,
walletId: <SUBWALLET_ID>,
});
Preparation
- Prepare a list of accepted Jettons.
- Deploy hot wallet (using v3R2 if no Jetton withdrawals are expected; highload v3 - if Jetton withdrawals are expected). Wallet deployment.
Creating deposits
- Accept a request to create a new deposit for the user.
- Generate a new subwallet (/v3R2) address based on the hot wallet seed. Creating a subwallet in Tonweb
- The receiving address can be given to the user as the address used for Jetton deposits (this is the address of the owner of the deposit Jetton wallet). Wallet initialization is not required, this can be accomplished when withdrawing Jettons from the deposit.
- For this address, it is necessary to calculate the address of the Jetton wallet through the Jetton master contract. How to retrieve a Jetton wallet address for a given user.
- Add the Jetton wallet address to the address pool for transaction monitoring and save the subwallet address.
Processing transactions
TON transactions are irreversible after just one confirmation. For the best user experience, it is suggested to avoid waiting on additional blocks once transactions are finalized on the TON Blockchain. Read more in the Catchain.pdf.
It is not always possible to determine the exact amount of Jettons received from the message, because Jetton
wallets may not send transfer notification
, excesses
, and internal transfer
messages. They are not standardized. This means
that there is no guarantee that the internal transfer
message can be decoded.
Therefore, to determine the amount received in the wallet, balances need to be requested using the get method. To retrieve key data when requesting balances, blocks are used according to the account’s state for a particular block on-chain. Preparation for block acceptance using Tonweb.
This process is conducted as follows:
- Preparation for block acceptance (by readying the system to accept new blocks).
- Retrieve a new block and save the previous block ID.
- Receive transactions from blocks.
- Filter transactions used only with addresses from the deposit Jetton wallet pool.
- Decode messages using the
transfer notification
body to receive more detailed data including thesender
address, Jettonamount
and comment. (See: Processing incoming Jettons) - If there is at least one transaction with non-decodable out messages (the message body does not contain op codes for
transfer notification
and op codes forexcesses
) or without out messages present within the account, then the Jetton balance must be requested using the get method for the current block, while the previous block is used to calculate the difference in balances. Now the total balance deposit changes are revealed due to the transactions being conducted within the block. - As an identifier for an unidentified transfer of Jettons (without a
transfer notification
), transaction data can be used if there is one such transaction or block data present (if several are present within a block). - Now it’s necessary to check to ensure the deposit balance is correct. If the deposit balance is sufficient enough to initiate a transfer between a hot wallet and the existing Jetton wallet, Jettons need to be withdrawn to ensure the wallet balance has decreased.
- Restart from step 2 and repeat the entire process.
Withdrawals made from deposits
Transfers should not be made from a deposit to a hot wallet with each deposit replenishment, because a commission in TON is taken for the transfer operation (paid in network gas fees). It is important to determine a certain minimum amount of Jettons which are required to make a transfer worthwhile (and thus deposit).
By default, wallet owners of Jetton deposit wallets are not initialized. This is because there is no predetermined
requirement to pay storage fees. Jetton deposit wallets can be deployed when sending messages with a
transfer
body which can then be destroyed immediately. To do this, the engineer must use a special
mechanism for sending messages: 128 + 32.
- Retrieve a list of deposits marked for withdrawal to a hot wallet
- Retrieve saved owner addresses for each deposit
- Messages are then sent to each owner address (by combining several such messages into a batch) from a highload
wallet with an attached TON Jetton amount. This is determined by adding the fees used for v3R2 wallet
initialization + the fees for sending a message with the
transfer
body + an arbitrary TON amount related to theforward_ton_amount
(if necessary). The attached TON amount is determined by adding the fees for v3R2 wallet initialization (value) + the fees for sending a message with thetransfer
body (value) + an arbitrary TON amount forforward_ton_amount
(value) (if necessary). - When the balance on the address becomes non-zero, the account status changes. Wait a few seconds and check the status
of the account, it will soon change from the
nonexists
state touninit
. - For each owner address (with
uninit
status), it is necessary to send an external message with the v3R2 wallet init and body with thetransfer
message for depositing into the Jetton wallet = 128 + 32. For thetransfer
, the user must specify the address of the hot wallet as thedestination
andresponse destination
. A text comment can be added to make it simpler to identify the transfer. - It is possible to verify Jetton delivery using the deposit address to the hot wallet address by taking into consideration the processing of incoming Jettons info found here.
Jetton withdrawals
It's recommended to read and understand how does jetton transfer work and how to send jettons with comment articles before reading this section.
Below you'll find step-by-step guide how to process jetton withdrawals.
To withdraw Jettons, the wallet sends messages with the transfer
body to its corresponding Jetton wallet.
The Jetton wallet then sends the Jettons to the recipient. It is important to attach some TON (1 nanoTON at least)
as the forward_ton_amount
(and optional comment to forward_payload
) to trigger a transfer notification
.
See: Jetton contracts message layouts
Preparation
- Prepare a list of Jettons for withdrawals: Adding new Jettons for processing and initial verification
- Hot wallet deployment is initiated. Highload v3 is recommended. Wallet Deployment
- Carry out a Jetton transfer using a hot wallet address to initialize the Jetton wallet and replenish its balance.