diff --git a/cspell.json b/cspell.json index 047ade6457..9336df7dab 100644 --- a/cspell.json +++ b/cspell.json @@ -4,9 +4,9 @@ "language": "en", "files": [ "**/*.md", - "**/*.mdx", + "**/*.mdx" ], - "dictionaries": ["tvm-instructions", "names", "commands"], + "dictionaries": ["tvm-instructions", "names", "commands", "examples"], "dictionaryDefinitions": [ { "name":"tvm-instructions", @@ -20,6 +20,10 @@ "name":"commands", "path":"./src/grammar/commands-dictionary.txt" }, + { + "name":"examples", + "path":"./src/grammar/examples-dictionary.txt" + }, ], "words": [ "ADNL", @@ -103,6 +107,7 @@ "Threadripper", "Threadripper-based", "Timeouted", + "Tolk", "Toncoin", "Toncoins", "Underload", @@ -175,6 +180,7 @@ "hmac", "howto", "HOWTO", + "idict", "inclusivity", "inplace", "int", @@ -196,12 +202,14 @@ "liteservers", "logname", "long", + "lowlevel", "masterchain", "mathrm", "mintless", "micropayment", "micropayments", "mintable", + "moddiv", "multichain", "multisignature", "mystore", @@ -217,6 +225,7 @@ "nonfinal", "penalising", "penalised", + "pfxdict", "precomplied", "preimage", "prer", @@ -259,6 +268,7 @@ "sunt", "superserver", "tick-tock", + "tilda", "timeouted", "tock", "tokenomics", @@ -266,6 +276,7 @@ "udict", "uint", "unbounceable", + "uncons", "underload", "underloaded", "unixtime", @@ -300,6 +311,7 @@ ], "flagWords": [], "ignorePaths": [ + "scripts", "static", "node_modules", "package.json", @@ -313,6 +325,6 @@ "sidebars.js", "sidebars", "i18n", - ".husky", + ".husky" ] } diff --git a/docs/v3/concepts/dive-into-ton/go-from-ethereum/difference-of-blockchains.md b/docs/v3/concepts/dive-into-ton/go-from-ethereum/difference-of-blockchains.md index b4d70de9cc..9000b67042 100644 --- a/docs/v3/concepts/dive-into-ton/go-from-ethereum/difference-of-blockchains.md +++ b/docs/v3/concepts/dive-into-ton/go-from-ethereum/difference-of-blockchains.md @@ -14,7 +14,7 @@ Ethereum, by inheriting and extending the foundational principles of Bitcoin, ha In response to these challenges, TON offers an alternative approach aimed at improving scalability and performance. Designed with the ambition to provide developers with maximum flexibility to create a variety of applications, TON uses the concept of shards and masterchain to optimize the block creation process. In each TON shardchain and masterchain, a new block is generated on average every 5 seconds, ensuring fast transaction execution. Unlike Ethereum, where state updates are synchronous, TON implements asynchronous messaging between smart contracts, allowing each transaction to be processed independently and in parallel, significantly speeding up transaction processing on the network. Sections and articles to familiarize yourself with: -* [Shards](/v3/documentation/smart-contracts/shards) +* [Shards](/v3/documentation/smart-contracts/shards/shards-intro) * [Comparison of Blockchains document](https://ton.org/comparison_of_blockchains.pdf) * [Comparison of Blockchains table (much less informative than the document, but more visual)](/v3/concepts/dive-into-ton/ton-blockchain/blockchain-comparison) diff --git a/docs/v3/concepts/dive-into-ton/go-from-ethereum/solidity-vs-func.md b/docs/v3/concepts/dive-into-ton/go-from-ethereum/solidity-vs-func.md index dd276761e2..9b6b0359c5 100644 --- a/docs/v3/concepts/dive-into-ton/go-from-ethereum/solidity-vs-func.md +++ b/docs/v3/concepts/dive-into-ton/go-from-ethereum/solidity-vs-func.md @@ -208,7 +208,7 @@ var msg = begin_cell() send_raw_message(msg, mode); ``` Let's discuss in more detail what it looks like for our smart contract to send a message to our recipient: -1. Initially, we need to build our message. The full structure of the send can be found [here](v3/documentation/smart-contracts/message-management/sending-messages). We won't go into detail on how to assemble it here, you can read about that at the link. +1. Initially, we need to build our message. The full structure of the send can be found [here](/v3/documentation/smart-contracts/message-management/sending-messages). We won't go into detail on how to assemble it here, you can read about that at the link. 2. The body of the message represents a cell. In `msg_body_cell` we do: `begin_cell()` - creates `Builder` for the future cell, first `store_uint` - stores the first uint into `Builder` (1 - this is our `op`), second `store_uint` - stores the second uint into `Builder` (num - this is our number that we will manipulate in the receiving contract), `end_cell()` - creates the cell. 3. To attach the body that will come in `recv_internal` in the message, we reference the collected cell in the message itself with `store_ref`. 4. Sending a message. diff --git a/docs/v3/concepts/dive-into-ton/ton-blockchain/sharding.md b/docs/v3/concepts/dive-into-ton/ton-blockchain/sharding.md index 93e5ef1a43..e534b5fd95 100644 --- a/docs/v3/concepts/dive-into-ton/ton-blockchain/sharding.md +++ b/docs/v3/concepts/dive-into-ton/ton-blockchain/sharding.md @@ -21,5 +21,5 @@ In addition to the dynamic creation of shards, TON uses **Split Merge** function ## See Also -* [Shards Dive In](/v3/documentation/smart-contracts/shards) -* [# Infinity Sharding Paradigm](/v3/documentation/smart-contracts/infinity-sharding-paradigm) +* [Shards Dive In](/v3/documentation/smart-contracts/shards/shards-intro) +* [# Infinity Sharding Paradigm](/v3/documentation/smart-contracts/shards/infinity-sharding-paradigm) diff --git a/docs/v3/concepts/qa-outsource/auditors.mdx b/docs/v3/concepts/qa-outsource/auditors.mdx index 1abd7af1e4..3ed76dac3f 100644 --- a/docs/v3/concepts/qa-outsource/auditors.mdx +++ b/docs/v3/concepts/qa-outsource/auditors.mdx @@ -14,6 +14,7 @@ Test your software with the following quality assurance providers. * [ton.tech](https://ton.tech/) * [trailofbits.com](https://www.trailofbits.com/) * [zellic.io](https://www.zellic.io/) +* [tonbit.xyz](https://www.tonbit.xyz/) ## See Also diff --git a/docs/v3/concepts/ton-blockchain/shards.md b/docs/v3/concepts/ton-blockchain/shards.md index 96af82cac3..39e6bef97a 100644 --- a/docs/v3/concepts/ton-blockchain/shards.md +++ b/docs/v3/concepts/ton-blockchain/shards.md @@ -21,5 +21,5 @@ In addition to the dynamic creation of shards, TON uses **Split Merge** function ## See Also -* [Shards Dive In](/v3/documentation/smart-contracts/shards) -* [# Infinity Sharding Paradigm](/v3/documentation/smart-contracts/infinity-sharding-paradigm) +* [Shards Dive In](/v3/documentation/smart-contracts/shards/shards-intro) +* [# Infinity Sharding Paradigm](/v3/documentation/smart-contracts/shards/infinity-sharding-paradigm) diff --git a/docs/v3/contribute/docs/schemes-guidelines.mdx b/docs/v3/contribute/docs/schemes-guidelines.mdx index 91741191e3..ba0af8c1c6 100644 --- a/docs/v3/contribute/docs/schemes-guidelines.mdx +++ b/docs/v3/contribute/docs/schemes-guidelines.mdx @@ -42,7 +42,7 @@ If the order of transactions doesn't matter, you can omit their labels. This sim -Learn references directly from Visio [message-processing.vsdx](/static/schemes-visio/message-processing.vsdx). +Learn references directly from Visio [message-processing.vsdx](/schemes-visio/message-processing.vsdx). ### Formats and Colors diff --git a/docs/v3/documentation/dapps/oracles/red_stone.mdx b/docs/v3/documentation/dapps/oracles/red_stone.mdx index e0c03e2d34..4638eb9607 100644 --- a/docs/v3/documentation/dapps/oracles/red_stone.mdx +++ b/docs/v3/documentation/dapps/oracles/red_stone.mdx @@ -19,7 +19,7 @@ To learn more about RedStone oracles design go to the [RedStone docs](https://do ### price_manager.fc - Sample oracle contract that consumes RedStone oracles data [price_manager.fc](https://github.com/redstone-finance/redstone-oracles-monorepo/blob/main/packages/ton-connector/contracts/price_manager.fc) written in - FunC. It requires [TVM Upgrade 2023.07](v3/documentation/tvm/changelog/tvm-upgrade-2023-07). + FunC. It requires [TVM Upgrade 2023.07](/v3/documentation/tvm/changelog/tvm-upgrade-2023-07). #### initial data diff --git a/docs/v3/documentation/data-formats/tlb/tl-b-language.mdx b/docs/v3/documentation/data-formats/tlb/tl-b-language.mdx index b22181552b..e2b5535ad0 100644 --- a/docs/v3/documentation/data-formats/tlb/tl-b-language.mdx +++ b/docs/v3/documentation/data-formats/tlb/tl-b-language.mdx @@ -5,7 +5,7 @@ import ThemedImage from '@theme/ThemedImage'; TL-B (Type Language - Binary) serves to describe the type system, constructors and existing functions. For example, we can use TL-B schemes to build binary structures associated with TON Blockchain. Special TL-B parsers can read schemes to deserialize binary data into different objects. TL-B describes data schemes for `Cell` objects. If you not familiar -with `Cells`, please read [Cell & Bag of Cells(BOC)](v3/documentation/data-formats/tlb/cell-boc#cell) article. +with `Cells`, please read [Cell & Bag of Cells(BOC)](/v3/documentation/data-formats/tlb/cell-boc#cell) article. ## Overview @@ -516,7 +516,7 @@ unary_succ$1 {n:#} x:(Unary ~n) = Unary ~(n + 1); _ u:(Unary Any) = UnaryChain; ``` -This is example has good explanation in [TL-B Types](v3/documentation/data-formats/tlb/tl-b-types#unary) +This is example has good explanation in [TL-B Types](/v3/documentation/data-formats/tlb/tl-b-types#unary) article. The main idea here is that `UnaryChain` will recursively deserialize until reach of `unary_zero$0` (because we know last element of `Unary X` type by definition `unary_zero$0 = Unary ~0;` and `X` is calculated in runtime due `Unary ~(n + 1)` definition). diff --git a/docs/v3/documentation/data-formats/tlb/transaction-layout.md b/docs/v3/documentation/data-formats/tlb/transaction-layout.md index 04eb6bfe12..41821d21ef 100644 --- a/docs/v3/documentation/data-formats/tlb/transaction-layout.md +++ b/docs/v3/documentation/data-formats/tlb/transaction-layout.md @@ -22,8 +22,8 @@ transaction$0111 account_addr:bits256 lt:uint64 | Field | Type | Required | Description | | ----------------- | ---------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_addr` | bits256 | Yes | The hash part of the address on which the transaction was executed. [More about addresses](v3/documentation/smart-contracts/addresses#address-of-smart-contract) | -| `lt` | uint64 | Yes | Represents _Logical time_. [More about logical time](v3/documentation/smart-contracts/message-management/messages-and-transactions#what-is-a-logical-time) | +| `account_addr` | bits256 | Yes | The hash part of the address on which the transaction was executed. [More about addresses](/v3/documentation/smart-contracts/addresses#address-of-smart-contract) | +| `lt` | uint64 | Yes | Represents _Logical time_. [More about logical time](/v3/documentation/smart-contracts/message-management/messages-and-transactions#what-is-a-logical-time) | | `prev_trans_hash` | bits256 | Yes | The hash of the previous transaction on this account. | | `prev_trans_lt` | uint64 | Yes | The `lt` of the previous transaction on this account. | | `now` | uint32 | Yes | The `now` value that was set when executing this transaction. It's a Unix timestamp in seconds. | @@ -32,7 +32,7 @@ transaction$0111 account_addr:bits256 lt:uint64 | `end_status` | [AccountStatus](#accountstatus) | Yes | The status of this account after executing the transaction. | | `in_msg` | (Message Any) | No | The incoming message that triggered the execution of the transaction. Stored in a reference. | | `out_msgs` | HashmapE 15 ^(Message Any) | Yes | The dictionary that contains the list of outgoing messages that were created while executing this transaction. | -| `total_fees` | [CurrencyCollection](/v3/documentation/data-formats/tlb/msg-tlb#currencycollection) | Yes | The total amount of fees that were collected while executing this transaction. It consists of a _Toncoin_ value and possibly some [Extra-currencies](v3/documentation/dapps/defi/coins#extra-currencies). | +| `total_fees` | [CurrencyCollection](/v3/documentation/data-formats/tlb/msg-tlb#currencycollection) | Yes | The total amount of fees that were collected while executing this transaction. It consists of a _Toncoin_ value and possibly some [Extra-currencies](/v3/documentation/dapps/defi/coins#extra-currencies). | | `state_update` | [HASH_UPDATE](#hash_update) Account | Yes | The `HASH_UPDATE` structure. Stored in a reference. | | `description` | [TransactionDescr](#transactiondescr-types) | Yes | A detailed description of the transaction execution process. Stored in a reference. | @@ -89,12 +89,12 @@ trans_ord$0000 credit_first:Bool | Field | Type | Required | Description | | -------------- | -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `credit_first` | Bool | Yes | A flag that correlates with `bounce` flag of an incoming message. `credit_first = !bounce` | -| `storage_ph` | TrStoragePhase | No | Contains information about storage phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `credit_ph` | TrCreditPhase | No | Contains information about credit phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | +| `storage_ph` | TrStoragePhase | No | Contains information about storage phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `credit_ph` | TrCreditPhase | No | Contains information about credit phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | | `aborted` | Bool | Yes | Indicates whether the transaction execution was aborted. | -| `bounce` | TrBouncePhase | No | Contains information about bounce phase of a transaction execution. [More Info](v3/documentation/smart-contracts/message-management/non-bounceable-messages) | +| `bounce` | TrBouncePhase | No | Contains information about bounce phase of a transaction execution. [More Info](/v3/documentation/smart-contracts/message-management/non-bounceable-messages) | | `destroyed` | Bool | Yes | Indicates whether the account was destroyed during the execution. | ## Storage @@ -108,7 +108,7 @@ trans_storage$0001 storage_ph:TrStoragePhase | Field | Type | Description | | ------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `storage_ph` | TrStoragePhase | Contains information about storage phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `storage_ph` | TrStoragePhase | Contains information about storage phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | ## Tick-tock @@ -123,9 +123,9 @@ trans_tick_tock$001 is_tock:Bool storage_ph:TrStoragePhase | Field | Type | Required | Description | | ------------ | -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `is_tock` | Bool | Yes | A flag indicating the type of transaction. Used to separate `Tick` and `Tock` transactions | -| `storage_ph` | TrStoragePhase | Yes | Contains information about storage phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | +| `storage_ph` | TrStoragePhase | Yes | Contains information about storage phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | | `aborted` | Bool | Yes | Indicates whether the transaction execution was aborted. | | `destroyed` | Bool | Yes | Indicates whether the account was destroyed during the execution. | @@ -150,9 +150,9 @@ trans_split_prepare$0100 split_info:SplitMergeInfo | Field | Type | Required | Description | | ------------ | -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `split_info` | SplitMergeInfo | Yes | Information about split process. | -| `storage_ph` | TrStoragePhase | No | Contains information about storage phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | +| `storage_ph` | TrStoragePhase | No | Contains information about storage phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | | `aborted` | Bool | Yes | Indicates whether the transaction execution was aborted. | | `destroyed` | Bool | Yes | Indicates whether the account was destroyed during the execution. | @@ -195,7 +195,7 @@ trans_merge_prepare$0110 split_info:SplitMergeInfo | Field | Type | Description | | ------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `split_info` | SplitMergeInfo | Information about merge process. | -| `storage_ph` | TrStoragePhase | Contains information about storage phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `storage_ph` | TrStoragePhase | Contains information about storage phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | | `aborted` | Bool | Indicates whether the transaction execution was aborted. | ## Merge install @@ -220,10 +220,10 @@ trans_merge_install$0111 split_info:SplitMergeInfo | --------------------- | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `split_info` | SplitMergeInfo | Yes | Information about merge process. | | `prepare_transaction` | [Transaction](#transaction) | Yes | Information about the [transaction prepared](#merge-prepare) for the merge operation. Stored in a reference. | -| `storage_ph` | TrStoragePhase | No | Contains information about storage phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `credit_ph` | TrCreditPhase | No | Contains information about credit phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases) | -| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | +| `storage_ph` | TrStoragePhase | No | Contains information about storage phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `credit_ph` | TrCreditPhase | No | Contains information about credit phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `compute_ph` | TrComputePhase | Yes | Contains information about compute phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases) | +| `action` | TrActionPhase | No | Contains information about action phase of a transaction execution. [More Info](/v3/documentation/tvm/tvm-overview#transactions-and-phases). Stored in a reference. | | `aborted` | Bool | Yes | Indicates whether the transaction execution was aborted. | | `destroyed` | Bool | Yes | Indicates whether the account was destroyed during the execution. | diff --git a/docs/v3/documentation/faq.md b/docs/v3/documentation/faq.md index 1b2959cfd3..4819944848 100644 --- a/docs/v3/documentation/faq.md +++ b/docs/v3/documentation/faq.md @@ -245,7 +245,7 @@ If the contract cannot initially execute `set_code()` (via its code or execution ### Can smart contract be deleted? -Yes, either as a result of storage fee accumulation (contract needs to reach -1 TON balance to be deleted) or by sending a message with [mode 160](v3/documentation/smart-contracts/message-management/sending-messages#message-modes). +Yes, either as a result of storage fee accumulation (contract needs to reach -1 TON balance to be deleted) or by sending a message with [mode 160](/v3/documentation/smart-contracts/message-management/sending-messages#message-modes). ### Are smart contract addresses case sensitive? diff --git a/docs/v3/documentation/infra/nodes/mytonctrl/mytonctrl-overview.mdx b/docs/v3/documentation/infra/nodes/mytonctrl/mytonctrl-overview.mdx index 9427e286a5..2daf307c8b 100644 --- a/docs/v3/documentation/infra/nodes/mytonctrl/mytonctrl-overview.mdx +++ b/docs/v3/documentation/infra/nodes/mytonctrl/mytonctrl-overview.mdx @@ -184,7 +184,7 @@ MyTonCtrl> add_custom_overlay Example: ```bash -add_custom_overlay custom /config.json # check link from above to know what config this command requires (v3/guidelines/nodes/custom-overlays) +add_custom_overlay custom /config.json # check link from above to know what config this command requires (/v3/guidelines/nodes/custom-overlays) ``` ### list_custom_overlays @@ -244,7 +244,7 @@ Based on the `validator index` (can be received by `status` command), there are - **The user is not a validator**: No penalties apply, but the user is not eligible for rewards either. No `validator efficiency` to check. This can be caused by a low stake or incorrect node configuration. Additionally, ensure that `mytonctrl` is running continuously. -Read more about `max_validators` and `max_main_validators` [on config parameters page](v3/documentation/network/configs/blockchain-configs#configuration-parameters-for-the-number-of-validators-for-elections). Get the actual values [for mainnet](https://tonviewer.com/config#16) and [for testnet](https://testnet.tonviewer.com/config#16). +Read more about `max_validators` and `max_main_validators` [on config parameters page](/v3/documentation/network/configs/blockchain-configs#configuration-parameters-for-the-number-of-validators-for-elections). Get the actual values [for mainnet](https://tonviewer.com/config#16) and [for testnet](https://testnet.tonviewer.com/config#16). ## Pool commands diff --git a/docs/v3/documentation/infra/nodes/validation/collators.md b/docs/v3/documentation/infra/nodes/validation/collators.md index 54ccbc00ea..69cb0afa05 100644 --- a/docs/v3/documentation/infra/nodes/validation/collators.md +++ b/docs/v3/documentation/infra/nodes/validation/collators.md @@ -22,7 +22,7 @@ Currently, TON testnet is used for testing this *Validator*/*Collator* separatio # Join with "lite validator" -New node software is available in [block-generation](https://github.com/SpyCheese/ton/tree/block-generation) branch. +New node software is available in [accelerator](https://github.com/ton-blockchain/ton/tree/accelerator) branch. ## Collator To create new collator you need to setup TON node; you can use flag `-M` to force node not to keep eye on shardchains it doesn't process. @@ -104,7 +104,7 @@ By default validators proposing new block in validator set do not attach data th Upgrade to new protocol when validators will share blocks with collated data attached can be done by - Upgrading all validators to new node version -- Setting [full_collated_data](https://github.com/spycheese/ton/blob/block-generation/crypto/block/block.tlb#L737) to true +- Setting [full_collated_data](https://github.com/ton-blockchain/ton/tree/accelerator/crypto/block/block.tlb#L858) to true # Next steps diff --git a/docs/v3/documentation/infra/nodes/validation/staking-incentives.md b/docs/v3/documentation/infra/nodes/validation/staking-incentives.md index 01c440597f..90a98f5f4d 100644 --- a/docs/v3/documentation/infra/nodes/validation/staking-incentives.md +++ b/docs/v3/documentation/infra/nodes/validation/staking-incentives.md @@ -63,7 +63,7 @@ Similarly to all blockchain networks, each transaction on TON requires a computa The network also subsidizes block creation by adding a subsidy to the reward pool equal to 1.7 TON for each masterchain block and 1 TON for each basechain block (Network Parameters `Config14:masterchain_block_fee` and `Config14:basechain_block_fee`). Note, that when splitting a basechain into more than one shardchain, the subsidy per shardchain block is split accordingly. This process allows the subsidy per unit of time to be kept near constant. :::info -TON Blockchain is planning to introduce a deflationary mechanism in Q2 of 2023. In particular, a portion of TON generated via network use will be burned instead of going to the rewards pool. +In June 2023, the [Deflationary Burn Mechanism](https://blog.ton.org/ton-holders-and-validators-vote-in-favor-of-implementing-the-toncoin-real-time-burn-mechanism) was introduced. With this mechanism, a portion of the TON generated by the network is burned instead of being allocated to the rewards pool. ::: After a validation cycle round lasting 65536 seconds or ~18 hours (Network Parameter `Config15:validators_elected_for`), staked TON is not immediately released by each validator, but instead held for an additional 32768 seconds or ~9 hours (Network Parameter `Config15:stake_held_for`). During this period, slashing (a penalization mechanism for misbehaving validators) penalties can be deducted from the validator. After funds are released, validators can withdraw their stake along with a share of the reward pool accrued during the validation round proportional to their voting _weight_. @@ -147,4 +147,4 @@ If you don't want to do this please consider using staking services https://ton. * [Running a Validator](/v3/guidelines/nodes/running-nodes/validator-node) * [Transaction Fees](/v3/documentation/smart-contracts/transaction-fees/fees) -* [What is blockchain? What is a smart contract? What is gas?](https://blog.ton.org/what-is-blockchain) \ No newline at end of file +* [What is blockchain? What is a smart contract? What is gas?](https://blog.ton.org/what-is-blockchain) diff --git a/docs/v3/documentation/network/configs/config-params.md b/docs/v3/documentation/network/configs/config-params.md index 93eb82b8b7..57b7517f3a 100644 --- a/docs/v3/documentation/network/configs/config-params.md +++ b/docs/v3/documentation/network/configs/config-params.md @@ -2,7 +2,7 @@ The aim of this document is to provide a basic explanation of configuration parameters of TON Blockchain, and to give step-by-step instructions for changing these parameters by a consensus of a majority of validators. -We assume that the reader is already familiar with [Fift](/v3/documentation/smart-contracts/fift/overview) and the [Lite Client](/v3/guidelines/nodes/running-nodes/liteserver-node), as explained in [FullNode-HOWTO (low-level)](/docs/v3/guidelines/nodes/running-nodes/full-node), and [Validator-HOWTO (low-level)](/v3/guidelines/nodes/running-nodes/validator-node) in the sections where validators' voting for the configuration proposals is described. +We assume that the reader is already familiar with [Fift](/v3/documentation/smart-contracts/fift/overview) and the [Lite Client](/v3/guidelines/nodes/running-nodes/liteserver-node), as explained in [FullNode-HOWTO (low-level)](/v3/guidelines/nodes/running-nodes/full-node), and [Validator-HOWTO (low-level)](/v3/guidelines/nodes/running-nodes/validator-node) in the sections where validators' voting for the configuration proposals is described. ## 1. Configuration parameters The **configuration parameters** are certain values that affect the behavior of validators and/or fundamental smart contracts of TON Blockchain. The current values of all configuration parameters are stored as a special part of the masterchain state and are extracted from the current masterchain state when needed. Therefore, it makes sense to speak of the values of the configuration parameters with respect to a certain masterchain block. Each shardchain block contains a reference to the latest known masterchain block; the values from the corresponding masterchain state are assumed to be active for this shardchain block and are used during its generation and validation. For masterchain blocks, the state of the previous masterchain block is used to extract the active configuration parameters. Therefore, even if one tries to change some configuration parameters inside a masterchain block, the changes will become active only for the next masterchain block. diff --git a/docs/v3/documentation/network/configs/network-configs.md b/docs/v3/documentation/network/configs/network-configs.md index 8be0ed1065..d98bd9b049 100644 --- a/docs/v3/documentation/network/configs/network-configs.md +++ b/docs/v3/documentation/network/configs/network-configs.md @@ -7,5 +7,5 @@ On this page you can find active network configs of TON Blockchain: ## See Also -- [Node Types](v3/documentation/infra/nodes/node-types) +- [Node Types](/v3/documentation/infra/nodes/node-types) - [Blockchain Params Config](/v3/documentation/network/configs/blockchain-configs) diff --git a/docs/v3/documentation/smart-contracts/contracts-specs/nominator-pool.mdx b/docs/v3/documentation/smart-contracts/contracts-specs/nominator-pool.mdx index f945a534f4..b372b36a80 100644 --- a/docs/v3/documentation/smart-contracts/contracts-specs/nominator-pool.mdx +++ b/docs/v3/documentation/smart-contracts/contracts-specs/nominator-pool.mdx @@ -2,6 +2,10 @@ A smart contract, called a Nominator Pool, provides the ability for one or more nominators to lend Toncoin in a validator stake, and ensures that the validator can use that Toncoin only for validation. Also, the smart contract guarantees the distribution of the reward. +## Architecture + +![image](/img/nominator-pool/nominator-pool.png) + ## Limits This pool is designed for large amounts of coins. @@ -16,10 +20,14 @@ The number of nominators above 40 has not been tested and we strongly advise aga ## Fees -Since the pool is located in the masterchain where the fees are high, it will take about 5 TON per validation round to operate the pool. +Since the pool is located in the masterchain where the fees are high, it will take about **5 TON** per validation round to operate the pool. Operational fees are paid by the validator. +:::info +Note that there should always be **10 TON** on the pool balance - this is the minimum balance for the network storage fee. 10 TON can not be withdrawn. +::: + ## Reward distribution For each round of validation, the pool sends a stake to the elector smart contract. @@ -39,6 +47,8 @@ Nominators share the remaining reward according to the size of their stakes. For example, if there are two nominators in the pool with stakes of 100k and 300k TON, then the first one will take 25% and the second 75% of the `nominators_reward`. +### Nominator Pool Slashing + In case of a large validation fine, when the amount received is less than the amount sent, the loss is debited from the validator's funds. If the validator's funds are not enough, then the remaining loss will be deducted from the nominators in proportion to their stakes. @@ -95,8 +105,6 @@ The nominator can only withdraw all of his funds at once. Partial withdrawal not The validator can withdraw from the pool all the Toncoins that does not belong to the nominators. -Note that there should always be 10 TON on the pool balance - this is the minimum balance for the network storage fee. 10 TON can not be withdrawn. - ## Participants must keep their private keys If the nominator loses access to his wallet from which he made the deposit, he will not be able to withdraw his funds from the pool. diff --git a/docs/v3/documentation/smart-contracts/contracts-specs/wallet-contracts.md b/docs/v3/documentation/smart-contracts/contracts-specs/wallet-contracts.md index f105024822..4c8d90e840 100644 --- a/docs/v3/documentation/smart-contracts/contracts-specs/wallet-contracts.md +++ b/docs/v3/documentation/smart-contracts/contracts-specs/wallet-contracts.md @@ -134,7 +134,7 @@ Also op-code, op::code and operational code |-----------------|-----------------|----------------------------| | Global | 0x00000000 | Text Comment | | Global | 0xffffffff | Bounce | -| Global | 0x2167da4b | [Encrypted Comment](v3/documentation/smart-contracts/message-management/internal-messages#messages-with-encrypted-comments) | +| Global | 0x2167da4b | [Encrypted Comment](/v3/documentation/smart-contracts/message-management/internal-messages#messages-with-encrypted-comments) | | Global | 0xd53276db | Excesses | | Elector | 0x4e73744b | New Stake | | Elector | 0xf374484c | New Stake Confirmation | diff --git a/docs/v3/documentation/smart-contracts/func/cookbook.md b/docs/v3/documentation/smart-contracts/func/cookbook.md index 5680d5c6b2..3fc52407d8 100644 --- a/docs/v3/documentation/smart-contracts/func/cookbook.md +++ b/docs/v3/documentation/smart-contracts/func/cookbook.md @@ -735,7 +735,7 @@ if (current_time > 1672080143) { :::caution draft Please note that this method of generating random numbers isn't safe. -Checkout [Random Number Generation](v3/guidelines/smart-contracts/securier-generation) for more information. +Checkout [Random Number Generation](/v3/guidelines/smart-contracts/security/random-number-generation) for more information. :::,. ```func diff --git a/docs/v3/documentation/smart-contracts/func/docs/dictionaries.md b/docs/v3/documentation/smart-contracts/func/docs/dictionaries.md index 548912ba20..8329da1133 100644 --- a/docs/v3/documentation/smart-contracts/func/docs/dictionaries.md +++ b/docs/v3/documentation/smart-contracts/func/docs/dictionaries.md @@ -24,7 +24,7 @@ Possible operations for hashmaps: - load from slice, store to builder - get/set/delete value by key - replace value (set new value if key was already present) / add one (if key was not present) -- move to next/previous key-value pair, in order of keys (this can be used to [iterate over dictionaries](v3/documentation/smart-contracts/func/cookbook#how-to-iterate-dictionaries) if gas limit is not a concern) +- move to next/previous key-value pair, in order of keys (this can be used to [iterate over dictionaries](/v3/documentation/smart-contracts/func/cookbook#how-to-iterate-dictionaries) if gas limit is not a concern) - retrieve minimal/maximal key with its value - get function (continuation) by key and immediately execute it diff --git a/docs/v3/documentation/smart-contracts/func/docs/literals_identifiers.md b/docs/v3/documentation/smart-contracts/func/docs/literals_identifiers.md index de62b6c8e1..7e9106618a 100644 --- a/docs/v3/documentation/smart-contracts/func/docs/literals_identifiers.md +++ b/docs/v3/documentation/smart-contracts/func/docs/literals_identifiers.md @@ -54,11 +54,11 @@ These are invalid identifiers: - `_` Some more uncommon examples of valid identifiers: -- `123valid` +- `123validname` - `2+2=2*2` -- `-valid` -- `0xdead` -- `{valid}` +- `-alsovalidname` +- `0xefefefhahaha` +- `{hehehe}` - ``pa{--}in"`aaa`"`` These are also invalid identifiers: diff --git a/docs/v3/documentation/smart-contracts/func/overview.mdx b/docs/v3/documentation/smart-contracts/func/overview.mdx index 04496a8d14..c5299be051 100644 --- a/docs/v3/documentation/smart-contracts/func/overview.mdx +++ b/docs/v3/documentation/smart-contracts/func/overview.mdx @@ -2,10 +2,10 @@ import Button from '@site/src/components/button' # Overview -A high-level language FunC is used to program smart contracts on TON. +__FunC__, a high-level language, is used to program smart contracts on TON. FunC is a domain-specific, C-like, statically typed language. -Here is a simple example method for sending money written in FunC: +Here is a simple example of a method for sending money written in FunC: ```func () send_money(slice address, int amount) impure inline { @@ -19,9 +19,9 @@ Here is a simple example method for sending money written in FunC: } ``` -FunC programs are compiled into Fift assembler code, which generates corresponding bytecode for the [TON Virtual Machine](/v3/documentation/tvm/tvm-overview). +FunC programs are compiled into Fift assembler code, which generates the corresponding bytecode for the [TON Virtual Machine](/v3/documentation/tvm/tvm-overview). -Further this bytecode (actually a [tree of cells](/v3/concepts/dive-into-ton/ton-blockchain/cells-as-data-storage), like any other data in TON Blockchain) can be used for creating smart contracts in the blockchain or can be run on a local instance of TVM. +his bytecode (essentially a [tree of cells](/v3/concepts/dive-into-ton/ton-blockchain/cells-as-data-storage), like any other data in the TON Blockchain) can then be used to create smart contracts on the blockchain or can be run on a local instance of the TVM. + +
+ + +## Motivation behind Tolk + +FunC is awesome. +It is really low-level and encourages a programmer to think about compiler internals. +It gives full control over TVM assembler, allowing a programmer to make his contract as effective as possible. +If you get used to it, you love it. + +But there is a problem. +FunC is "functional C", and it's for ninja. +If you are keen on Lisp and Haskell, you'll be happy. +But if you are a JavaScript / Go / Kotlin developer, its syntax is peculiar for you, leading to occasional mistakes. +A struggle with syntax may decrease your motivation for digging into TON. + +Imagine, what if there was a language, also smart, also low-level, but not functional and not like C? +Leaving all beauty and complexity inside, what if it would be more similar to popular languages at first glance? + +That's what Tolk is about. + + +## Migrating from FunC to Tolk + +If you know FunC and want to try a new syntax, your way is: +1. Read [Tolk vs FunC: in short](/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-short). +2. With blueprint, create a new Tolk contract (for example, a counter) and experiment around. Remember, that almost all stdlib functions are renamed to ~~verbose~~ clear names. Here is [a mapping](/v3/documentation/smart-contracts/tolk/tolk-vs-func/stdlib). +3. Try a [converter](https://github.com/ton-blockchain/convert-func-to-tolk) for your existing contracts or one from [FunC Contracts](/v3/documentation/smart-contracts/contracts-specs/examples). Keep in mind that contracts written in Tolk from scratch would definitely look nicer than being auto-converted. For instance, using logical operators instead of bitwise tremendously increases code readability. + +## How to try Tolk if you don't know FunC + +:::tip Currently, this documentation assumes that you know FunC +The documentation describes "Tolk vs FunC" differences. +Later it will be adapted to land newcomers. Moreover, FunC will eventually become deprecated, +and all code snippets throughout the whole documentation will be rewritten to Tolk. +::: + +If you are new to TON, your way is: +1. Dig into [this documentation](/v3/documentation/smart-contracts/overview) to acquire basic on development in TON. No matter what language you'll use, you need to be aware of cells, slices, TON asynchronous nature after all. +2. Facing FunC snippets, you can still use FunC, or try to express the same in Tolk. If FunC syntax is peculiar for you, don't worry: the goal of Tolk is exactly to fix this issue. +3. Once you gain some understanding of what's going on, try using Tolk with [blueprint](https://github.com/ton-org/blueprint). + + +## Tooling around Tolk Language + +Sources of the Tolk compiler are a part of the `ton-blockchain` [repo](https://github.com/ton-blockchain/ton). +Besides the compiler, we have: + +1. [tolk-js](https://github.com/ton-blockchain/tolk-js) — a WASM wrapper for Tolk compiler. +2. [JetBrains IDE plugin](https://github.com/ton-blockchain/intellij-ton) supports Tolk besides FunC, Fift, TL/B, and Tact. +3. [VS Code Extension](https://github.com/ton-blockchain/tolk-vscode) enabling Tolk Language support. +4. [Converter from FunC to Tolk](https://github.com/ton-blockchain/convert-func-to-tolk) — convert a `.fc` file to a `.tolk` file with a single `npx` command. +5. Tolk Language is available in [blueprint](https://github.com/ton-org/blueprint). + + +## Is Tolk production-ready? + +The Tolk compiler, a fork of the FunC compiler, is deemed production-ready, albeit somewhat experimental at the moment. + +Undiscovered bugs may exist, potentially inherited from FunC or attributable to TVM characteristics. +Anyway, no matter what language you use, you should cover your contracts with tests to reach high reliability. + + +## Roadmap + +The first released version of Tolk is v0.6, emphasizing [missing](/v3/documentation/smart-contracts/tolk/changelog#how-tolk-was-born) FunC v0.5. + +Here are some (yet not all and not ordered in any way) points to be investigated: +- type system improvements: boolean type, nullability, dictionaries +- structures, with auto-packing to/from cells, probably integrated with message handlers +- structures with methods, probably generalized to cover built-in types +- some integrations with TL scheme, either syntactical or via code generation +- human-readable compiler errors +- easier messages sending +- better experience for common use-cases (jettons, nft, etc.) +- gas and stack optimizations, AST inlining +- extending and maintaining stdlib +- think about some kind of ABI (how explorers "see" bytecode) +- think about gas and fee management in general + +Note, that most of the points above are a challenge to implement. +At first, FunC kernel must be fully refactored to "interbreed" with abilities it was not designed for. + +Also, I see Tolk evolution partially guided by community needs. +It would be nice to talk to developers who have created interconnected FunC contracts, +to absorb their pain points and discuss how things could be done differently. + + +## Issues and Contacts + +If you face issue, connect to developer society on [TON Dev Chats](https://t.me/addlist/1r5Vcb8eljk5Yzcy) or create GitHub issues. diff --git a/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-detail.mdx b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-detail.mdx new file mode 100644 index 0000000000..111958bf4d --- /dev/null +++ b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-detail.mdx @@ -0,0 +1,849 @@ +# Tolk vs FunC: in detail + +A very huge list below. Will anyone have enough patience to read it up to the end?.. + +:::tip There is a compact version +Here: [Tolk vs FunC: in short](/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-short) +::: + + +

+ ✅ Traditional comments :) +

