### Jetton Test Setup Example Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Sets up the testing environment for Jetton contracts. Compiles JettonWallet and JettonMinter, sets up the blockchain, creates accounts, and deploys the JettonMinter. ```typescript import { Blockchain, SandboxContract, TreasuryContract } from "@ton/sandbox"; import { Cell, toNano } from "@ton/core"; import { compile } from "@ton/blueprint"; import { JettonMinter } from "../wrappers/JettonMinter"; import { JettonWallet } from "../wrappers/JettonWallet"; import "@ton/test-utils"; describe("Jetton", () => { let walletCode: Cell; let minterCode: Cell; let blockchain: Blockchain; let deployer: SandboxContract; let notDeployer: SandboxContract; let jettonMinter: SandboxContract; let defaultContent: Cell; beforeAll(async () => { // Compile contracts using Blueprint // Looks for JettonWallet.compile.ts and JettonMinter.compile.ts walletCode = await compile("JettonWallet"); minterCode = await compile("JettonMinter"); // Setup blockchain (TVM 12 is activated by default in latest sandbox) blockchain = await Blockchain.create(); // Create test accounts deployer = await blockchain.treasury("deployer"); notDeployer = await blockchain.treasury("notDeployer"); // Prepare content defaultContent = jettonContentToCell({ type: 1, uri: "https://testjetton.org/content.json", }); // Deploy minter jettonMinter = blockchain.openContract( JettonMinter.createFromConfig( { admin: deployer.address, content: defaultContent, wallet_code: jwallet_code, }, minter_code ) ); }); afterAll(() => { GAS_LOG.saveCurrentRunAfterAll(); }); // Helper function to get wallet address const userWallet = async (address: Address) => blockchain.openContract( JettonWallet.createFromAddress( await jettonMinter.getWalletAddress(address) ) ); // Tests... }); ``` -------------------------------- ### Example: Load Opcode from Slice Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Shows how to read a 32-bit signed integer from a slice, typically used to get an opcode or similar identifier. ```tolk var opcode = cs.loadInt(32); ``` -------------------------------- ### Full Example: Lazy Loading in Message Handler Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md A comprehensive example demonstrating lazy loading of messages and storage within an internal message handler, optimizing gas by loading data on demand. ```tolk fun onInternalMessage(in: InMessage) { val msg = lazy AllowedMessageToWallet.fromSlice(in.body); match (msg) { InternalTransferStep => { var storage = lazy WalletStorage.load(); // Not loaded yet if (in.senderAddress != storage.minterAddress) { // minterAddress loaded here // Validation logic } storage.jettonBalance += msg.jettonAmount; // jettonBalance loaded here storage.save(); } AskToTransfer => { var storage = lazy WalletStorage.load(); // Storage loaded on first access assert (in.senderAddress == storage.ownerAddress) throw ERR_NOT_FROM_OWNER; } } } ``` -------------------------------- ### Begin Cell Builder Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Initializes a new, empty builder object. Use this to start constructing a cell. ```tolk @pure fun beginCell(): builder ``` -------------------------------- ### Example: Get and Remove Signature Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Illustrates using `getLastBits` to extract a signature of a fixed size and `removeLastBits` to process the remaining data from a slice, common in message verification. ```tolk var signature = inMsgBody.getLastBits(SIZE_SIGNATURE); var signedSlice = inMsgBody.removeLastBits(SIZE_SIGNATURE); ``` -------------------------------- ### Comparison Operators Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Demonstrates the use of comparison operators for equality, inequality, and ordering. Includes examples for asserting conditions. ```tolk a == b // Equal a != b // Not equal a < b // Less than a > b // Greater than a <= b // Less than or equal a >= b // Greater than or equal ``` ```tolk assert (storage.jettonBalance >= msg.jettonAmount) throw ERR_NOT_ENOUGH_BALANCE; assert (msg.transferRecipient.getWorkchain() == BASECHAIN) throw ERR_WRONG_WORKCHAIN; ``` -------------------------------- ### Example: Load Jetton Amount Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Demonstrates loading a serialized nanotoncoins value from a slice, as might be done when processing jetton transfers. ```tolk var jettonAmount = cs.loadCoins(); ``` -------------------------------- ### Example: Load Amount from Slice Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Illustrates reading a 64-bit unsigned integer from a slice, commonly used for amounts or quantities. ```tolk var amount = cs.loadUint(64); ``` -------------------------------- ### Tolk Compilation and Testing Setup Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/00-tolk-overview.md Shows how to compile Tolk code using '@ton/tolk-js' and set up a testing environment with '@ton/sandbox'. ```javascript # Compilation (via @ton/tolk-js) import { compileTolk } from '@ton/tolk-js'; const result = await compileTolk({ file: 'contract.tolk' }); # Testing (via @ton/sandbox) import { Blockchain } from '@ton/sandbox'; const blockchain = await Blockchain.create(); const contract = blockchain.openContract(...); ``` -------------------------------- ### Example: Build and Parse Cell Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Demonstrates how to use `beginCell` to create a builder, store data (an unsigned integer and an address), and then finalize it into a cell using `endCell`. ```tolk var cell = beginCell() .storeUint(0x12345678, 32) .storeAddress(addr) .endCell(); ``` -------------------------------- ### Documentation Comments in Tolk Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Documentation comments, starting with ///, are used to generate documentation for functions, types, and other code elements. They support markdown and can include examples. ```tolk /// Loads a signed len-bit integer from a slice. /// Example: /// ``` /// var opcode = cs.loadInt(32); /// ``` @pure fun slice.loadInt(mutate self, len: int): int builtin ``` -------------------------------- ### Arithmetic Operators Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Provides examples of basic arithmetic operations including addition, subtraction, multiplication, division, modulo, and negation. ```tolk var sum = a + b; var diff = a - b; var product = a * b; var quotient = a / b; var remainder = a % b; var negation = -a; ``` -------------------------------- ### Project Setup and Compilation Config Source: https://context7.com/ilya-aksakov/ton-tolk-llm-docs/llms.txt Configure TON blueprint compiler settings for TLK language. Use withSrcLineComments and withStackComments for enhanced debugging information. ```typescript // wrappers/JettonWallet.compile.ts import { CompilerConfig } from "@ton/blueprint"; export const compile: CompilerConfig = { lang: "tolk", entrypoint: "jetton-wallet.tolk", withSrcLineComments: true, withStackComments: true, }; ``` -------------------------------- ### Tolk Language Syntax Example Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/00-tolk-overview.md Demonstrates basic Tolk syntax including version declaration, imports, struct definition, message handling with pattern matching, and a getter function. ```tolk tolk 1.2 import "@stdlib/gas-payments" import "errors" struct MinterStorage { totalSupply: coins adminAddress: address content: cell } fun onInternalMessage(in: InMessage) { val msg = lazy AllowedMessage.fromSlice(in.body); match (msg) { MintRequest => { /* handle */ } else => throw 0xFFFF } } get fun get_total_supply(): coins { val storage = lazy MinterStorage.load(); return storage.totalSupply; } ``` -------------------------------- ### Example: Assert Slice Consumption Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Shows how to use `assertEnd` to verify that all data within a slice has been processed, which is crucial for ensuring data integrity. ```tolk cs.assertEnd(); // Ensure all data consumed ``` -------------------------------- ### Compile Contracts Once with beforeAll Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Use `beforeAll` to perform expensive setup operations like contract compilation once before all tests in a suite. ```typescript import { compile } from "@ton/blueprint"; beforeAll(async () => { // Compile contracts once contractCode = await compile("MyContract"); // Setup blockchain once blockchain = await Blockchain.create(); }); ``` -------------------------------- ### Minimal Tolk Contract Example Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/00-tolk-overview.md A basic Tolk contract demonstrating storage loading, saving, incrementing a counter on internal messages, and a getter method. ```tolk tolk 1.2 struct Storage { counter: int } fun Storage.load() { return Storage.fromCell(contract.getData()) } fun Storage.save(self) { contract.setData(self.toCell()) } fun onInternalMessage(in: InMessage) { var storage = Storage.load(); storage.counter += 1; storage.save(); } get fun get_counter(): int { val storage = Storage.load(); return storage.counter; } ``` -------------------------------- ### Example: Parsing Exotic Cell Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Demonstrates how to parse an exotic cell after transforming it into a slice using `beginParseSpecial`. It shows how to load the cell type and handle different exotic cell types. ```tolk var (s, isExotic) = c.beginParseSpecial(); if (isExotic) { val cellType = s.loadInt(8) as ExoticCellType; match (cellType) { ExoticCellType.LibraryReference => { ... } ExoticCellType.MerkleProof => { ... } } } ``` -------------------------------- ### Test Jetton Wallet Get Methods Source: https://context7.com/ilya-aksakov/ton-tolk-llm-docs/llms.txt Tests the `get_wallet_data` method to ensure it returns correct jetton balance, owner address, and minter address. ```typescript it("get_wallet_data returns correct fields", async () => { const data = await jettonWallet.getWalletData(); expect(data.jettonBalance).toEqual(expectedBalance); expect(data.ownerAddress).toEqualAddress(owner); expect(data.minterAddress).toEqualAddress(minter); }); ``` -------------------------------- ### Test Wallet Contract Get Methods Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Verifies that the various getter methods of a wallet contract return the expected values. ```typescript it("wallet-v5 get methods should work", async () => { expect(await walletV5.getSeqno()).toBe(0); expect(await walletV5.getSubwalletId()).toBe(WALLET_ID.serialized); expect(await walletV5.getPublicKey()).toBe(bufferToBigInt(keypair.publicKey)); expect(await walletV5.getIsSignatureAllowed()).toBe(true); const extensions = await walletV5.getExtensions(); expect(extensions.isEmpty()).toBe(true); }); ``` -------------------------------- ### Basic Test Structure for MyContract Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Sets up a basic testing structure for a smart contract using @ton/sandbox and @ton/blueprint. Includes blockchain creation, test account setup, contract compilation, and deployment for each test. ```typescript import { Blockchain, SandboxContract, TreasuryContract, internal, SendMessageResult, } from "@ton/sandbox"; import { Cell, toNano, beginCell, Address } from "@ton/core"; import { compile } from "@ton/blueprint"; import { MyContract } from "../wrappers/MyContract"; import "@ton/test-utils"; describe("MyContract", () => { let blockchain: Blockchain; let deployer: SandboxContract; let contract: SandboxContract; let contractCode: Cell; beforeAll(async () => { // Compile contract using Blueprint // Looks for myContract.compile.ts in the same directory as the wrapper contractCode = await compile("MyContract"); // Create blockchain blockchain = await Blockchain.create(); // Create test accounts deployer = await blockchain.treasury("deployer"); }); beforeEach(async () => { // Deploy fresh contract for each test contract = blockchain.openContract( MyContract.createFromConfig( { /* config */ }, contractCode ) ); await contract.sendDeploy(deployer.getSender(), toNano("0.05")); }); it("should work", async () => { // Test implementation }); }); ``` -------------------------------- ### Setup Gas Logger for Contract Tests Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Initializes and configures the GasLogAndSave utility for tracking gas consumption during contract testing. Remember contract BOC sizes before tests. ```typescript import { GasLogAndSave } from "../gas-logger"; describe("MyContract", () => { let GAS_LOG = new GasLogAndSave("01_project"); beforeAll(async () => { // Compile and setup... // Remember contract sizes GAS_LOG.rememberBocSize("minter", minterCode); GAS_LOG.rememberBocSize("wallet", walletCode); }); afterAll(() => { // Save all gas logs GAS_LOG.saveCurrentRunAfterAll(); }); // Tests... }); ``` -------------------------------- ### Example: Check Remaining Bits Count Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Demonstrates using `remainingBitsCount` to assert that a slice contains a specific number of bits before proceeding, preventing errors with malformed payloads. ```tolk assert (msg.forwardPayload.remainingBitsCount()) throw ERR_INVALID_PAYLOAD; ``` -------------------------------- ### Test Basic Get Method for Wallet Data Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Demonstrates how to call a 'getWalletData' method on a Jetton Wallet contract and asserts the correctness of the returned jetton balance, owner address, and minter address. ```typescript it("should return correct wallet data", async () => { const data = await jettonWallet.getWalletData(); expect(data.jettonBalance).toEqual(expectedBalance); expect(data.ownerAddress).toEqualAddress(owner); expect(data.minterAddress).toEqualAddress(minter); }); ``` -------------------------------- ### Define Helper Functions for Reusability Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Create reusable helper functions to abstract common operations like minting jettons or getting user wallets. ```typescript async function mintJettons(to: Address, amount: bigint) { return await jettonMinter.sendMint( deployer.getSender(), to, amount, toNano("0.05"), toNano("1") ); } async function getUserWallet(owner: Address) { return blockchain.openContract( JettonWallet.createFromAddress(await jettonMinter.getWalletAddress(owner)) ); } ``` -------------------------------- ### Create Empty Typed Map Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Initialize an empty map with specific key and value types using `createEmptyMap`. This function is equivalent to `PUSHNULL` and is useful for starting map constructions. ```tolk @pure fun createEmptyMap(): map ``` ```tolk var extensions: map = createEmptyMap(); ``` -------------------------------- ### Function Returning Multiple Values Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md A function can return a tuple of values. The usage example shows how to destructure the returned tuple into separate variables. ```tolk fun address.getWorkchainAndHash(self): (int8, uint256) // Usage: var (workchain, hash) = myAddress.getWorkchainAndHash(); ``` -------------------------------- ### Single-Line Comments in Tolk Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Single-line comments start with // and are useful for brief explanations or inline notes. They extend to the end of the line. ```tolk // This is a single-line comment var balance = 100; // Balance in nanotons ``` -------------------------------- ### Get Current Block Logical Time with blockchain.currentBlockLogicalTime() Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the starting logical time of the current block. Useful for block-scoped operations. ```tolk @pure fun blockchain.currentBlockLogicalTime(): int ``` -------------------------------- ### Get Original Contract Balance with contract.getOriginalBalance() Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the balance in nanotoncoins at the start of the Computation Phase. Useful for calculating fees or tracking balance changes. ```tolk @pure fun contract.getOriginalBalance(): coins ``` ```tolk var tonBalanceBeforeMsg = contract.getOriginalBalance() - msgValue; var storageFee = MIN_TONS_FOR_STORAGE - min(tonBalanceBeforeMsg, MIN_TONS_FOR_STORAGE); ``` -------------------------------- ### Validation Chain Example Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/03-patterns-and-practices.md Demonstrates a validation chain for processing an 'AskToTransfer' message. It includes checks for payload format, workchain, storage, authorization, balance, and attached TON, throwing specific errors for each failed validation. ```tolk AskToTransfer => { // 1. Validate payload format assert (msg.forwardPayload.remainingBitsCount()) throw ERR_INVALID_PAYLOAD; // 2. Validate workchain assert (msg.transferRecipient.getWorkchain() == BASECHAIN) throw ERR_WRONG_WORKCHAIN; // 3. Load and validate storage var storage = lazy WalletStorage.load(); // 4. Validate authorization assert (in.senderAddress == storage.ownerAddress) throw ERR_NOT_FROM_OWNER; // 5. Validate balance assert (storage.jettonBalance >= msg.jettonAmount) throw ERR_NOT_ENOUGH_BALANCE; // 6. Validate attached TON var forwardedMessagesCount = msg.forwardTonAmount ? 2 : 1; assert (in.valueCoins > msg.forwardTonAmount + forwardedMessagesCount * in.originalForwardFee + (2 * JETTON_WALLET_GAS_CONSUMPTION + MIN_TONS_FOR_STORAGE) ) throw ERR_NOT_ENOUGH_TON; // All validations passed - process transfer processTransfer(msg, storage); } ``` -------------------------------- ### Prefix Dictionary Get Operation Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Retrieves a value from the dictionary using a key prefix. It returns the full key, the value, and a boolean indicating if a match was found. ```tolk @pure fun dict.prefixDictGet(self, keyLen: int, key: slice): (slice, slice?, slice?, bool) ``` -------------------------------- ### Map in Storage Pattern for Extensions Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/03-patterns-and-practices.md Defines a storage structure that uses a map to store enabled extensions, keyed by address hash. Provides examples for checking, adding, and removing extensions. ```tolk // From wallet-v5 struct Storage { isSignatureAllowed: bool seqno: uint32 subwalletId: uint32 publicKey: uint256 extensions: map // Address hash -> enabled } ``` -------------------------------- ### Get Middle Bits of Slice Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Extracts a slice containing `len` bits starting from the specified `offset` within the current slice, without modifying the original slice. ```tolk @pure fun slice.getMiddleBits(self, offset: int, len: int): slice ``` -------------------------------- ### Combined Dictionary Operations Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Functions for setting and getting previous values, or deleting and getting values from dictionaries. ```APIDOC ## Combined Operations ### `dict.iDictSetAndGet` Sets value and returns previous value for integer keys. #### Signature ```tolk @pure fun dict.iDictSetAndGet(mutate self, keyLen: int, key: int, value: slice): (slice?, bool) ``` ### `dict.uDictSetAndGet` Sets value and returns previous value for unsigned integer keys. #### Signature ```tolk fun dict.uDictSetAndGet(mutate self, keyLen: int, key: int, value: slice): (slice?, bool) ``` ### `dict.sDictSetAndGet` Sets value and returns previous value for slice keys. #### Signature ```tolk fun dict.sDictSetAndGet(mutate self, keyLen: int, key: slice, value: slice): (slice?, bool) ``` ### `dict.iDictDeleteAndGet` Deletes and returns the previous value for integer keys. #### Signature ```tolk fun dict.iDictDeleteAndGet(mutate self, keyLen: int, key: int): (slice?, bool) ``` ### `dict.uDictDeleteAndGet` Deletes and returns the previous value for unsigned integer keys. #### Signature ```tolk fun dict.uDictDeleteAndGet(mutate self, keyLen: int, key: int): (slice?, bool) ``` ### `dict.sDictDeleteAndGet` Deletes and returns the previous value for slice keys. #### Signature ```tolk fun dict.sDictDeleteAndGet(mutate self, keyLen: int, key: slice): (slice?, bool) ``` ``` -------------------------------- ### Get Method for External Queries Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Get methods are read-only functions accessible for external queries. They typically load data from storage and return it in a structured format. ```tolk get fun get_wallet_data(): JettonWalletDataReply { val storage = lazy WalletStorage.load(); return { jettonBalance: storage.jettonBalance, ownerAddress: storage.ownerAddress, minterAddress: storage.minterAddress, jettonWalletCode: contract.getCode(), } } ``` ```tolk get fun is_signature_allowed(): bool { val storage = lazy Storage.load(); return storage.isSignatureAllowed; } ``` ```tolk get fun seqno(): int { val storage = lazy Storage.load(); return storage.seqno; } ``` ```tolk get fun get_subwallet_id(): int { val storage = lazy Storage.load(); return storage.subwalletId; } ``` ```tolk get fun get_public_key(): int { val storage = lazy Storage.load(); return storage.publicKey; } ``` ```tolk get fun get_extensions(): map { val storage = lazy Storage.load(); return storage.extensions; } ``` -------------------------------- ### blockchain.currentBlockLogicalTime Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the starting logical time of the current block. This is a pure function. ```APIDOC ## blockchain.currentBlockLogicalTime ### Description Returns the starting logical time of the current block. ### Signature ```tolk @pure fun blockchain.currentBlockLogicalTime(): int ``` ``` -------------------------------- ### Dictionary Set and Get Operations Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md These functions set a value for a given key and return the previous value associated with that key. They are available for integer and slice keys, with variants for different key/value types. ```tolk @pure fun dict.iDictSetAndGet(mutate self, keyLen: int, key: int, value: slice): (slice?, bool) fun dict.uDictSetAndGet(mutate self, keyLen: int, key: int, value: slice): (slice?, bool) fun dict.sDictSetAndGet(mutate self, keyLen: int, key: slice, value: slice): (slice?, bool) ``` -------------------------------- ### Tolk Project Structure Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/00-tolk-overview.md Illustrates a typical project directory structure for a Tolk smart contract, showing common file types and their purposes. ```bash project/ ├── contract.tolk # Main contract (entrypoint) ├── storage.tolk # Storage structures ├── messages.tolk # Message definitions ├── errors.tolk # Error constants └── utils.tolk # Helper functions ``` -------------------------------- ### contract.getOriginalBalance Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the balance in nanotoncoins at the start of the Computation Phase. This is a pure function. ```APIDOC ## contract.getOriginalBalance ### Description Returns the balance in nanotoncoins at the start of Computation Phase. ### Signature ```tolk @pure fun contract.getOriginalBalance(): coins ``` ### Example ```tolk var tonBalanceBeforeMsg = contract.getOriginalBalance() - msgValue; var storageFee = MIN_TONS_FOR_STORAGE - min(tonBalanceBeforeMsg, MIN_TONS_FOR_STORAGE); ``` ``` -------------------------------- ### Get Remaining References Count Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the number of cell references currently remaining in the slice. ```tolk @pure fun slice.remainingRefsCount(self): int ``` -------------------------------- ### Get Remaining Bits Count Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the number of data bits currently remaining in the slice. ```tolk @pure fun slice.remainingBitsCount(self): int ``` -------------------------------- ### Dictionary Operations - Get Ref Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Provides functions to retrieve values as cell references from TVM dictionaries. ```APIDOC ### Get Ref Operations #### `dict.iDictGetRef(self, keyLen: int, key: int): (cell?, bool)` Retrieves a value as a cell reference using a signed integer key. Returns `(cell, true)` if found, `(null, false)` otherwise. #### `dict.uDictGetRef(self, keyLen: int, key: int): (cell?, bool)` Retrieves a value as a cell reference using an unsigned integer key. Returns `(cell, true)` if found, `(null, false)` otherwise. #### `dict.sDictGetRef(self, keyLen: int, key: slice): (cell?, bool)` Retrieves a value as a cell reference using a slice key. Returns `(cell, true)` if found, `(null, false)` otherwise. #### `dict.iDictGetRefOrNull(self, keyLen: int, key: int): cell?` Retrieves a cell reference using a signed integer key, or returns `null` if not found. #### `dict.uDictGetRefOrNull(self, keyLen: int, key: int): cell?` Retrieves a cell reference using an unsigned integer key, or returns `null` if not found. #### `dict.sDictGetRefOrNull(self, keyLen: int, key: slice): cell?` Retrieves a cell reference using a slice key, or returns `null` if not found. ``` -------------------------------- ### Import Standard Library Modules Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Import modules from the standard library using the '@stdlib/' prefix. Note that 'common.tolk' is implicitly imported. ```Tolk import "@stdlib/gas-payments" import "@stdlib/tvm-dicts" import "@stdlib/lisp-lists" ``` -------------------------------- ### Dictionary Operations - Get Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Provides functions to retrieve values from TVM dictionaries based on key type. ```APIDOC ### Get Operations Three variants for different key types: - `iDict*` - Signed integer keys - `uDict*` - Unsigned integer keys - `sDict*` - Arbitrary slice keys #### `dict.iDictGet(self, keyLen: int, key: int): (slice?, bool)` Retrieves a value using a signed integer key. #### `dict.uDictGet(self, keyLen: int, key: int): (slice?, bool)` Retrieves a value using an unsigned integer key. #### `dict.sDictGet(self, keyLen: int, key: slice): (slice?, bool)` Retrieves a value using a slice key. **Parameters:** - `keyLen`: Key length in bits - `key`: The key to lookup **Returns**: `(value, found)` tuple **Example:** ```tolk var (value, found) = myDict.uDictGet(256, userHash); if (found) { var balance = value!.loadCoins(); } ``` ``` -------------------------------- ### Get References Count Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the total number of cell references currently stored within the builder. ```tolk @pure fun builder.refsCount(self): int ``` -------------------------------- ### Declare Tolk Version and Import Modules Source: https://context7.com/ilya-aksakov/ton-tolk-llm-docs/llms.txt Every Tolk file must begin with a version declaration. Standard library modules are prefixed with `@stdlib/`, and local files do not require a `.tolk` extension. ```tolk tolk 1.2 import "@stdlib/gas-payments" import "@stdlib/tvm-dicts" import "errors" import "storage" import "messages" ``` -------------------------------- ### Usage of Wallet Storage Load and Save Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/03-patterns-and-practices.md Demonstrates how to lazily load wallet storage, modify its balance, and then save the updated state back to the contract's c4 register. ```tolk // Load storage (lazy loading for gas optimization) var storage = lazy WalletStorage.load(); // Modify storage.jettonBalance += amount; // Save back to c4 storage.save(); ``` -------------------------------- ### Get Head of Lisp List Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the first element of a lisp-style list. This function assumes the list is not empty. ```tolk @pure fun listGetHead(list: tuple): X ``` -------------------------------- ### Get Data Bits Count Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the total number of data bits currently stored within the builder. ```tolk @pure fun builder.bitsCount(self): int ``` -------------------------------- ### Storage Pattern Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Demonstrates the pattern for loading, modifying, and saving storage variables using lazy loading. ```tolk // Storage pattern var storage = lazy Storage.load(); storage.field = newValue; storage.save(); ``` -------------------------------- ### Get Current Random Seed Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the current seed used for pseudo-random number generation. This is a pure function. ```tolk @pure fun random.getSeed(): uint256 ``` -------------------------------- ### Gas and Fee Calculation Functions Source: https://context7.com/ilya-aksakov/ton-tolk-llm-docs/llms.txt Import '@stdlib/gas-payments' for fee calculations. Use acceptExternalMessage for external messages and setGasLimitToMaximum to set gas limits. ```tolk import "@stdlib/gas-payments" // Accept gas charge for external message (required in onExternalMessage) fun onExternalMessage(inMsgBody: slice) { // ... validate ... acceptExternalMessage() setGasLimitToMaximum() // ... process ... } // Calculate nanoton cost for gas units consumed var fee = calculateGasFee(BASECHAIN, getGasConsumedAtTheMoment()) // Calculate storage fee for contract data var (cells, bits, refs, ok) = dataCell.calculateSize(1000) var dailyFee = calculateStorageFee(0, 86400, bits, cells) // Calculate forward fee for a message var msgSize = msgCell.calculateSizeStrict(1000) var fwdFee = calculateForwardFee(0, msgSize.1, msgSize.0) // Query outstanding storage debt var debt = contract.getStorageDuePayment() ``` -------------------------------- ### Get Declared Pack Prefix Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the compile-time serialization prefix of a struct. Use this to understand how a struct is encoded. ```tolk @pure fun T.getDeclaredPackPrefix(): int ``` ```tolk struct (0xF0) AssetRegular { ... } AssetRegular.getDeclaredPackPrefix() // Returns 240 ``` -------------------------------- ### Loading Nested Data from Storage Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/03-patterns-and-practices.md Shows how to load the main storage structure and then subsequently load the nested data stored in a reference cell. ```tolk var storage = MinterStorage.load(); var extra = storage.extraData.load(); // Load from ref ``` -------------------------------- ### Get Logical Time with blockchain.logicalTime() Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the logical time of the current transaction. This is distinct from the actual wall-clock time. ```tolk @pure fun blockchain.logicalTime(): int ``` -------------------------------- ### Calculate Days and Hours Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Divides total hours by 24 to get the number of full days and remaining hours. ```tolk var (days, hours) = divMod(totalHours, 24); ``` -------------------------------- ### Parse and Manipulate Addresses in Tolk Source: https://context7.com/ilya-aksakov/ton-tolk-llm-docs/llms.txt Demonstrates compile-time address parsing, workchain extraction, and building addresses from components. Ensure addresses are valid and correctly formatted for TON interactions. ```tolk // Compile-time address parsing val ADMIN = address("EQCRDM9h4k3UJdOePPuyX40mCgA4vxge5Dc5vjBR8djbEKC5") ``` ```tolk // Workchain extraction assert (msg.transferRecipient.getWorkchain() == BASECHAIN) throw ERR_WRONG_WORKCHAIN ``` ```tolk var (senderWc, senderHash) = in.senderAddress.getWorkchainAndHash() ``` ```tolk // Build address from parts var addr = address.fromWorkchainAndHash(0, computedHash) ``` -------------------------------- ### Basic Function Syntax Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Defines a function with parameters and a return type. Ensure all parameters and the return type are correctly specified. ```tolk fun functionName(param1: Type1, param2: Type2): ReturnType { // function body return result; } ``` -------------------------------- ### Get Cell Depth of Level Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the i-th depth of a cell, which is relevant for Merkle structures. Requires the level as input. ```tolk @pure fun cell.depthOfLevel(self, level: int): int ``` -------------------------------- ### Get Cell Hash of Level Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the i-th hash of a cell, which is relevant for Merkle structures. Requires the level as input. ```tolk @pure fun cell.hashOfLevel(self, level: int): uint256 ``` -------------------------------- ### TON Jetton Test Scaffolding with Sandbox Source: https://context7.com/ilya-aksakov/ton-tolk-llm-docs/llms.txt Sets up the testing environment for Jetton contracts using `@ton/sandbox`. It compiles contract code, deploys treasury contracts, and initializes the JettonMinter contract. ```typescript import { Blockchain, SandboxContract, TreasuryContract } from "@ton/sandbox"; import { Cell, toNano } from "@ton/core"; import { compile } from "@ton/blueprint"; import { JettonMinter } from "../wrappers/JettonMinter"; import { JettonWallet } from "../wrappers/JettonWallet"; import "@ton/test-utils"; describe("Jetton", () => { let walletCode: Cell; let minterCode: Cell; let blockchain: Blockchain; let deployer: SandboxContract; let notDeployer: SandboxContract; let jettonMinter: SandboxContract; beforeAll(async () => { walletCode = await compile("JettonWallet"); minterCode = await compile("JettonMinter"); blockchain = await Blockchain.create(); deployer = await blockchain.treasury("deployer"); notDeployer = await blockchain.treasury("notDeployer"); jettonMinter = blockchain.openContract( JettonMinter.createFromConfig( { admin: deployer.address, content: defaultContent, wallet_code: walletCode }, minterCode ) ); await jettonMinter.sendDeploy(deployer.getSender(), toNano("100")); }); const userWallet = async (address: Address) => blockchain.openContract( JettonWallet.createFromAddress( await jettonMinter.getWalletAddress(address) ) ); }); ``` -------------------------------- ### Get Contract Code with contract.getCode() Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Retrieves the code of the smart contract from c7. This is useful for introspection or dynamic code loading. ```tolk @pure fun contract.getCode(): cell ``` -------------------------------- ### Create Structure Instances Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Structure instances can be created using named fields for clarity or shorthand when variable names match field names. ```tolk // Named fields (recommended) var storage: WalletStorage = { jettonBalance: 0, ownerAddress: owner, minterAddress: minter, }; // Shorthand when variable names match field names val emptyWalletStorage: WalletStorage = { jettonBalance: 0, ownerAddress, minterAddress, }; ``` -------------------------------- ### Implement Loops with do-while Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Execute a code block at least once, and then repeatedly as long as a specified condition remains true. ```tolk do { // code } while (condition); ``` -------------------------------- ### Assembly Stack Manipulation Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Demonstrates various stack manipulation syntaxes within TVM assembly, including reordering and loading references. ```tolk asm(c self) "STREF" // Reorder: c, self -> self with c stored ``` ```tolk asm( -> 1 0) "LDREF" // Return order: stack positions ``` ```tolk asm(-> 0 2 1 3) "DICTIREMMIN" // Complex reordering ``` -------------------------------- ### Create Empty Cell Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Creates an empty cell with no bits or references. This is equivalent to starting a new builder and immediately ending it. ```tolk @pure fun createEmptyCell(): cell ``` -------------------------------- ### Implement Loops with while Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md Execute a code block repeatedly as long as a specified condition remains true. Ensure the condition eventually becomes false to avoid infinite loops. ```tolk while (condition) { // code } ``` ```tolk while (true) { val action = lazy ExtraAction.fromSlice(extraActions); match (action) { AddExtensionExtraAction => { ... } RemoveExtensionExtraAction => { ... } SetSignatureAllowedExtraAction => { ... } else => throw ERROR_UNSUPPORTED_ACTION } if (!extraActions.hasNext()) { return; } extraActions = extraActions.getNext(); } ``` -------------------------------- ### Message Handling Pattern Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Illustrates the pattern for handling incoming messages by lazily loading and matching message types. ```tolk // Message handling pattern val msg = lazy AllowedMessage.fromSlice(in.body); match (msg) { MessageType1 => { ... } MessageType2 => { ... } } ``` -------------------------------- ### Basic Wallet Storage Structure and Methods Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/03-patterns-and-practices.md Defines a basic storage structure for a wallet and provides methods to load from and save to the contract's data register (c4). Use lazy loading for gas optimization. ```tolk // storage.tolk struct WalletStorage { jettonBalance: coins ownerAddress: address minterAddress: address } fun WalletStorage.load() { return WalletStorage.fromCell(contract.getData()) } fun WalletStorage.save(self) { contract.setData(self.toCell()) } ``` -------------------------------- ### Get Tail of Lisp List Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the rest of a lisp-style list (all elements except the first). Returns null if the list is empty. ```tolk @pure fun listGetTail(list: tuple): tuple? ``` -------------------------------- ### Testing a Contract with @ton/sandbox Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/README.md Sets up a blockchain environment and deploys a contract for testing. Includes tests for deposits, owner withdrawals, and non-owner withdrawal failures. ```typescript import { Blockchain, SandboxContract, TreasuryContract } from "@ton/sandbox"; import { Cell, toNano } from "@ton/core"; import { compile } from "@ton/blueprint"; import { MyContract } from "../wrappers/MyContract"; import "@ton/test-utils"; describe("MyContract", () => { let blockchain: Blockchain; let deployer: SandboxContract; let contract: SandboxContract; beforeAll(async () => { const code = await compile("contractName"); blockchain = await Blockchain.create(); deployer = await blockchain.treasury("deployer"); contract = blockchain.openContract( MyContract.createFromConfig({ owner: deployer.address }, code) ); await contract.sendDeploy(deployer.getSender(), toNano("0.05")); }); it("should accept deposits", async () => { const result = await contract.sendDeposit( deployer.getSender(), toNano("1") ); expect(result.transactions).toHaveTransaction({ from: deployer.address, to: contract.address, success: true, }); expect(await contract.getBalance()).toEqual(toNano("1")); }); it("owner can withdraw", async () => { const result = await contract.sendWithdraw( deployer.getSender(), toNano("0.5") ); expect(result.transactions).toHaveTransaction({ from: contract.address, to: deployer.address, success: true, }); expect(await contract.getBalance()).toEqual(toNano("0.5")); }); it("non-owner cannot withdraw", async () => { const other = await blockchain.treasury("other"); const result = await contract.sendWithdraw( other.getSender(), toNano("0.1") ); expect(result.transactions).toHaveTransaction({ from: other.address, to: contract.address, aborted: true, exitCode: ERR_NOT_OWNER, }); }); }); ``` -------------------------------- ### Map Operations Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Provides functions for interacting with map data structures, including checking for existence, getting, setting, and deleting elements. ```APIDOC ## map.exists ### Description Checks if a key exists in a map. ### Signature ```tolk @pure fun map.exists(self, key: K): bool ``` ### Example ```tolk if (!storage.extensions.exists(senderAddrHash)) { return; } ``` ``` ```APIDOC ## map.get ### Description Gets an element by key. Returns `MapLookupResult` with an `isFound` flag. ### Signature ```tolk @pure fun map.get(self, key: K): MapLookupResult ``` ### Example ```tolk val result = balances.get(userAddress); if (result.isFound) { var balance = result.loadValue(); } ``` ``` ```APIDOC ## map.mustGet ### Description Gets an element by key or throws an exception if not found. ### Signature ```tolk @pure fun map.mustGet(self, key: K, throwIfNotFound: int = 9): V ``` ``` ```APIDOC ## map.set ### Description Sets an element by key. Returns `self` for chaining. ### Signature ```tolk @pure fun map.set(mutate self, key: K, value: V): self ``` ### Example ```tolk balances.set(userAddress, newBalance); ``` ``` ```APIDOC ## map.setAndGetPrevious ### Description Sets an element by key and returns the previous value (or `isFound = false`). ### Signature ```tolk @pure fun map.setAndGetPrevious(mutate self, key: K, value: V): MapLookupResult ``` ``` ```APIDOC ## map.replaceIfExists ### Description Replaces an element only if the key already exists. Returns whether the replacement occurred. ### Signature ```tolk @pure fun map.replaceIfExists(mutate self, key: K, value: V): bool ``` ``` ```APIDOC ## map.addIfNotExists ### Description Adds an element only if the key does not exist. Returns whether the element was added. ### Signature ```tolk @pure fun map.addIfNotExists(mutate self, key: K, value: V): bool ``` ### Example ```tolk val inserted = storage.extensions.addIfNotExists(extensionAddrHash, true); assert (inserted) throw ERROR_ADD_EXTENSION; ``` ``` ```APIDOC ## map.delete ### Description Deletes an element by key. Returns whether the deletion occurred. ### Signature ```tolk @pure fun map.delete(mutate self, key: K): bool ``` ### Example ```tolk val removed = storage.extensions.delete(extensionAddrHash); assert (removed) throw ERROR_REMOVE_EXTENSION; ``` ``` ```APIDOC ## map.deleteAndGetDeleted ### Description Deletes an element by key and returns the deleted element. ### Signature ```tolk @pure fun map.deleteAndGetDeleted(mutate self, key: K): MapLookupResult ``` ``` -------------------------------- ### Get Remaining Bits and Refs Count Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns a tuple containing the number of data bits and cell references remaining in the slice. ```tolk @pure fun slice.remainingBitsAndRefsCount(self): (int, int) ``` -------------------------------- ### Get Contract Address with contract.getAddress() Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the internal address of the current smart contract. Used to retrieve the contract's own address. ```tolk @pure fun contract.getAddress(): address ``` ```tolk var myWorkchain = contract.getAddress().getWorkchain(); ``` -------------------------------- ### High-Precision Math Functions Source: https://context7.com/ilya-aksakov/ton-tolk-llm-docs/llms.txt Utilize math functions like `mulDivFloor` and `divMod` for high-precision calculations, avoiding overflow. Standard min/max/abs/sign functions are also available. ```tolk // mulDivFloor — floor(x * y / z) using 513-bit intermediate var proportionalFee = mulDivFloor(amount, feeNumerator, feeDenominator) // divMod — returns (quotient, remainder) var (days, hours) = divMod(totalHours, 24) // min / max / abs / sign var reserve = min(currentBalance, MIN_TONS_FOR_STORAGE) var (low, high) = minMax(price1, price2) ``` -------------------------------- ### State Init Pattern in Tolk Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/02-language-features.md The State Init pattern is used to define the initial state of a contract, including its code and data. This is crucial for contract deployment and address calculation. ```tolk fun calcDeployedJettonWallet(ownerAddress: address, minterAddress: address, jettonWalletCode: cell): AutoDeployAddress { val emptyWalletStorage: WalletStorage = { jettonBalance: 0, ownerAddress, minterAddress, }; return { stateInit: { code: jettonWalletCode, data: emptyWalletStorage.toCell() } } } // Calculate address: var walletAddr = calcDeployedJettonWallet(owner, minter, code).calculateAddress(); ``` -------------------------------- ### Get Contract Storage Due Payment Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Retrieves the amount of nanotoncoins a contract owes for storage. Returns 0 if there is no outstanding storage debt. ```tolk fun contract.getStorageDuePayment(): coins ``` -------------------------------- ### Test Admin Minting Jettons Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/04-testing-guide.md Verifies that an administrator can successfully mint new Jettons. Checks for transaction success, wallet deployment, excess return, and updated balances. ```typescript it("admin should be able to mint jettons", async () => { let initialTotalSupply = await jettonMinter.getTotalSupply(); const deployerJettonWallet = await userWallet(deployer.address); let initialJettonBalance = toNano("1000.23"); const mintResult = await jettonMinter.sendMint( deployer.getSender(), deployer.address, initialJettonBalance, toNano("0.05"), toNano("1") ); // Check wallet deployed expect(mintResult.transactions).toHaveTransaction({ from: jettonMinter.address, to: deployerJettonWallet.address, deploy: true, }); // Check excesses returned expect(mintResult.transactions).toHaveTransaction({ from: deployerJettonWallet.address, to: jettonMinter.address, }); // Check balance updated expect(await deployerJettonWallet.getJettonBalance()).toEqual( initialJettonBalance ); expect(await jettonMinter.getTotalSupply()).toEqual( initialTotalSupply + initialJettonBalance ); }); ``` -------------------------------- ### Get Declared Pack Prefix Length Source: https://github.com/ilya-aksakov/ton-tolk-llm-docs/blob/main/docs/01-stdlib-reference.md Returns the length in bits of a struct's serialization prefix. Useful for precise data manipulation. ```tolk @pure fun T.getDeclaredPackPrefixLen(): int ``` ```tolk AssetRegular.getDeclaredPackPrefixLen() // Returns 16 ```