+ + + + + + + + + + + + + + + + + + +
FunCTolk
{';; comment'}{'// comment'}
{'{- multiline comment -}'}{'/* multiline comment */'}
+ + +

+ ✅ `2+2` is 4, not an identifier. Identifiers can only be alpha-numeric +

+ +In FunC, almost any character can be a part of identifier. +For example, `2+2` (without a space) is an identifier. +You can even declare a variable with such a name. + +In Tolk, spaces are not mandatory. `2+2` is 4, as expected. `3+~x` is `3 + (~ x)`, and so on. + + + + + + + + + + + + + + +
FunCTolk
{'return 2+2; ;; undefined function `2+2`'}{'return 2+2; // 4'}
+ +More precisely, an identifier can start from {'[a-zA-Z$_]'} +and be continued with {'[a-zA-Z0-9$_]'}. Note, that `?`, `:`, and others are not valid symbols, `found?` and `op::increase` are not valid identifiers. + +You can use backticks to surround an identifier, and then it can contain any symbols (similar to Kotlin and some other langs). Its potential usage is to allow keywords be used as identifiers, in case of code generation by a scheme, for example. + + + + + + + + + + + + + + + + + + +
FunCTolk
{'const op::increase = 0x1234;'}{'const OP_INCREASE = 0x1234;'}
int 2+2 = 5;'}}>var \`2+2\` = 5;'}}>
+ + +

+ ✅ Impure by default, compiler won't drop user function calls +

+ +FunC has an `impure` function specifier. When absent, a function is treated as pure. If its result is unused, its call was deleted by the compiler. + +Though this behavior is documented, it is very unexpected to newcomers. +For instance, various functions that don't return anything (throw an exception on mismatch, for example), +are silently deleted. This situation is spoilt by the fact that FunC doesn't check and validate function body, +allowing impure operations inside pure functions. + +In Tolk, all functions are impure by default. You can mark a function pure with annotation, +and then impure operations are forbidden in its body (exceptions, globals modification, calling non-pure functions, etc.). + + +

+ ✅ New functions syntax: `fun` keyword, `@` attributes, types on the right (like in TypeScript, Kotlin, Python, etc.) +

+ + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'cell parse_data(slice cs) { }'}{'fun parse_data(cs: slice): cell { }'}
{'(cell, int) load_storage() { }'}{'fun load_storage(): (cell, int) { }'}
{'() main() { ... }'}{'fun main() { ... }'}
+ +Types of variables — also to the right: + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'slice cs = ...;'}{'var cs: slice = ...;'}
{'(cell c, int n) = parse_data(cs);'}{'var (c: cell, n: int) = parse_data(cs);'}
{'global int stake_at;'}{'global stake_at: int;'}
+ +Modifiers `inline` and others — with annotations: + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
int f(cell s) inline {'}}>fun f(s: cell): int {'}}>
() load_data() impure inline_ref {'}}>fun load_data() {'}}>
{'global int stake_at;'}{'global stake_at: int;'}
+ +`forall` — this way: + + + + + + + + + + + + + + +
FunCTolk
{'forall X -> tuple cons(X head, tuple tail)'}
+ +`asm` implementation — like in FunC, but being properly aligned, it looks nicer: +```tolk +@pure +fun third(t: tuple): X + asm "THIRD"; + +@pure +fun iDictDeleteGet(dict: cell, keyLen: int, index: int): (cell, slice, int) + asm(index dict keyLen) "DICTIDELGET NULLSWAPIFNOT"; + +@pure +fun mulDivFloor(x: int, y: int, z: int): int + builtin; +``` + +There is also a `@deprecated` attribute, not affecting compilation, but for a human and IDE. + + +

+ ✅ `get` instead of `method_id` +

+ +In FunC, `method_id` (without arguments) actually declared a get method. In Tolk, you use a straightforward syntax: + + + + + + + + + + + + + + +
FunCTolk
{'int seqno() method_id { ... }'}{'get seqno(): int { ... }'}
+ +Both `get methodName()` and `get fun methodName()` are acceptable. + +For `method_id(xxx)` (uncommon in practice, but valid), there is an attribute: + + + + + + + + + + + + + + +
FunCTolk
() after_code_upgrade(cont old_code) impure method_id(1666)'}}>fun afterCodeUpgrade(oldCode: continuation)'}}>
+ + +

+ ✅ It's essential to declare types of parameters (though optional for locals) +

+ +```tolk +// not allowed +fun do_smth(c, n) +// types are mandatory +fun do_smth(c: cell, n: int) +``` + +There is an `auto` type, so `fun f(a: auto)` is valid, though not recommended. + +If parameter types are mandatory, return type is not (it's often obvious of verbose). If omitted, it means `auto`: +```tolk +fun x() { ... } // auto infer return +``` + +For local variables, types are also optional: +```tolk +var i = 10; // ok, int +var b = beginCell(); // ok, builder +var (i, b) = (10, beginCell()); // ok, two variables, int and builder + +// types can be specified manually, of course: +var b: builder = beginCell(); +var (i: int, b: builder) = (10, beginCell()); +``` + + +

+ ✅ Variables are not allowed to be redeclared in the same scope +

+ +```tolk +var a = 10; +... +var a = 20; // error, correct is just `a = 20` +if (1) { + var a = 30; // it's okay, it's another scope +} +``` + +As a consequence, partial reassignment is not allowed: +```tolk +var a = 10; +... +var (a, b) = (20, 30); // error, releclaration of a +``` + +Note, that it's not a problem for `loadUint()` and other methods. In FunC, they returned a modified object, so a pattern `var (cs, int value) = cs.load_int(32)` was quite common. In Tolk, such methods mutate an object: `var value = cs.loadInt(32)`, so redeclaration is unlikely to be needed. + +```tolk +fun send(msg: cell) { + var msg = ...; // error, redeclaration of msg + + // solution 1: intruduce a new variable + var msgWrapped = ...; + // solution 2: use `redef`, though not recommended + var msg redef = ...; +``` + + +

+ ✅ Changes in the type system +

+ +Type system in the first Tolk release is the same as in FunC, with the following modifications: +- `void` is effectively an empty tensor (more canonical to be named `unit`, but `void` is more reliable); btw, `return` (without expression) is actually `return ()`, a convenient way to return from void functions +```tolk +fun setContractData(c: cell): void + asm "c4 POP"; +``` +- `auto` mean "auto infer"; in FunC, `_` was used for that purpose; note, that if a function doesn't specify return type, it's `auto`, not `void` +- `self`, to make chainable methods, described below; actually it's not a type, it can only occur instead of return type of a function +- `cont` renamed to `continuation` + + +

+ ✅ Another naming for recv_internal / recv_external +

+ +```tolk +fun onInternalMessage +fun onExternalMessage +fun onTickTock +fun onSplitPrepare +fun onSplitInstall +``` + +All parameter types and their order rename the same, only naming is changed. `fun main` is also available. + + +

+ ✅ #include → import. Strict imports +

+ + + + + + + + + + + + + + +
FunCTolk
{'#include "another.fc";'}{'import "another.tolk"'}
+ +In Tolk, you can not used a symbol from `a.tolk` without importing this file. In other words, "import what you use". + +All stdlib functions are available out of the box, downloading stdlib and `#include "stdlib.fc"` is not needed. See below about embedded stdlib. + +There is still a global scope of naming. If `f` is declared in two different files, it's an error. We "import" a whole file, no per-file visibility and `export` keyword is now supported, but probably will be in the future. + + +

+ ✅ #pragma → compiler options +

+ +In FunC, "experimental" features like `allow-post-modifications` were turned on by a pragma in .fc files (leading to problems when some files contain it, some don't). Indeed, it's not a pragma for a file, it's a compilation option. + +In Tolk, all pragmas were removed. `allow-post-modification` and `compute-asm-ltr` were merged into Tolk sources (as if they were always on in FunC). Instead of pragmas, there is now an ability to pass experimental options. + +As for now, there is one experimental option introduced — `remove-unused-functions`, which doesn't include unused symbols to Fift output. + +`#pragma version xxx` was replaced by `tolk xxx` (no >=, just a strict version). It's good practice to annotate compiler version you are using. If it doesn't match, Tolk will show a warning. +```tolk +tolk 0.6 +``` + + +

+ ✅ Late symbols resolving. AST representation +

+ +In FunC (like in С) you can not access a function declared below: +```func +int b() { a(); } ;; error +int a() { ... } ;; since it's declared below +``` + +To avoid an error, a programmer should create a forward declaration at first. The reason is that symbols resolving is performed right at the time of parsing. + +Tolk compiler separates these two steps. At first it does parsing, and then it does symbol resolving. Hence, a snippet above would not be erroneous. + +Sounds simple, but internally, it's a very huge job. To make this available, I've introduced an intermediate AST representation, completely missed in FunC. That's an essential point of future modifications and performing semantic code analisys. + + +

+ ✅ `null` keyword +

+ +Creating null values and checking variables on null looks very pretty now. + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'a = null()'}{'a = null'}
{'if (null?(a))'}{'if (a == null)'}
{'if (~ null?(b))'}{'if (b != null)'}
{'if (~ cell_null?(c))'}{'if (c != null)'}
+ +Note, that it does NOT mean that Tolk language has nullability. No, you can still assign `null` to an integer variable — like in FunC, just syntactically pleasant. A true nullability will be available someday, after hard work on the type system. + + +

+ ✅ `throw` and `assert` keywords +

+ +Tolk greatly simplifies working with exceptions. + +If FunC has `throw()`, `throw_if()`, `throw_arg_if()`, and the same for unless, Tolk has only two primitives: `throw` and `assert`. + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'throw(excNo)'}{'throw excNo'}
{'throw_arg(arg, excNo)'}{'throw (excNo, arg)'}
{'throw_unless(excNo, condition)'}{'assert(condition, excNo)'}
{'throw_if(excNo, condition)'}{'assert(!condition, excNo)'}
+ +Note, that `!condition` is possible since logical NOT is available, see below. + +There is a long (verbose) syntax of `assert(condition, excNo)`: +```tolk +assert(condition) throw excNo; +// with possibility to include arg to throw +``` + +Also, Tolk swaps `catch` arguments: it's `catch (excNo, arg)`, both optional (since arg is most likely empty). + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'try { } catch (_, _) { }'}{'try { } catch { }'}
{'try { } catch (_, excNo) { }'}{'try { } catch(excNo) { }'}
{'try { } catch (arg, excNo) { }'}{'try { } catch(excNo, arg) { }'}
+ + +

+ ✅ `do ... until` → `do ... while` +

+ + + + + + + + + + + + + + + + + + +
FunCTolk
{'do { ... } until (~ condition);'}{'do { ... } while (condition);'}
{'do { ... } until (condition);'}{'do { ... } while (!condition);'}
+ +Note, that `!condition` is possible since logical NOT is available, see below. + + +

+ ✅ Operator precedence became identical to C++ / JavaScript +

+ +In FunC, such code `if (slices_equal() & status == 1)` is parsed as `if( (slices_equal()&status) == 1 )`. This is a reason of various errors in real-world contracts. + +In Tolk, `&` has lower priority, identical to C++ and JavaScript. + +Moreover, Tolk fires errors on potentially wrong operators usage to completely eliminate such errors: +```tolk +if (flags & 0xFF != 0) +``` + +will lead to a compilation error (similar to gcc/clang): +``` +& has lower precedence than ==, probably this code won't work as you expected. Use parenthesis: either (... & ...) to evaluate it first, or (... == ...) to suppress this error. +``` + +Hence, the code should be rewritten: +```tolk +// either to evaluate it first (our case) +if ((flags & 0xFF) != 0) +// or to emphasize the behavior (not our case here) +if (flags & (0xFF != 0)) +``` + +I've also added a diagnostic for a common mistake in bitshift operators: `a << 8 + 1` is equivalent to `a << 9`, probably unexpected. + +``` +int result = a << 8 + low_mask; + +error: << has lower precedence than +, probably this code won't work as you expected. Use parenthesis: either (... << ...) to evaluate it first, or (... + ...) to suppress this error. +``` + +Operators `~% ^% /% ~/= ^/= ~%= ^%= ~>>= ^>>=` no longer exist. + + +

+ ✅ Immutable variables, declared via `val` +

+ +Like in Kotlin: `var` for mutable, `val` for immutable, optionally followed by a type. FunC has no analogue of `val`. +```tolk +val flags = msgBody.loadMessageFlags(); +flags &= 1; // error, modifying an immutable variable + +val cs: slice = c.beginParse(); +cs.loadInt(32); // error, since loadInt() mutates an object +cs.preloadInt(32); // ok, it's a read-only method +``` + +Parameters of a function are mutable, but since they are copied by value, called arguments aren't changed. Exactly like in FunC, just to clarify. +```tolk +fun some(x: int) { + x += 1; +} + +val origX = 0; +some(origX); // origX remains 0 + +fun processOpIncrease(msgBody: slice) { + val flags = msgBody.loadInt(32); + ... +} + +processOpIncrease(msgBody); // by value, not modified +``` + +In Tolk, a function can declare `mutate` parameters. It's a generalization of FunC `~` tilda functions, read below. + + +

+ ✅ Deprecated command-line options removed +

+ +Command-line flags `-A`, `-P`, and others, were removed. Default behavior +``` +/path/to/tolk {inputFile} +``` +is more than enough. Use `-v` to print version and exit. Use `-h` for all available command-line flags. + +Only one input file can be passed, others should be `import`'ed. + + +

+ ✅ stdlib functions renamed to ~~verbose~~ clear names, camelCase style +

+ +All naming in standard library was reconsidered. Now, functions are named using longer, but clear names. + + + + + + + + + + + + + + +
FunCTolk
car(l)
get_balance().pair_first()
raw_reserve(count)
dict~idict_add?(...)
dict~udict::delete_get_max()
t~tpush(triple(x, y, z))
s.slice_bits()
~dump(x)
...'}}>
listGetHead(l)
getMyOriginalBalance()
reserveToncoinsOnBalance(count)
dict.iDictSetIfNotExists(...)
dict.uDictDeleteLastAndGet()
t.tuplePush([x, y, z])
s.getRemainingBitsCount()
debugPrint(x)
...'}}>
+ +A former "stdlib.fc" was split into multiple files: common.tolk, tvm-dicts.tolk, and others. + +Continue here: [Tolk vs FunC: standard library](/v3/documentation/smart-contracts/tolk/tolk-vs-func/stdlib). + + +

+ ✅ stdlib is now embedded, not downloaded from GitHub +

+ + + + + + + + + + + + + + +
FunCTolk
+
    +
  1. Download stdlib.fc from GitHub
  2. +
  3. Save into your project
  4. +
  5. `#include "stdlib.fc";`
  6. +
  7. Use standard functions
  8. +
+
+
    +
  1. Use standard functions
  2. +
+
+ +In Tolk, stdlib a part of distribution. Standard library is inseparable, since keeping a triple "language, compiler, stdlib" together is the only correct way to maintain release cycle. + +It works in such a way. Tolk compiler knows how to locate a standard library. If a user has installed an apt package, stdlib sources were also downloaded and exist on a hard disk, so the compiler locates them by system paths. If a user uses a WASM wrapper, they are provided by tolk-js. And so on. + +Standard library is split into multiple files: `common.tolk` (most common functions), `gas-payments.tolk` (calculating gas fees), `tvm-dicts.tolk`, and others. Functions from `common.tolk` are available always (a compiler implicitly imports it). Other files are needed to be explicitly imported: +```tolk +import "@stdlib/tvm-dicts" // ".tolk" optional + +... +var dict = createEmptyDict(); +dict.iDictSet(...); +``` + +Mind the rule "import what you use", it's applied to `@stdlib/...` files also (with the only exception of "common.tolk"). + +JetBrains IDE plugin automatically discovers stdlib folder and inserts necessary imports as you type. + + +

+ ✅ Logical operators `&& ||`, logical not `!` +

+ +In FunC, there are only bitwise operators `~ & | ^`. Developers making first steps, thinking "okay, no logical, I'll use bitwise in the same manner", often do errors, since operator behavior is completely different: + + + + + + + + + + + + + + + + + + + + + + + + +
`a & b``a && b`
sometimes, identical:
{'0 & X = 0'}{'0 & X = 0'}
{'-1 & X = -1'}{'-1 & X = -1'}
but generally, not:
{'1 & 2 = 0'}{'1 && 2 = -1 (true)'}
+ + + + + + + + + + + + + + + + + + + + + + + + +
`~ found``!found`
sometimes, identical:
{'true (-1) → false (0)'}{'-1 → 0'}
{'false (0) → true (-1)'}{'0 → -1'}
but generally, not:
{'1 → -2'}{'1 → 0 (false)'}
+ + + + + + + + + + + + + + +
condition & f()condition && f()
f() is called alwaysf() is called only if condition
+ + + + + + + + + + + + + + +
condition | f()condition || f()
f() is called alwaysf() is called only if condition is false
+ +Tolk supports logical operators. They behave exactly as you get used to (right column). For now, `&&` and `||` sometimes produce not optimal Fift code, but in the future, Tolk compiler will become smarter in this case. It's negligible, just use them like in other languages. + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'if (~ found?)'}{'if (!found)'}
    if (cs~load_int(32) == 0) {
        ...
    }
}'}}>
    ...
}'}}>
{'ifnot (cell_null?(signatures))'}{'if (signatures != null)'}
{'elseifnot (eq_checksum)'}{'else if (!eqChecksum)'}
+ +Keywords `ifnot` and `elseifnot` were removed, since now we have logical not (for optimization, Tolk compiler generates `IFNOTJMP`, btw). Keyword `elseif` was replaced by traditional `else if`. + +Note, that it does NOT mean that Tolk language has `bool` type. No, comparison operators still return an integer. A `bool` type support will be available someday, after hard work on the type system. + +Remember, that `true` is -1, not 1. Both in FunC and Tolk. It's a TVM representation. + + +

+ ✅ No tilda `~` methods, `mutate` keyword instead +

+ +This change is so huge that it's described on a separate page: [Tolk mutability](/v3/documentation/smart-contracts/tolk/tolk-vs-func/mutability). + + +
+ +

Tolk vs FunC gas consumption

+ +:::caution TLDR +Tolk gas consumption could be a bit higher, because it fixes unexpected arguments shuffling in FunC. It's negligible in practice. +In the future, Tolk compiler will become smart enough to reorder arguments targeting less stack manipulations, +but still avoiding a shuffling problem. +::: + +FunC compiler could unexpectedly shuffle arguments when calling an assembly function: +``` +some_asm_function(f1(), f2()); +``` + +Sometimes, `f2()` could be called before `f1()`, and it's unexpected. +To fix this behavior, one could specify `#pragma compute-asm-ltr`, forcing arguments to be always evaluated in ltr-order. +This was experimental, and therefore turned off by default. + +This pragma reorders arguments on a stack, often leading to more stack manipulations than without it. +In other words, in fixes unexpected behavior, but increases gas consumption. + +Tolk puts arguments onto a stack exactly the same as if this pragma turned on. +So, its gas consumption is sometimes higher than in FunC if you didn't use this pragma. +Of course, there is no shuffling problem in Tolk. + +In the future, Tolk compiler will become smart enough to reorder arguments targeting less stack manipulations, +but still avoiding a shuffling problem. diff --git a/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-short.md b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-short.md new file mode 100644 index 0000000000..36642c4c3e --- /dev/null +++ b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-short.md @@ -0,0 +1,56 @@ +# Tolk vs FunC: in short + +Tolk is much more similar to TypeScript and Kotlin than to C and Lisp. +But it still gives you full control over TVM assembler, since it has a FunC kernel inside. + +1. Functions are declared via `fun`, get methods via `get`, variables via `var` (and `val` for immutable), putting types on the right; parameter types are mandatory; return type can be omitted (auto inferred), as well as for locals; specifiers `inline` and others are `@` attributes +```tolk +global storedV: int; + +fun parseData(cs: slice): cell { + var flags: int = cs.loadMessageFlags(); + ... +} + +@inline +fun sum(a: int, b: int) { // auto inferred int + val both = a + b; // same + return both; +} + +get currentCounter(): int { ... } +``` +2. No `impure`, it's by default, compiler won't drop user function calls +3. Not `recv_internal` and `recv_external`, but `onInternalMessage` and `onExternalMessage` +4. `2+2` is 4, not an identifier; identifiers are alpha-numeric; use naming `const OP_INCREASE` instead of `const op::increase` +5. Logical operators AND `&&`, OR `||`, NOT `!` are supported +6. Syntax improvements: + - `;; comment` → `// comment` + - `{- comment -}` → `/* comment */` + - `#include` → `import`, with a strict rule "import what you use" + - `~ found` → `!found` (for true/false only, obviously) (true is -1, like in FunC) + - `v = null()` → `v = null` + - `null?(v)` → `v == null`, same for `builder_null?` and others + - `~ null?(v)` → `c != null` + - `throw(excNo)` → `throw excNo` + - `catch(_, _)` → `catch` + - `catch(_, excNo)` → `catch(excNo)` + - `throw_unless(excNo, cond)` → `assert(cond, excNo)` + - `throw_if(excNo, cond)` → `assert(!cond, excNo)` + - `return ()` → `return` + - `do ... until (cond)` → `do ... while (!cond)` + - `elseif` → `else if` + - `ifnot (cond)` → `if (!cond)` +7. A function can be called even if declared below; forward declarations not needed; the compiler at first does parsing, and then it does symbol resolving; there is now an AST representation of source code +8. stdlib functions renamed to ~~verbose~~ clear names, camelCase style; it's now embedded, not downloaded from GitHub; it's split into several files; common functions available always, more specific available with `import "@stdlib/tvm-dicts"`, IDE will suggest you; here is [a mapping](/v3/documentation/smart-contracts/tolk/tolk-vs-func/stdlib) +9. No `~` tilda methods; `cs.loadInt(32)` modifies a slice and returns an integer; `b.storeInt(x, 32)` modifies a builder; `b = b.storeInt()` also works, since it not only modifies, but returns; chained methods work identically to JS, they return `self`; everything works exactly as expected, similar to JS; no runtime overhead, exactly same Fift instructions; custom methods are created with ease; tilda `~` does not exist in Tolk at all; [more details here](/v3/documentation/smart-contracts/tolk/tolk-vs-func/mutability) + +#### Tooling around +- JetBrains plugin exists +- VS Code extension [exists](https://github.com/ton-blockchain/tolk-vscode) +- WASM wrapper for blueprint [exists](https://github.com/ton-blockchain/tolk-js) +- And even a converter from FunC to Tolk [exists](https://github.com/ton-blockchain/convert-func-to-tolk) + +#### Where to go next + +[Tolk vs FunC: in detail](/v3/documentation/smart-contracts/tolk/tolk-vs-func/in-detail) diff --git a/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/mutability.mdx b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/mutability.mdx new file mode 100644 index 0000000000..06bfc9aba8 --- /dev/null +++ b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/mutability.mdx @@ -0,0 +1,321 @@ +--- +title: "Tolk vs FunC: mutability" +--- + +# Mutability in Tolk vs tilda functions in FunC + +:::tip TLDR +- no `~` tilda methods +- `cs.loadInt(32)` modifies a slice and returns an integer +- `b.storeInt(x, 32)` modifies a builder +- `b = b.storeInt()` also works, since it not only modifies, but returns +- chained methods work identically to JS, they return `self` +- everything works exactly as expected, similar to JS +- no runtime overhead, exactly same Fift instructions +- custom methods are created with ease +- tilda `~` does not exist in Tolk at all +::: + +This is a drastic change. If FunC has `.methods()` and `~methods()`, Tolk has only dot, one and only way to call a `.method()`. A method may *mutate* an object, or may not. Unlike the list "in short", it's a behavioral and semantic difference from FunC. + +The goal is to have calls identical to JS and other languages: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'int flags = cs~load_uint(32);'}{'var flags = cs.loadUint(32);'}
{'(cs, int flags) = cs.load_uint(32);'}{'var flags = cs.loadUint(32);'}
{'(slice cs2, int flags) = cs.load_uint(32);'}var flags = cs2.loadUint(32);'}}>
             .begin_parse();
int flag = data~load_uint(32);'}}>
           .beginParse()
           .loadUint(32);'}}>
{'dict~udict_set(...);'}{'dict.uDictSet(...);'}
{'b~store_uint(x, 32);'}{'b.storeInt(x, 32);'}
{'b = b.store_int(x, 32);'}
// also works
b = b.storeUint(32);'}}>
     .store_int(y, 32);'}}> .storeInt(y, 32);

// b = ...; also works'}}>
+ +In order to make this available, Tolk offers a mutability conception, which is a generalization of what a tilda means in FunC. + +

+ By default, all arguments are copied by value (identical to FunC) +

+ +```tolk +fun someFn(x: int) { + x += 1; +} + +var origX = 0; +someFn(origX); // origX remains 0 +someFn(10); // ok, just int +origX.someFn(); // still allowed (but not recommended), origX remains 0 +``` + +Same goes for cells, slices, whatever: +```tolk +fun readFlags(cs: slice) { + return cs.loadInt(32); +} + +var flags = readFlags(msgBody); // msgBody is not modified +// msgBody.loadInt(32) will read the same flags +``` + +It means, that when you call a function, you are sure that original data is not modified. + +

+ `mutate` keyword and mutating functions +

+ +But if you add `mutate` keyword to a parameter, a passed argument will be mutated. To avoid unexpected mutations, you must specify `mutate` when calling it, also: +```tolk +fun increment(mutate x: int) { + x += 1; +} + +// it's correct, simple and straightforward +var origX = 0; +increment(mutate origX); // origX becomes 1 + +// these are compiler errors +increment(origX); // error, unexpected mutation +increment(10); // error, not lvalue +origX.increment(); // error, not a method, unexpected mutation +val constX = getSome(); +increment(mutate constX); // error, it's immutable, since `val` +``` + +Same for slices and any other types: +```tolk +fun readFlags(mutate cs: slice) { + return cs.loadInt(32); +} + +val flags = readFlags(mutate msgBody); +// msgBody.loadInt(32) will read the next integer +``` + +It's a generalization. A function may have several mutate parameters: +```tolk +fun incrementXY(mutate x: int, mutate y: int, byValue: int) { + x += byValue; + y += byValue; +} + +incrementXY(mutate origX, mutate origY, 10); // both += 10 +``` + +*You may ask — is it just passing by reference? It effectively is, but since "ref" is an overloaded term in TON (cells and slices have refs), a keyword `mutate` was chosen.* + +

+ `self` parameter turning a function into a method +

+ +When a first parameter is named `self`, it emphasizes that a function (still a global one) is a method and should be called via dot. +```tolk +fun assertNotEq(self: int, throwIfEq: int) { + if (self == throwIfEq) { + throw 100; + } +} + +someN.assertNotEq(10); +10.assertNotEq(10); // also ok, since self is not mutating +assertNotEq(someN, 10); // still allowed (but not recommended) +``` + +`self`, without `mutate`, is **immutable** (unlike all other parameters). Think of it like "read-only method". +```tolk +fun readFlags(self: slice) { + return self.loadInt(32); // error, modifying immutable variable +} + +fun preloadInt32(self: slice) { + return self.preloadInt(32); // ok, it's a read-only method +} +``` + +Combining `mutate` and `self`, we get mutating methods. + +

+ `mutate self` is a method, called via dot, mutating an object +

+ +As follows: +```tolk +fun readFlags(mutate self: slice) { + return self.loadInt(32); +} + +val flags = msgBody.readFlags(); // pretty obvious + +fun increment(mutate self: int) { + self += 1; +} + +var origX = 10; +origX.increment(); // 11 +10.increment(); // error, not lvalue + +// even this is possible +fun incrementWithY(mutate self: int, mutate y: int, byValue: int) { + self += byValue; + y += byValue; +} + +origX.incrementWithY(mutate origY, 10); // both += 10 +``` + +If you take a look into stdlib, you'll notice, that lots of functions are actually `mutate self`, meaning they are methods, modifying an object. Tuples, dictionaries, and so on. In FunC, they were usually called via tilda. +```tolk +@pure +fun tuplePush(mutate self: tuple, value: X): void + asm "TPUSH"; + +t.tuplePush(1); +``` + +

+ `return self` makes a method chainable +

+ +Exactly like `return self` in Python or `return this` in JavaScript. That's what makes methods like `storeInt()` and others chainable. +```tolk +fun storeInt32(mutate self: builder, x: int): self { + self.storeInt(x, 32); + return self; + + // this would also work as expected (the same Fift code) + // return self.storeInt(x, 32); +} + +var b = beginCell().storeInt(1, 32).storeInt32(2).storeInt(3, 32); +b.storeInt32(4); // works without assignment, since mutates b +b = b.storeInt32(5); // and works with assignment, since also returns +``` + +Pay attention to the return type, it's `self`. Currently, you should specify it. Being left empty, compilation will fail. Probably, in the future it would be correct. + +

+ `mutate self` and asm functions +

+ +While it's obvious for user-defined functions, one could be interested, how to make an `asm` function with such behavior? To answer this question, we should look under the hood, how mutation works inside the compiler. + +When a function has `mutate` parameters, it actually implicitly returns them, and they are implicitly assigned to arguments. It's better by example: +```tolk +// actually returns (int, void) +fun increment(mutate x: int): void { ... } + +// actually does: (x', _) = increment(x); x = x' +increment(mutate x); + +// actually returns (int, int, (slice, cell)) +fun f2(mutate x: int, mutate y: int): (slice, cell) { ... } + +// actually does: (x', y', r) = f2(x, y); x = x'; y = y'; someF(r) +someF(f2(mutate x, mutate y)); + +// when `self`, it's exactly the same +// actually does: (cs', r) = loadInt(cs, 32); cs = cs'; flags = r +flags = cs.loadInt(32); +``` + +So, an `asm` function should place `self'` onto a stack before its return value: +```tolk +// "TPUSH" pops (tuple) and pushes (tuple') +// so, self' = tuple', and return an empty tensor +// `void` is a synonym for an empty tensor +fun tuplePush(mutate self: tuple, value: X): void + asm "TPUSH"; + +// "LDU" pops (slice) and pushes (int, slice') +// with asm(-> 1 0), we make it (slice', int) +// so, self' = slice', and return int +fun loadMessageFlags(mutate self: slice): int + asm(-> 1 0) "4 LDU"; +``` + +Note, that to return self, you don't have to do anything special, just specify a return type. Compiler will do the rest. +```tolk +// "STU" pops (int, builder) and pushes (builder') +// with asm(op self), we put arguments to correct order +// so, self' = builder', and return an empty tensor +// but to make it chainable, `self` instead of `void` +fun storeMessageOp(mutate self: builder, op: int): self + asm(op self) "32 STU"; +``` + +It's very unlikely you'll have to do such tricks. Most likely, you'll just write wrappers around existing functions: +```tolk +// just do like this, without asm, it's the same effective + +@inline +fun myLoadMessageFlags(mutate self: slice): int { + return self.loadUint(4); +} + +@inline +fun myStoreMessageOp(mutate self: builder, flags: int): self { + return self.storeUint(32, flags); +} +``` + +

+ Do I need `@inline` for simple functions/methods? +

+ +For now, better do it, yes. In most examples above, `@inline` was omitted for clarity. Currently, without `@inline`, it will be a separate TVM continuation with jumps in/out. With `@inline`, a function will be generated, but inlined by Fift (like `inline` specifer in FunC). + +In the future, Tolk will automatically detect simple functions and perform a true inlining by itself, on AST level. Such functions won't be even codegenerated to Fift. The compiler would decide, better than a human, whether to inline, to make a ref, etc. But it will take some time for Tolk to become so smart :) For now, please specify the `@inline` attribute. + +

+ But `self` is not a method, it's still a function! I feel like I've been cheated +

+ +Absolutely. Like FunC, Tolk has only global functions (as of v0.6). There are no classes / structures with methods. There are no methods `hash()` for `slice` and `hash()` for `cell`. Instead, there are functions `sliceHash()` and `cellHash()`, which can be called either like functions or by dot (preferred): +```tolk +fun f(s: slice, c: cell) { + // not like this + s.hash(); + c.hash(); + // but like this + s.sliceHash(); + c.cellHash(); + // since it's the same as + sliceHash(s); + cellHash(s); +} +``` + +In the future, after a giant work on the type system, having fully refactored FunC kernel inside, Tolk might have an ability of declaring structures with real methods, generalized enough for covering built-in types. But it will take a long journey to follow. + diff --git a/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/stdlib.md b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/stdlib.md new file mode 100644 index 0000000000..70e37faf41 --- /dev/null +++ b/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/stdlib.md @@ -0,0 +1,274 @@ +# Tolk vs FunC: standard library + +FunC has a rich [standard library](/v3/documentation/smart-contracts/func/docs/stdlib), +known as *"stdlib.fc"* file. It's quite low-level and contains lots of `asm` functions +named very closely to TVM commands. + +Tolk also has a standard library based on a FunC one. Three main differences: +1. It's split in multiple files: `common.tolk`, `tvm-dicts.tolk`, and others. Functions from `common.tolk` are available always. Functions from other files are available after import: +```tolk +import "@stdlib/tvm-dicts" + +beginCell() // available always +createEmptyDict() // available due to import +``` +2. You don't need to download it from GitHub, it's a part of Tolk distribution. +3. Almost all FunC functions were renamed to ~~verbose~~ clear names. So that when you write contracts or read example, you better understand what's going on. + + +## A list of renamed functions + +If "Required import" column is empty, a function is available without any imports. + +Note, that some of the functions were deleted, because they either can be expressed syntactically, +or they were very uncommon in practice. + +| FunC name | Tolk name | Required import | +|--------------------------|-----------------------------------------|-----------------| +| empty_tuple | createEmptyTuple | | +| tpush | tuplePush | | +| first | tupleFirst | | +| at | tupleAt | | +| touch | stackMoveToTop | tvm-lowlevel | +| impure_touch | *(deleted)* | | +| single | *(deleted)* | | +| unsingle | *(deleted)* | | +| pair | *(deleted)* | | +| unpair | *(deleted)* | | +| triple | *(deleted)* | | +| untriple | *(deleted)* | | +| tuple4 | *(deleted)* | | +| untuple4 | *(deleted)* | | +| second | *(deleted)* | | +| third | *(deleted)* | | +| fourth | *(deleted)* | | +| pair_first | *(deleted)* | | +| pair_second | *(deleted)* | | +| triple_first | *(deleted)* | | +| triple_second | *(deleted)* | | +| triple_third | *(deleted)* | | +| minmax | minMax | | +| my_address | getMyAddress | | +| get_balance | getMyOriginalBalanceWithExtraCurrencies | | +| cur_lt | getLogicalTime | | +| block_lt | getCurrentBlockLogicalTime | | +| cell_hash | cellHash | | +| slice_hash | sliceHash | | +| string_hash | stringHash | | +| check_signature | isSignatureValid | | +| check_data_signature | isSliceSignatureValid | | +| compute_data_size | calculateCellSizeStrict | | +| slice_compute_data_size | calculateSliceSizeStrict | | +| compute_data_size? | calculateCellSize | | +| slice_compute_data_size? | calculateSliceSize | | +| ~dump | debugPrint | | +| ~strdump | debugPrintString | | +| dump_stack | debugDumpStack | | +| get_data | getContractData | | +| set_data | setContractData | | +| get_c3 | getTvmRegisterC3 | tvm-lowlevel | +| set_c3 | setTvmRegisterC3 | tvm-lowlevel | +| bless | transformSliceToContinuation | tvm-lowlevel | +| accept_message | acceptExternalMessage | | +| set_gas_limit | setGasLimit | | +| buy_gas | *(deleted)* | | +| commit | commitContractDataAndActions | | +| divmod | divMod | | +| moddiv | modDiv | | +| muldiv | mulDivFloor | | +| muldivr | mulDivRound | | +| muldivc | mulDivCeil | | +| muldivmod | mulDivMod | | +| begin_parse | beginParse | | +| end_parse | assertEndOfSlice | | +| load_ref | loadRef | | +| preload_ref | preloadRef | | +| load_int | loadInt | | +| load_uint | loadUint | | +| preload_int | preloadInt | | +| preload_uint | preloadUint | | +| load_bits | loadBits | | +| preload_bits | preloadBits | | +| load_grams | loadCoins | | +| load_coins | loadCoins | | +| skip_bits | skipBits | | +| first_bits | getFirstBits | | +| skip_last_bits | removeLastBits | | +| slice_last | getLastBits | | +| load_dict | loadDict | | +| preload_dict | preloadDict | | +| skip_dict | skipDict | | +| load_maybe_ref | loadMaybeRef | | +| preload_maybe_ref | preloadMaybeRef | | +| cell_depth | getCellDepth | | +| slice_refs | getRemainingRefsCount | | +| slice_bits | getRemainingBitsCount | | +| slice_bits_refs | getRemainingBitsAndRefsCount | | +| slice_empty? | isEndOfSlice | | +| slice_data_empty? | isEndOfSliceBits | | +| slice_refs_empty? | isEndOfSliceRefs | | +| slice_depth | getSliceDepth | | +| equal_slice_bits | isSliceBitsEqual | | +| builder_refs | getBuilderRefsCount | | +| builder_bits | getBuilderBitsCount | | +| builder_depth | getBuilderDepth | | +| begin_cell | beginCell | | +| end_cell | endCell | | +| store_ref | storeRef | | +| store_uint | storeUint | | +| store_int | storeInt | | +| store_slice | storeSlice | | +| store_grams | storeCoins | | +| store_coins | storeCoins | | +| store_dict | storeDict | | +| store_maybe_ref | storeMaybeRef | | +| store_builder | storeBuilder | | +| load_msg_addr | loadAddress | | +| parse_addr | parseAddress | | +| parse_std_addr | parseStandardAddress | | +| parse_var_addr | *(deleted)* | | +| config_param | getBlockchainConfigParam | | +| raw_reserve | reserveToncoinsOnBalance | | +| raw_reserve_extra | reserveExtraCurrenciesOnBalance | | +| send_raw_message | sendRawMessage | | +| set_code | setContractCodePostponed | | +| rand | randomRange | | +| get_seed | randomGetSeed | | +| set_seed | randomSetSeed | | +| randomize | randomizeBy | | +| randomize_lt | randomizeByLogicalTime | | +| dump | debugPrint | | +| strdump | debugPrintString | | +| dump_stk | debugDumpStack | | +| empty_list | createEmptyList | lisp-lists | +| cons | listPrepend | lisp-lists | +| uncons | listSplit | lisp-lists | +| list_next | listNext | lisp-lists | +| car | listGetHead | lisp-lists | +| cdr | listGetTail | lisp-lists | +| new_dict | createEmptyDict | tvm-dicts | +| dict_empty? | dictIsEmpty | tvm-dicts | +| idict_set_ref | iDictSetRef | tvm-dicts | +| udict_set_ref | uDictSetRef | tvm-dicts | +| idict_get_ref | iDictGetRefOrNull | tvm-dicts | +| idict_get_ref? | iDictGetRef | tvm-dicts | +| udict_get_ref? | uDictGetRef | tvm-dicts | +| idict_set_get_ref | iDictSetAndGetRefOrNull | tvm-dicts | +| udict_set_get_ref | iDictSetAndGetRefOrNull | tvm-dicts | +| idict_delete? | iDictDelete | tvm-dicts | +| udict_delete? | uDictDelete | tvm-dicts | +| idict_get? | iDictGet | tvm-dicts | +| udict_get? | uDictGet | tvm-dicts | +| idict_delete_get? | iDictDeleteAndGet | tvm-dicts | +| udict_delete_get? | uDictDeleteAndGet | tvm-dicts | +| udict_set | uDictSet | tvm-dicts | +| idict_set | iDictSet | tvm-dicts | +| dict_set | sDictSet | tvm-dicts | +| udict_add? | uDictSetIfNotExists | tvm-dicts | +| udict_replace? | uDictSetIfExists | tvm-dicts | +| idict_add? | iDictSetIfNotExists | tvm-dicts | +| idict_replace? | iDictSetIfExists | tvm-dicts | +| udict_set_builder | uDictSetBuilder | tvm-dicts | +| idict_set_builder | iDictSetBuilder | tvm-dicts | +| dict_set_builder | sDictSetBuilder | tvm-dicts | +| udict_add_builder? | uDictSetBuilderIfNotExists | tvm-dicts | +| udict_replace_builder? | uDictSetBuilderIfExists | tvm-dicts | +| idict_add_builder? | iDictSetBuilderIfNotExists | tvm-dicts | +| idict_replace_builder? | iDictSetBuilderIfExists | tvm-dicts | +| udict_delete_get_min | uDictDeleteFirstAndGet | tvm-dicts | +| idict_delete_get_min | iDictDeleteFirstAndGet | tvm-dicts | +| dict_delete_get_min | sDictDeleteFirstAndGet | tvm-dicts | +| udict_delete_get_max | uDictDeleteLastAndGet | tvm-dicts | +| idict_delete_get_max | iDictDeleteLastAndGet | tvm-dicts | +| dict_delete_get_max | sDictDeleteLastAndGet | tvm-dicts | +| udict_get_min? | uDictGetFirst | tvm-dicts | +| udict_get_max? | uDictGetLast | tvm-dicts | +| udict_get_min_ref? | uDictGetFirstAsRef | tvm-dicts | +| udict_get_max_ref? | uDictGetLastAsRef | tvm-dicts | +| idict_get_min? | iDictGetFirst | tvm-dicts | +| idict_get_max? | iDictGetLast | tvm-dicts | +| idict_get_min_ref? | iDictGetFirstAsRef | tvm-dicts | +| idict_get_max_ref? | iDictGetLastAsRef | tvm-dicts | +| udict_get_next? | uDictGetNext | tvm-dicts | +| udict_get_nexteq? | uDictGetNextOrEqual | tvm-dicts | +| udict_get_prev? | uDictGetPrev | tvm-dicts | +| udict_get_preveq? | uDictGetPrevOrEqual | tvm-dicts | +| idict_get_next? | iDictGetNext | tvm-dicts | +| idict_get_nexteq? | iDictGetNextOrEqual | tvm-dicts | +| idict_get_prev? | iDictGetPrev | tvm-dicts | +| idict_get_preveq? | iDictGetPrevOrEqual | tvm-dicts | +| udict::delete_get_min | uDictDeleteFirstAndGet | tvm-dicts | +| idict::delete_get_min | iDictDeleteFirstAndGet | tvm-dicts | +| dict::delete_get_min | sDictDeleteFirstAndGet | tvm-dicts | +| udict::delete_get_max | uDictDeleteLastAndGet | tvm-dicts | +| idict::delete_get_max | iDictDeleteLastAndGet | tvm-dicts | +| dict::delete_get_max | sDictDeleteLastAndGet | tvm-dicts | +| pfxdict_get? | prefixDictGet | tvm-dicts | +| pfxdict_set? | prefixDictSet | tvm-dicts | +| pfxdict_delete? | prefixDictDelete | tvm-dicts | + + +## A list of added functions + +Tolk standard library has some functions that were missing in FunC, but are quite common for everyday tasks. + +Since Tolk is actively developed, and its standard library changes, better consider `tolk-stdlib/` folder +in sources [here](https://github.com/ton-blockchain/ton/tree/master/crypto/smartcont/tolk-stdlib). +Besides functions, there some constants were added: `SEND_MODE_*`, `RESERVE_MODE_*`, etc. + +When FunC becomes deprecated, the documentation about Tolk stdlib will be completely rewritten, anyway. + +And remember, that all the functions above are actually wrappers over TVM assembler. If something is missing, +you can easily wrap any TVM instruction yourself. + + +## Some functions became mutating, not returning a copy + + + + + + + + + + + + + + + + + + + + + + +
FunCTolk
{'int flags = cs~load_uint(32);'}{'var flags = cs.loadUint(32);'}
{'dict~udict_set(...);'}{'dict.uDictSet(...);'}
......
+ +Most FunC functions, that were used with `~` tilda in practice, now mutate the object, see examples above. + +For example, if you used `dict~udict_set(…)`, just use `dict.uDictSet(…)`, and everything is fine. +But if you used `dict.udict_set(…)` to obtain a copy, you'll need to express it some other way. + +[Read about mutability](/v3/documentation/smart-contracts/tolk/tolk-vs-func/mutability). + + +## How does embedded stdlib work under the hood + +As told above, all standard functions are available out of the box. +Yeah, for you need `import` for non-common functions (it's intentionally), but still, no external downloads. + +It works the following way. + +The first thing Tolk compiler does on start is locating stdlib folder by searching in predefined paths relative to an executable binary. +For example, if you launch Tolk compiler from a package installed (e.g. `/usr/bin/tolk`), locate stdlib in `/usr/share/ton/smartcont`. +If you have non-standard installation, you may pass `TOLK_STDLIB` env variable. It's standard practice for compilers. + +A WASM wrapper [tolk-js](https://github.com/ton-blockchain/tolk-js) also contains stdlib. +So, when you take tolk-js or blueprint, all stdlib functions are still available out of the box. + +IDE plugins (both JetBrains and VS Code) also auto-locate stdlib to provide auto-completion. +If you use blueprint, it automatically installs tolk-js, and therefore, folder `node_modules/@ton/tolk-js/` exists in your project file structure. +Inside, there are `common.tolk`, `tvm-dicts.tolk`, and others. diff --git a/docs/v3/documentation/tvm/changelog/tvm-upgrade-2023-07.md b/docs/v3/documentation/tvm/changelog/tvm-upgrade-2023-07.md index fa7dd679c4..2b57dc5ab2 100644 --- a/docs/v3/documentation/tvm/changelog/tvm-upgrade-2023-07.md +++ b/docs/v3/documentation/tvm/changelog/tvm-upgrade-2023-07.md @@ -68,7 +68,7 @@ Rule of thumb when choosing gas cost on new opcodes is that it should not be les | `GASCONSUMED` | _`- g_c`_ | Returns gas consumed by VM so far (including this instruction).
_26 gas_ | ## Arithmetics -New variants of [the division opcode](v3/documentation/tvm/instructions#52-division) (`A9mscdf`) are added: +New variants of [the division opcode](/v3/documentation/tvm/instructions#52-division) (`A9mscdf`) are added: `d=0` takes one additional integer from stack and adds it to the intermediate value before division/rshift. These operations return both the quotient and the remainder (just like `d=3`). Quiet variants are also available (e.g. `QMULADDDIVMOD` or `QUIET MULADDDIVMOD`). diff --git a/docs/v3/documentation/tvm/tvm-exit-codes.md b/docs/v3/documentation/tvm/tvm-exit-codes.md index a54863b6fc..183e20544f 100644 --- a/docs/v3/documentation/tvm/tvm-exit-codes.md +++ b/docs/v3/documentation/tvm/tvm-exit-codes.md @@ -1,43 +1,43 @@ # TVM Exit codes -If TVM exits with an arbitrary 16-bit unsigned integer `exit_code`. `exit_code` higher than 1, it is considered to be an _error code_, therefore an exit with such a code may cause the transaction to revert/bounce. +If TVM exits with an arbitrary 16-bit unsigned integer `exit_code`. `exit_code` higher than 1, it is considered an _error code_. Therefore, an exit with such a code may cause the transaction to revert or bounce. ## Standard exit codes :::info -The list of standard exit codes contains all universal TVM exit codes defined for TON Blockchain. Alternative exit codes should be sought in the source code of corresponded contract. +The list of standard exit codes contains all universal TVM exit codes defined for the TON Blockchain. Alternative exit codes should be sought in the source code of the corresponding contract. ::: -| Exit Code | TVM Phase | Description | -|-----------|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `0` | Compute Phase | Standard successful execution exit code. | -| `1` | Compute Phase | Alternative successful execution exit code. | -| `2` | Compute Phase | Stack underflow. Last op-code consumed more elements than there are on the stacks. 1 | -| `3` | Compute Phase | Stack overflow. More values have been stored on a stack than allowed by this version of TVM. | -| `4` | Compute Phase | Integer overflow. Integer does not fit into −2256 ≤ x < 2256 or a division by zero has occurred. | -| `5` | Compute Phase | Integer out of expected range. | -| `6` | Compute Phase | Invalid opcode. Instruction is unknown in the current TVM version. | -| `7` | Compute Phase | Type check error. An argument to a primitive is of an incorrect value type. 1 | -| `8` | Compute Phase | Cell overflow. Writing to builder is not possible since after operation there would be more than 1023 bits or 4 references. | -| `9` | Compute Phase | Cell underflow. Read from slice primitive tried to read more bits or references than there are. | -| `10` | Compute Phase | Dictionary error. Error during manipulation with dictionary (hashmaps). | +| Exit Code | TVM Phase | Description | +|-----------|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `0` | Compute Phase | Standard successful execution exit code. | +| `1` | Compute Phase | Alternative successful execution exit code. | +| `2` | Compute Phase | Stack underflow. The last op-code consumed more elements than there are on the stacks. 1 | +| `3` | Compute Phase | Stack overflow. More values have been stored on a stack than are allowed by this version of TVM. | +| `4` | Compute Phase | Integer overflow. Integer does not fit into −2256 ≤ x < 2256 or a division by zero has occurred. | +| `5` | Compute Phase | Integer is out of expected range. | +| `6` | Compute Phase | Invalid opcode. The instruction is unknown in the current TVM version. | +| `7` | Compute Phase | Type check error. An argument to a primitive has an incorrect value type. 1 | +| `8` | Compute Phase | Cell overflow. Writing to the builder is not possible since after operation there would be more than 1023 bits or 4 references. | +| `9` | Compute Phase | Cell underflow. The read operation from slice primitive tried to read more bits or references than available. | +| `10` | Compute Phase | Dictionary error. An error during manipulation with the dictionary (hashmaps). | | `11` | Compute Phase | Most often caused by trying to call get-method whose id wasn't found in the code (missing `method_id` modifier or wrong get-method name specified when trying to call it). In [TVM docs](https://ton.org/tvm.pdf) its described as "Unknown error, may be thrown by user programs". | -| `12` | Compute Phase | Thrown by TVM in situations deemed impossible. | -| `13` | Compute Phase | Out of gas error. Thrown by TVM when the remaining gas becomes negative. | -| `-14` | Compute Phase | It means out of gas error, same as `13`. Negative, because it [cannot be faked](https://github.com/ton-blockchain/ton/blob/20758d6bdd0c1327091287e8a620f660d1a9f4da/crypto/vm/vm.cpp#L492) | -| `32` | Action Phase | Action list is invalid. Set during action phase if c5 register after execution contains unparsable object. | -| `-32` | Action Phase | (the same as prev 32) - Method ID not found. Returned by TonLib during an attempt to execute non-existent get method. | -| `33` | Action Phase | Action list is too long. | -| `34` | Action Phase | Action is invalid or not supported. Set during action phase if current action cannot be applied. | -| `35` | Action Phase | Invalid Source address in outbound message. | -| `36` | Action Phase | Invalid Destination address in outbound message. | -| `37` | Action Phase | Not enough TON. Message sends too much TON (or there is not enough TON after deducting fees). | -| `38` | Action Phase | Not enough extra-currencies. | -| `40` | Action Phase | Not enough funds to process a message. This error is thrown when there is only enough gas to cover part of the message, but does not cover it completely. | -| `43` | Action Phase | The maximum number of cells in the library is exceeded or the maximum depth of the Merkle tree is exceeded. | +| `12` | Compute Phase | Thrown by TVM in situations considered impossible. | +| `13` | Compute Phase | Out of gas error. Thrown by TVM when the remaining gas turns negative. | +| `-14` | Compute Phase | This indicates an out of gas error, the same as code `13`. It is negative because it [cannot be faked](https://github.com/ton-blockchain/ton/blob/20758d6bdd0c1327091287e8a620f660d1a9f4da/crypto/vm/vm.cpp#L492) | +| `32` | Action Phase | Action list is invalid. Set during the action phase if c5 register after execution contains unparsable object. | +| `-32` | Action Phase | (the same as prev 32) - Method ID not found. Returned by TonLib during an attempt to execute non-existent get method. | +| `33` | Action Phase | The action list is too long. | +| `34` | Action Phase | Action is invalid or not supported. Set during the action phase if current action cannot be applied. | +| `35` | Action Phase | Invalid Source address in the outbound message. | +| `36` | Action Phase | Invalid Destination address in the outbound message. | +| `37` | Action Phase | Not enough TON. The message sends too much TON, or there isn't enough TON remaining after deducting fees. | +| `38` | Action Phase | Not enough extra-currencies. | +| `40` | Action Phase | Not enough funds to process the message. This error is thrown when there is only enough gas to partially cover the message, but not enough to cover it completely. | +| `43` | Action Phase | The maximum number of cells in the library has been exceeded, or the maximum depth of the Merkle tree has been surpassed. | 1 If you encounter such exception in a func contract it probably means a type error in asm declarations. :::info Often you can see the exit code `0xffff` (65535 in decimal form). This usually means that the received opcode is unknown to the contract. When writing contracts, this code is set by the developer himself. -::: \ No newline at end of file +::: diff --git a/docs/v3/documentation/tvm/tvm-initialization.md b/docs/v3/documentation/tvm/tvm-initialization.md index 9c8a0170f2..6b35346075 100644 --- a/docs/v3/documentation/tvm/tvm-initialization.md +++ b/docs/v3/documentation/tvm/tvm-initialization.md @@ -174,7 +174,7 @@ First component of this tuple is an _Integer_ value, which is always equal to 0x | `actions` | uint16 | Originally initialized by 0, but incremented by one whenever an output action is installed by a non-RAW output action primitive | | `msgs_sent` | uint16 | Number of messages sent | | `unixtime` | uint32 | Unix timestamp in seconds | -| `block_lt` | uint64 | Represents _logical time_ of the previous block of this account. [More about logical time](v3/documentation/smart-contracts/message-management/messages-and-transactions#what-is-a-logical-time) | +| `block_lt` | uint64 | Represents _logical time_ of the previous block of this account. [More about logical time](/v3/documentation/smart-contracts/message-management/messages-and-transactions#what-is-a-logical-time) | | `trans_lt` | uint64 | Represents _logical time_ of the previous transaction of this account | | `rand_seed` | bits256 | Initialized deterministically starting from `rand_seed` of the block, the account address, the hash of the incoming message being processed (if any), and the transaction logical time `trans_lt` | | `balance_remaining` | [CurrencyCollection](/v3/documentation/data-formats/tlb/msg-tlb#currencycollection) | Remaining balance of the smart contract | diff --git a/docs/v3/documentation/whitepapers/overview.md b/docs/v3/documentation/whitepapers/overview.md index fd7b8e4264..2a59c8c71b 100644 --- a/docs/v3/documentation/whitepapers/overview.md +++ b/docs/v3/documentation/whitepapers/overview.md @@ -14,7 +14,7 @@ Please note that here and later the code, comments and/or documentation may cont * [TON Virtual Machine](https://docs.ton.org/tvm.pdf) - TON Virtual Machine description(may include outdated information on OP Codes, actual list in [TVM Instruction](v3/documentation/tvm/tvm-overview) section). + TON Virtual Machine description(may include outdated information on OP Codes, actual list in [TVM Instruction](/v3/documentation/tvm/tvm-overview) section). * [TON Blockchain](https://docs.ton.org/tblkch.pdf) diff --git a/docs/v3/guidelines/dapps/apis-sdks/api-types.md b/docs/v3/guidelines/dapps/apis-sdks/api-types.md index 873bd90278..433237d185 100644 --- a/docs/v3/guidelines/dapps/apis-sdks/api-types.md +++ b/docs/v3/guidelines/dapps/apis-sdks/api-types.md @@ -10,12 +10,13 @@ - [toncenter/v2](https://toncenter.com/) - This API enables HTTP access to TON blockchain - getting accounts and wallets information, looking up blocks and transactions, sending messages to the blockchain, calling get methods of smart contracts, and more. ## Third party APIs -- [tonapi.io](https://docs.tonconsole.com/tonapi) — Fast indexed API providing basic data about accounts, transactions, blocks, and application-specific data about NFTs, Auctions, Jettons, TON DNS, and Subscriptions. It also provides annotated data on transaction chains. -- [TONX API](https://docs.tonxapi.com/reference/build-your-first-dapp) — Your go-to API for accessing data on accounts, transactions, blocks, NFTs, and Jettons with 99.99% uptime—just like TonKey and TonStake did. -- [dton.io](https://dton.io/graphql/) — GraphQL API that can provide data about accounts, transactions, and blocks, as well as application-specific data about NFTs, Auctions, Jettons, and TON DNS. -- [ton-api-v4](https://mainnet-v4.tonhubapi.com) — A lite API focused on speed via aggressive caching in CDN. -- [docs.nftscan.com](https://docs.nftscan.com/reference/ton/model/asset-model) — NFT APIs for the TON blockchain. -- [everspace.center](https://everspace.center/toncoin) — Simple RPC API for accessing the TON blockchain. +- [tonapi.io](https://docs.tonconsole.com/tonapi) - fast indexed API which provides basic data about accounts, transactions, blocks, application-specific data about NFT, Auctions, Jettons, TON DNS, Subscriptions. It also provides annotated data on transaction chains. +- [TONX API](https://docs.tonxapi.com/) - an API specifically designed for seamless Dapp development, enabling easy access to a variety of tools and data. +- [dton.io](https://dton.io/graphql/) - GraphQL API with that can provide data about accounts, transactions and blocks, as well as application-specific data about NFT, Auctions, Jettons and TON DNS. +- [ton-api-v4](https://mainnet-v4.tonhubapi.com) - another lite-api focused on speed via aggressive cashing in CDN. +- [docs.nftscan.com](https://docs.nftscan.com/reference/ton/model/asset-model) - NFT APIs for TON blockchain. +- [everspace.center](https://everspace.center/toncoin) - Simple RPC API for accessing TON Blockchain. + ## Additional APIs diff --git a/docs/v3/guidelines/dapps/apis-sdks/ton-adnl-apis.md b/docs/v3/guidelines/dapps/apis-sdks/ton-adnl-apis.md index c1a2aea589..d46226b7e2 100644 --- a/docs/v3/guidelines/dapps/apis-sdks/ton-adnl-apis.md +++ b/docs/v3/guidelines/dapps/apis-sdks/ton-adnl-apis.md @@ -23,7 +23,7 @@ Read more about [Merkle proofs](/v3/documentation/data-formats/tlb/proofs) at [T Public liteservers (from the global config) exist to get you started with TON quickly. It can be used for learning to program in TON, or for applications and scripts that do not require 100% uptime. For building production infrastructure - it is suggested use well prepared infrastructure: -- [set up own liteserver](v3/guidelines/nodes/running-nodes/full-node#enable-liteserver-mode), +- [set up own liteserver](/v3/guidelines/nodes/running-nodes/full-node#enable-liteserver-mode), - use Liteserver premium providers [@liteserver_bot](https://t.me/liteserver_bot) ## Pros & Cons diff --git a/docs/v3/guidelines/dapps/asset-processing/jettons.md b/docs/v3/guidelines/dapps/asset-processing/jettons.md index 56f5eae3b2..69f87b8f0b 100644 --- a/docs/v3/guidelines/dapps/asset-processing/jettons.md +++ b/docs/v3/guidelines/dapps/asset-processing/jettons.md @@ -4,19 +4,92 @@ import Button from '@site/src/components/button'; # Jetton Processing +## Best Practices on Jettons Processing + +Jettons are tokens on TON Blockchain - one can consider them similarly to ERC-20 tokens on Ethereum. + +:::info Transaction Confirmation +TON transactions are irreversible after just one confirmation. For the best UX/UI avoid additional waiting. +::: + +#### Withdrawal + +[Highload Wallet v3](/v3/documentation/smart-contracts/contracts-specs/highload-wallet#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](https://github.com/toncenter/examples/blob/main/withdrawals-jettons-highload-batch.js) - Meaning that multiple withdrawals are sent in batches, allowing for quick and cheap withdrawals. + +#### Deposits :::info -For clear understanding, the reader should be familiar with the basic principles of asset processing described in [payments processing section](/v3/guidelines/dapps/asset-processing/payments-processing) of our documentation. +It is suggested to set several MEMO deposit wallets for better performance. ::: -Jettons are tokens on TON Blockchain set with [TEP-74](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md). One can consider them similarly to ERC-20 tokens on Ethereum. +[Memo Deposits](https://github.com/toncenter/examples/blob/main/deposits-jettons.js) - 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](https://github.com/gobicycle/bicycle) - 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 + +:::caution Transaction Notification +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](https://testnet.tonviewer.com/transaction/a0eede398d554318326b6e13081c2441f8b9a814bf9704e2e2f44f24adb3d407), 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](https://github.com/toncenter/tonweb) - which is the official JS library from the TON Foundation. + +- If you want to use Java, you can look into [ton4j](https://github.com/neodix42/ton4j/tree/main). + +- For Go, one should consider [tonutils-go](https://github.com/xssnick/tonutils-go). At the moment, we recommend the JS lib. + + +## Content List + + +:::tip +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: +1. Overview +2. Architecture +2. Jetton Master Contract (Token Minter) +3. Jetton Wallet Contract (User Wallet) +4. Message Layouts +4. Jetton Processing (off-chain) +5. Jetton Processing (on-chain) +6. Wallet processing +7. Best Practices + +## Overview + +:::info +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](/v3/documentation/dapps/assets/overview). In particular, it is important to be familiar with [contracts](/v3/documentation/smart-contracts/addresses#everything-is-a-smart-contract), [wallets](/v3/guidelines/smart-contracts/howto/wallet), [messages](/v3/documentation/smart-contracts/message-management/messages-and-transactions) and deployment process. +::: + +:::Info +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](https://docs.ton.org/catchain.pdf#page=3). +::: + +Quick jump to the core description of jetton 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](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md) and [metadata](https://github.com/ton-blockchain/TEPs/blob/master/text/0064-token-data-standard.md). A less formal sharding-focused overview of jetton architecture can be found in our [anatomy of jettons blog post](https://blog.ton.org/how-to-shard-your-ton-smart-contract-and-why-studying-the-anatomy-of-tons-jettons). -Also, you should keep in mind that there are two approaches to working with jetton withdraws: -- [Memo Deposits](https://github.com/toncenter/examples/blob/main/deposits-jettons.js) - 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 this is slightly less easy for your users. -- [Memo-less deposits](https://github.com/gobicycle/bicycle) - This solution also exists. However, it is more difficult to integrate. If you would prefer to take this route, please notify us before deciding to implement this approach as we can assist with this. +We have also provided specific details discussing our third-party open-source TON Payment Processor ([bicycle](https://github.com/gobicycle/bicycle)) which allows users to deposit and withdraw both Toncoin and jettons using a separate deposit address without using a text memo. + + + ## Jetton Architecture @@ -46,27 +119,22 @@ To eliminate the possibility of fraud for TON users, please look up the **origin ### Retrieving Jetton data -To retrieve more specific Jetton data use the contract's _get_ method `get_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](https://github.com/ton-blockchain/TEPs/blob/master/text/0064-token-data-standard.md), check [jetton metadata parsing page](/v3/guidelines/dapps/asset-processing/nft-processing/metadata-parsing) for more. | -| `jetton_wallet_code` | `cell` | | - -You can call it via [Toncenter API](https://toncenter.com/api/v3/#/default/get_jetton_masters_api_v3_jetton_masters_get) or one of the [SDKs](/v3/guidelines/dapps/apis-sdks/sdk). +| 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](https://github.com/ton-blockchain/TEPs/blob/master/text/0064-token-data-standard.md), check [jetton metadata parsing page](/v3/guidelines/dapps/asset-processing/nft-processing/metadata-parsing) for more. | +| `jetton_wallet_code` | `cell` | | - - -> Run `jetton/masters` method from the [Toncenter API](https://toncenter.com/api/v3/#/default/get_jetton_masters_api_v3_jetton_masters_get) +It is also possible to use the method `/jetton/masters` from the [Toncenter API](https://toncenter.com/api/v3/#/default/get_jetton_masters_api_v3_jetton_masters_get) to retrieve the already decoded Jetton data and metadata. We have also developed methods for (js) [tonweb](https://github.com/toncenter/tonweb/blob/master/src/contract/token/ft/JettonMinter.js#L85) and (js) [ton-core/ton](https://github.com/ton-core/ton/blob/master/src/jetton/JettonMaster.ts#L28), (go) [tongo](https://github.com/tonkeeper/tongo/blob/master/liteapi/jetton.go#L48) and (go) [tonutils-go](https://github.com/xssnick/tonutils-go/blob/33fd62d754d3a01329ed5c904db542ab4a11017b/ton/jetton/jetton.go#L79), (python) [pytonlib](https://github.com/toncenter/pytonlib/blob/d96276ec8a46546638cb939dea23612876a62881/pytonlib/client.py#L742) and many other [SDKs](/v3/guidelines/dapps/apis-sdks/sdk). - - +Example of using [Tonweb](https://github.com/toncenter/tonweb) to run a get method and get url for off-chain metadata: ```js import TonWeb from "tonweb"; @@ -77,9 +145,6 @@ 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`. @@ -92,7 +157,7 @@ If the jetton admin wants to restrict jetton creation, there are three ways to d 1. 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. 2. 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. -3. If you can update the contract's code, you can add restrictions by updating the code of the already deployed contract. +3. 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. @@ -116,7 +181,7 @@ the `Jetton master contract` provides the get method `get_wallet_address(slice o -> Run `get_wallet_address(slice owner_address)` through `/runGetMethod` method from the [Toncenter API](https://toncenter.com/api/v3/#/default/run_get_method_api_v3_runGetMethod_post). In real cases (not test ones) it is important to always check that the wallet indeed is attributed to desired Jetton Master. Check code example for more. +> Run `get_wallet_address(slice owner_address)` through `/runGetMethod` method from the [Toncenter API](https://toncenter.com/api/v3/#/default/run_get_method_api_v3_runGetMethod_post). 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. @@ -142,6 +207,11 @@ console.log('Jetton wallet address:', jettonWalletAddress.toString(true, true, t +:::tip +For more examples read the [TON Cookbook](/v3/guidelines/dapps/cookbook#tep-74-jettons-standard). +::: + + ### 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. @@ -186,7 +256,11 @@ console.log('Jetton master address:', data.jettonMinterAddress.toString(true, tr -## Jetton wallets communication overview +## Message Layouts + +:::tip Messages +Read more about Messages [here](/v3/documentation/smart-contracts/message-management/messages-and-transactions). +::: Communication between Jetton wallets and TON wallets occurs through the following communication sequence: @@ -199,7 +273,7 @@ Communication between Jetton wallets and TON wallets occurs through the followin |------------------------|------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `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. | +| `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`** | @@ -223,25 +297,27 @@ Here `sender` address is an address of Alice's `Jetton wallet`. | Name | Type | |----------------------|----------------| -| `query_id` | uint64 | +| `query_id` | uint64 | :::tip Jettons standard A detailed description of the jetton wallet contract fields can be found in the [TEP-74](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md) `Jetton standard` interface description. ::: -## Send Jettons with comments - -This transfer requires some ton coins for **fees** and, optionally, **transfer notification message** (check forward amount field). +## How to send Jetton transfers with comments and notifications -To send a **comment** you need set up a `forward payload`. Set the **first 32 bits to 0x0** and append **your text**. +This transfer require some ton coins for **fees** and **transfer notification message**. -`forward payload` is sent in `transfer notification` internal message. It will be generated only if `forward_ton_amount` > 0. Recommended `forward_ton_amount` for jetton transfer with comment is 1 nanoton. +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. +:::info +Recommended `forward_ton_amount` for jetton transfer with comment is 1 nanoton. +::: -Finally, to retrieve an `Excess` message you must set up a `response destination`. +Finally, to retrieve `Excess 0xd53276db` message you must set up `response destination`. -Sometimes you may encounter a `709` error when sending jetton. It says that the value of the toncoin attached to the message is not enough to send it. Make sure that `Toncoin > to_nano(TRANSFER_CONSUMPTION) + forward_ton_amount`. `TRANSFER_CONSUMPTION` in most cases may be 0.037 if the `forward_payload` is not too large. +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. +You may also encounter the error [`cskip_no_gas`](/v3/documentation/tvm/tvm-overview#compute-phase-skipped), 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. :::tip Check [best practices](/v3/guidelines/dapps/asset-processing/jettons#best-practices) for _"send jettons with comments"_ example. @@ -276,7 +352,7 @@ The sender address of the internal message containing the `Transfer notification It should not to be confused with the `sender` field in the `Transfer notification` [body](/v3/guidelines/dapps/asset-processing/jettons#jetton-wallets-communication-overview). 1. Retrieve the Jetton master address for the new Jetton wallet by [getting wallet data](/v3/guidelines/dapps/asset-processing/jettons#retrieving-data-for-a-specific-jetton-wallet). -2. 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](#retrieving-jetton-wallet-addresses-for-a-given-user). +2. 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](#retrieving-jetton-wallet-addresses-for-a-given-user) 3. 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. 4. Retrieve Jetton metadata: [How to receive Jetton metadata](#retrieving-jetton-data). @@ -286,7 +362,11 @@ It should not to be confused with the `sender` field in the `Transfer notificati ### Accepting Jettons from users through a centralized wallet :::info -To prevent a bottleneck of 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. +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. +::: + +:::caution Transaction Notification +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](https://testnet.tonviewer.com/transaction/a0eede398d554318326b6e13081c2441f8b9a814bf9704e2e2f44f24adb3d407), 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 @@ -305,7 +385,7 @@ Tonweb examples: #### Preparations 1. [Prepare a list of accepted Jettons](/v3/guidelines/dapps/asset-processing/jettons#adding-new-jettons-for-asset-processing-and-initial-verification) (Jetton master addresses). -2. Deploy hot wallet (using v3R2 if no Jetton withdrawals are expected; highload v3 - if Jetton withdrawals are expected). [Wallet deployment](/v3/guidelines/dapps/asset-processing/payments-processing/#wallet-deployment). +2. Deploy hot wallet (using v3R2 if no Jetton withdrawals are expected; highload v3 - if Jetton withdrawals are expected). [Wallet deployment](/v3/guidelines/dapps/asset-processing/payments-processing#wallet-deployment). 3. Perform a test Jetton transfer using the hot wallet address to initialize the wallet. #### Processing incoming Jettons @@ -315,7 +395,7 @@ Tonweb examples: 4. 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. 5. 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](v3/guidelines/dapps/asset-processing/payments-processing/#checking-contracts-transactions). + iterate it (by sorting through each transaction one by one). See: [Checking contract's transactions](https://docs.ton.org/develop/dapps/asset-processing/#checking-contracts-transactions). 6. Check the input message (in_msg) for transactions and retrieve the source address from the input message. [Tonweb example](https://github.com/toncenter/examples/blob/9f20f7104411771793dfbbdf07f0ca4860f12de2/deposits-jettons-single-wallet.js#L84) 7. 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. @@ -358,12 +438,12 @@ const wallet = new WalletClass(tonweb.provider, { #### Preparation 1. [Prepare a list of accepted Jettons](#adding-new-jettons-for-asset-processing-and-initial-verification). -2. Deploy hot wallet (using v3R2 if no Jetton withdrawals are expected; highload v3 - if Jetton withdrawals are expected). [Wallet deployment](/v3/guidelines/dapps/asset-processing/payments-processing/#wallet-deployment). +2. Deploy hot wallet (using v3R2 if no Jetton withdrawals are expected; highload v3 - if Jetton withdrawals are expected). [Wallet deployment](/v3/guidelines/dapps/asset-processing/payments-processing#wallet-deployment). #### Creating deposits 1. Accept a request to create a new deposit for the user. -2. Generate a new subwallet (v3R2) address based on the hot wallet seed. [Creating a subwallet in Tonweb](#creating-a-subwallet-in-tonweb) +2. Generate a new subwallet (/v3R2) address based on the hot wallet seed. [Creating a subwallet in Tonweb](#creating-a-subwallet-in-tonweb) 3. 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. @@ -416,8 +496,8 @@ requirement to pay storage fees. Jetton deposit wallets can be deployed when sen mechanism for sending messages: [128 + 32](/v3/documentation/smart-contracts/message-management/sending-messages#message-modes). -1. Retrieve a list of deposits marked for withdrawal to a hot wallet. -2. Retrieve saved owner addresses for each deposit. +1. Retrieve a list of deposits marked for withdrawal to a hot wallet +2. Retrieve saved owner addresses for each deposit 3. 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 the `forward_ton_amount` @@ -438,24 +518,24 @@ mechanism for sending messages: [128 + 32](/v3/documentation/smart-contracts/mes :::info Important It's **recommended** to read and **understand** [how does jetton transfer work](/v3/guidelines/dapps/asset-processing/jettons#jetton-wallets-communication-overview) and [how to send jettons with comment](/v3/guidelines/dapps/asset-processing/jettons#jetton-off-chain-processing) articles before reading this section. -Below you'll find a step-by-step guide on how to process jetton withdrawals. +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. In good faith, it is important to attach some TON +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](#jetton-contract-message-layouts) #### Preparation 1. Prepare a list of Jettons for withdrawals: [Adding new Jettons for processing and initial verification](#adding-new-jettons-for-asset-processing-and-initial-verification) -2. Hot wallet deployment is initiated. Highload v3 is recommended. [Wallet Deployment](/v3/guidelines/dapps/asset-processing/payments-processing/#wallet-deployment) +2. Hot wallet deployment is initiated. Highload v3 is recommended. [Wallet Deployment](/v3/guidelines/dapps/asset-processing/payments-processing#wallet-deployment) 3. Carry out a Jetton transfer using a hot wallet address to initialize the Jetton wallet and replenish its balance. #### Processing withdrawals -1. Load a list of processed Jettons. -2. Retrieve Jetton wallet addresses for the deployed hot wallet: [How to retrieve Jetton wallet addresses for a given user](#retrieving-jetton-wallet-addresses-for-a-given-user). +1. Load a list of processed Jettons +2. Retrieve Jetton wallet addresses for the deployed hot wallet: [How to retrieve Jetton wallet addresses for a given user](#retrieving-jetton-wallet-addresses-for-a-given-user) 3. Retrieve Jetton master addresses for each Jetton wallet: [How to retrieve data for Jetton wallets](#retrieving-data-for-a-specific-jetton-wallet). A `jetton` parameter is required (which is actually the address of Jetton master contract). 4. Compare the addresses from Jetton master contracts from step 1. and step 3. If the addresses do not match, then a Jetton address verification error should be reported. @@ -464,10 +544,10 @@ See: [Jetton contracts message layouts](#jetton-contract-message-layouts) 7. Generate a [message](/v3/guidelines/dapps/asset-processing/jettons#message-0). 8. When using a highload wallet, it is recommended that a batch of messages is collected and that one batch at a time is sent to optimize fees. 9. Save the expiration time for outgoing external messages (this is the time until the wallet successfully - processes the message, after this is completed, the wallet will no longer accept the message). + processes the message, after this is completed, the wallet will no longer accept the message) 10. Send a single message or more than one message (batch messaging). 11. Retrieve the list of the latest unprocessed transactions within the hot wallet account and iterate it. - Learn more here: [Checking contract's transactions](/v3/guidelines/dapps/asset-processing/payments-processing/#checking-contracts-transactions), + Learn more here: [Checking contract's transactions](/develop/dapps/asset-processing/#checking-contracts-transactions), [Tonweb example](https://github.com/toncenter/examples/blob/9f20f7104411771793dfbbdf07f0ca4860f12de2/deposits-single-wallet.js#L43) or use the Toncenter API `/getTransactions` method. 12. Look at outgoing messages in the account. @@ -477,7 +557,7 @@ See: [Jetton contracts message layouts](#jetton-contract-message-layouts) the expiration time and the outgoing message with the given `query_id` is not found, then the request should (this is optional) be marked as expired and should be safely resent. 15. Look for incoming messages in the account. -16. If a message that uses the `excesses` op code exists, the message should be decoded and the `query_id` +16. If a message that uses the `Excess 0xd53276db` op code exists, the message should be decoded and the `query_id` value should be retrieved. A found `query_id` must be marked as successfully delivered. 17. Go to step 5. Expired requests that have not been successfully sent should be pushed back to the withdrawal list. diff --git a/docs/v3/guidelines/dapps/asset-processing/payments-processing.md b/docs/v3/guidelines/dapps/asset-processing/payments-processing.md index 56ef41996a..a6ca079f67 100644 --- a/docs/v3/guidelines/dapps/asset-processing/payments-processing.md +++ b/docs/v3/guidelines/dapps/asset-processing/payments-processing.md @@ -195,7 +195,7 @@ If `value` attached is too small transaction can get aborted with error `cskip_n It can be unclear that to get more information on transaction user must scan blockchain through [getTransactions](https://toncenter.com/api/v2/#/transactions/get_transactions_getTransactions_get) function. It is impossible to retrieve the transaction ID immediately after sending a message, as the transaction must first be confirmed by the blockchain network. -To understand required pipeline read [Send payments](v3/guidelines/dapps/asset-processing/payments-processing/#send-payments) carefully, especially 7th point. +To understand required pipeline read [Send payments](/v3/guidelines/dapps/asset-processing/payments-processing/#send-payments) carefully, especially 7th point. ## Invoice-based approach To accept payments based on attached comments, the service should @@ -331,7 +331,7 @@ if __name__ == "__main__": ### Wallet Creation for Different Shards -When under heavy load, the TON blockchain may split into [shards](/v3/documentation/smart-contracts/shards). A simple analogy for a shard in the Web3 world would be a network segment. +When under heavy load, the TON blockchain may split into [shards](/v3/documentation/smart-contracts/shards/shards-intro). A simple analogy for a shard in the Web3 world would be a network segment. Just as we distribute service infrastructure in the Web2 world to be as close as possible to the end user, in TON, we can deploy contracts to be in the same shard as the user's wallet or any other contract that interacts with it. diff --git a/docs/v3/guidelines/dapps/cookbook.mdx b/docs/v3/guidelines/dapps/cookbook.mdx index 6d93ef28b9..01a62884d3 100644 --- a/docs/v3/guidelines/dapps/cookbook.mdx +++ b/docs/v3/guidelines/dapps/cookbook.mdx @@ -690,7 +690,7 @@ def calculate_jetton_address( return jetton_address ``` -Read the entire example [here](/static/example-code-snippets/pythoniq/jetton-offline-address-calc-wrapper.py). +Read the entire example [here](/example-code-snippets/pythoniq/jetton-offline-address-calc-wrapper.py). diff --git a/docs/v3/guidelines/dapps/tma/tutorials/step-by-step-guide.mdx b/docs/v3/guidelines/dapps/tma/tutorials/step-by-step-guide.mdx index c216eefaca..3168ce2cd2 100644 --- a/docs/v3/guidelines/dapps/tma/tutorials/step-by-step-guide.mdx +++ b/docs/v3/guidelines/dapps/tma/tutorials/step-by-step-guide.mdx @@ -19,7 +19,7 @@ Expires: 0 ``` ::: -2. Once the script is connected, a **[window.Telegram.WebApp](https://core.telegram.org/bots/webapps#initializing-web-apps)** object becomes available. You can read more about creating Mini App utilizing [`telegram-web-app.js`](v3/guidelines/dapps/tma/tutorials/app-examples#basic-twa-example) here. +2. Once the script is connected, a **[window.Telegram.WebApp](https://core.telegram.org/bots/webapps#initializing-web-apps)** object becomes available. You can read more about creating Mini App utilizing [`telegram-web-app.js`](/v3/guidelines/dapps/tma/tutorials/app-examples#basic-twa-example) here. 3. The modern way to connect SDK is an NPM package for Telegram Mini Apps SDK: @@ -27,7 +27,7 @@ Expires: 0 npm i @twa-dev/sdk ``` -You can find a guide for [`@twa-dev/sdk`](v3/guidelines/dapps/tma/tutorials/app-examples#modern-twa-example ) here. +You can find a guide for [`@twa-dev/sdk`](/v3/guidelines/dapps/tma/tutorials/app-examples#modern-twa-example ) here. 5. When your Mini App is ready and deployed to the web server, follow to the next step. diff --git a/docs/v3/guidelines/dapps/tutorials/web3-game-example.md b/docs/v3/guidelines/dapps/tutorials/web3-game-example.md index ec69e11da3..1ea0a1c677 100644 --- a/docs/v3/guidelines/dapps/tutorials/web3-game-example.md +++ b/docs/v3/guidelines/dapps/tutorials/web3-game-example.md @@ -6,7 +6,7 @@ In this tutorial we will consider how to add the TON blockchain to a game. For o ![Flappy Bird game without GameFi features](/img/tutorials/gamefi-flappy/no-gamefi-yet.png) We are going to implement the following: -- Achievements. Let’s reward our users with [SBTs](v3/concepts/glossary#sbt). The achievement system is a great tool to increase user engagement. +- Achievements. Let’s reward our users with [SBTs](/v3/concepts/glossary#sbt). The achievement system is a great tool to increase user engagement. - Game currency. In TON blockchain it’s easy to launch your own token (jetton). The token can be used to create an in-game economy. Our users will be able to earn the game coins to spend them later. - Game shop. We will provide users with the possibility to purchase in-game items using either in-game currency or the TON coin itself. @@ -116,7 +116,7 @@ const gameFi = await GameFi.create({ ``` > To learn more about initialization options please read the [library documentation](https://github.com/ton-org/game-engines-sdk). -> To learn what `tonconnect-manifest.json` is please check ton-connect [manifest description](v3/guidelines/ton-connect/guidelines/creating-manifest). +> To learn what `tonconnect-manifest.json` is please check ton-connect [manifest description](/v3/guidelines/ton-connect/guidelines/creating-manifest). Now we are ready to create a wallet connect button. Let’s create a UI scene in Phaser which will contain the connect button: ```typescript diff --git a/docs/v3/guidelines/dapps/tutorials/zero-knowledge-proofs.md b/docs/v3/guidelines/dapps/tutorials/zero-knowledge-proofs.md index e0bc06b038..e8e045b594 100644 --- a/docs/v3/guidelines/dapps/tutorials/zero-knowledge-proofs.md +++ b/docs/v3/guidelines/dapps/tutorials/zero-knowledge-proofs.md @@ -241,7 +241,7 @@ slice bls_g1_multiexp( ) asm "BLS_G1_MULTIEXP"; int bls_pairing(slice x1, slice y1, slice x2, slice y2, slice x3, slice y3, slice x4, slice y4, int n) asm "BLS_PAIRING"; ``` -The above lines are the new [TVM opcodes](v3/documentation/tvm/changelog/tvm-upgrade-2023-07#bls12-381) (BLS12-381) that allow pairing checks to be conducted on the TON Blockchain. +The above lines are the new [TVM opcodes](/v3/documentation/tvm/changelog/tvm-upgrade-2023-07#bls12-381) (BLS12-381) that allow pairing checks to be conducted on the TON Blockchain. The load_data and save_data functions are simply used to load and save the proof verification results (only for test purposes). diff --git a/docs/v3/guidelines/get-started-with-ton.mdx b/docs/v3/guidelines/get-started-with-ton.mdx index 777e663a46..2d4c3c2ea6 100644 --- a/docs/v3/guidelines/get-started-with-ton.mdx +++ b/docs/v3/guidelines/get-started-with-ton.mdx @@ -40,12 +40,6 @@ Our goal for today is to mine an NFT! This achievement will stay with you *forev Finally, you are able to mine this NFT achievement even in mainnet. (_it costs only 0,05 TON!_). -### Video tutorial - -Check out this awesome video tutorial created by a member of the TON developer community! With this helpful guide, you can complete the tutorial with ease: - - - ### Mining on TON Blockchain Today, we are going to teach our prospective builders how to mine on TON Blockchain. This experience will allow all of you to understand the significance of mining and why Bitcoin mining helped revolutionize the industry. @@ -55,7 +49,7 @@ Although the PoW Giver smart contract framework, which defined the initial minin * [Dive deeper into our economic model and mining on TON](https://ton.org/mining) -Now, let’s focus on the first steps to becoming a **TVM Developer** and learn how to mine an NFT on TON! Below is an example of what we're aiming to create. +Now, let’s focus on the first steps to becoming a **TON Developer** and learn how to mine an NFT on TON! Below is an example of what we're aiming to create.