├── .prettierignore ├── CHANGELOG.md ├── .gitignore ├── .prettierrc ├── wrappers ├── jetton-minter.compile.ts ├── jetton-wallet.compile.ts ├── jetton-wallet.ts └── jetton-minter.ts ├── jest.config.ts ├── tsconfig.json ├── contracts ├── utils │ ├── workchain.fc │ ├── op-codes.fc │ ├── jetton-utils.fc │ └── gas.fc ├── jetton-wallet.fc ├── jetton-minter.fc └── imports │ └── stdlib.fc ├── package.json ├── README.md ├── LICENSE ├── scripts ├── incrementSample.ts ├── jetton-helpers.ts └── deployMinter.ts └── tests └── Sample.spec.ts /.prettierignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Jan 21 2 | 3 | - Initial release 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | temp 3 | build 4 | dist 5 | .DS_Store 6 | .env -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120, 3 | "tabWidth": 4, 4 | "singleQuote": true, 5 | "bracketSpacing": true, 6 | "semi": true 7 | } 8 | -------------------------------------------------------------------------------- /wrappers/jetton-minter.compile.ts: -------------------------------------------------------------------------------- 1 | import { CompilerConfig } from '@ton/blueprint'; 2 | 3 | export const compile: CompilerConfig = { 4 | lang: 'func', 5 | targets: ['contracts/jetton-minter.fc'], 6 | }; 7 | -------------------------------------------------------------------------------- /wrappers/jetton-wallet.compile.ts: -------------------------------------------------------------------------------- 1 | import { CompilerConfig } from '@ton/blueprint'; 2 | 3 | export const compile: CompilerConfig = { 4 | lang: 'func', 5 | targets: ['contracts/jetton-wallet.fc'], 6 | }; 7 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | import type { Config } from 'jest'; 2 | 3 | const config: Config = { 4 | preset: 'ts-jest', 5 | testEnvironment: 'node', 6 | testPathIgnorePatterns: ['/node_modules/', '/dist/'], 7 | }; 8 | 9 | export default config; 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "outDir": "dist", 5 | "module": "commonjs", 6 | "declaration": true, 7 | "esModuleInterop": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "strict": true, 10 | "skipLibCheck": true 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /contracts/utils/workchain.fc: -------------------------------------------------------------------------------- 1 | #include "../imports/stdlib.fc"; 2 | #include "op-codes.fc"; 3 | 4 | const BASECHAIN = 0; 5 | 6 | const MY_WORKCHAIN = BASECHAIN; 7 | 8 | int is_same_workchain(slice addr) inline { 9 | (int wc, _) = parse_std_addr(addr); 10 | return wc == MY_WORKCHAIN; 11 | } 12 | 13 | () check_same_workchain(slice addr) impure inline { 14 | throw_unless(error::wrong_workchain, is_same_workchain(addr)); 15 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Sameple", 3 | "version": "0.0.1", 4 | "scripts": { 5 | "start": "blueprint run", 6 | "build": "blueprint build", 7 | "test": "jest --verbose" 8 | }, 9 | "devDependencies": { 10 | "@ton/core": "^0.53.0", 11 | "@ton/crypto": "^3.2.0", 12 | "@ton/sandbox": "^0.18.0", 13 | "@ton/test-utils": "^0.4.2", 14 | "@ton/ton": "^13.9.0", 15 | "@types/jest": "^29.5.0", 16 | "@types/node": "^20.2.5", 17 | "jest": "^29.5.0", 18 | "prettier": "^3.1.0", 19 | "ts-jest": "^29.0.5", 20 | "ts-node": "^10.9.1", 21 | "typescript": "^5.3.2" 22 | }, 23 | "dependencies": { 24 | "@aws-crypto/sha256-js": "^5.2.0", 25 | "@ton/blueprint": "^0.19.1" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sameple 2 | 3 | ## Project structure 4 | 5 | - `contracts` - source code of all the smart contracts of the project and their dependencies. 6 | - `wrappers` - wrapper classes (implementing `Contract` from ton-core) for the contracts, including any [de]serialization primitives and compilation functions. 7 | - `tests` - tests for the contracts. 8 | - `scripts` - scripts used by the project, mainly the deployment scripts. 9 | 10 | ## How to use 11 | 12 | ### Build 13 | 14 | `npx blueprint build` or `yarn blueprint build` 15 | 16 | ### Test 17 | 18 | `npx blueprint test` or `yarn blueprint test` 19 | 20 | ### Deploy or run another script 21 | 22 | `npx blueprint run` or `yarn blueprint run` 23 | 24 | ### Add a new contract 25 | 26 | `npx blueprint create ContractName` or `yarn blueprint create ContractName` 27 | -------------------------------------------------------------------------------- /contracts/utils/op-codes.fc: -------------------------------------------------------------------------------- 1 | ;; common 2 | 3 | const op::transfer = 0xf8a7ea5; 4 | const op::transfer_notification = 0x7362d09c; 5 | const op::internal_transfer = 0x178d4519; 6 | const op::excesses = 0xd53276db; 7 | const op::burn = 0x595f07bc; 8 | const op::burn_notification = 0x7bdd97de; 9 | 10 | const op::provide_wallet_address = 0x2c76b973; 11 | const op::take_wallet_address = 0xd1735400; 12 | 13 | const op::top_up = 0xd372158c; 14 | 15 | const error::invalid_op = 72; 16 | const error::wrong_op = 0xffff; 17 | const error::not_owner = 73; 18 | const error::not_valid_wallet = 74; 19 | const error::wrong_workchain = 333; 20 | 21 | ;; jetton-minter 22 | 23 | const op::mint = 0x642b7d07; 24 | const op::change_admin = 0x6501f354; 25 | const op::claim_admin = 0xfb88e119; 26 | const op::upgrade = 0x2508d66a; 27 | const op::call_to = 0x235caf52; 28 | const op::change_metadata_uri = 0xcb862902; 29 | 30 | ;; jetton-wallet 31 | 32 | const op::set_status = 0xeed236d3; 33 | 34 | const error::contract_locked = 45; 35 | const error::balance_error = 47; 36 | const error::not_enough_gas = 48; 37 | const error::invalid_message = 49; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Howard Peng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /scripts/incrementSample.ts: -------------------------------------------------------------------------------- 1 | import { Address, toNano } from '@ton/core'; 2 | import { Sample } from '../wrappers/jetton-minter'; 3 | import { NetworkProvider, sleep } from '@ton/blueprint'; 4 | 5 | export async function run(provider: NetworkProvider, args: string[]) { 6 | const ui = provider.ui(); 7 | 8 | const address = Address.parse(args.length > 0 ? args[0] : await ui.input('Sample address')); 9 | 10 | if (!(await provider.isContractDeployed(address))) { 11 | ui.write(`Error: Contract at address ${address} is not deployed!`); 12 | return; 13 | } 14 | 15 | const sample = provider.open(Sample.createFromAddress(address)); 16 | 17 | const counterBefore = await sample.getCounter(); 18 | 19 | await sample.sendIncrease(provider.sender(), { 20 | increaseBy: 1, 21 | value: toNano('0.05'), 22 | }); 23 | 24 | ui.write('Waiting for counter to increase...'); 25 | 26 | let counterAfter = await sample.getCounter(); 27 | let attempt = 1; 28 | while (counterAfter === counterBefore) { 29 | ui.setActionPrompt(`Attempt ${attempt}`); 30 | await sleep(2000); 31 | counterAfter = await sample.getCounter(); 32 | attempt++; 33 | } 34 | 35 | ui.clearActionPrompt(); 36 | ui.write('Counter increased successfully!'); 37 | } 38 | -------------------------------------------------------------------------------- /scripts/jetton-helpers.ts: -------------------------------------------------------------------------------- 1 | import { Sha256 } from "@aws-crypto/sha256-js"; 2 | import { Dictionary, beginCell, Cell } from "@ton/core"; 3 | 4 | const ONCHAIN_CONTENT_PREFIX = 0x00; 5 | const SNAKE_PREFIX = 0x00; 6 | const CELL_MAX_SIZE_BYTES = Math.floor((1023 - 8) / 8); 7 | 8 | const sha256 = (str: string) => { 9 | const sha = new Sha256(); 10 | sha.update(str); 11 | return Buffer.from(sha.digestSync()); 12 | }; 13 | 14 | const toKey = (key: string) => { 15 | return BigInt(`0x${sha256(key).toString("hex")}`); 16 | }; 17 | 18 | export function buildOnchainMetadata(data: { name: string; description: string; image: string }): Cell { 19 | let dict = Dictionary.empty(Dictionary.Keys.BigUint(256), Dictionary.Values.Cell()); 20 | 21 | // Store the on-chain metadata in the dictionary 22 | Object.entries(data).forEach(([key, value]) => { 23 | dict.set(toKey(key), makeSnakeCell(Buffer.from(value, "utf8"))); 24 | }); 25 | 26 | return beginCell().storeInt(ONCHAIN_CONTENT_PREFIX, 8).storeDict(dict).endCell(); 27 | } 28 | 29 | export function makeSnakeCell(data: Buffer) { 30 | // Create a cell that package the data 31 | let chunks = bufferToChunks(data, CELL_MAX_SIZE_BYTES); 32 | 33 | const b = chunks.reduceRight((curCell, chunk, index) => { 34 | if (index === 0) { 35 | curCell.storeInt(SNAKE_PREFIX, 8); 36 | } 37 | curCell.storeBuffer(chunk); 38 | if (index > 0) { 39 | const cell = curCell.endCell(); 40 | return beginCell().storeRef(cell); 41 | } else { 42 | return curCell; 43 | } 44 | }, beginCell()); 45 | return b.endCell(); 46 | } 47 | 48 | function bufferToChunks(buff: Buffer, chunkSize: number) { 49 | let chunks: Buffer[] = []; 50 | while (buff.byteLength > 0) { 51 | chunks.push(buff.slice(0, chunkSize)); 52 | buff = buff.slice(chunkSize); 53 | } 54 | return chunks; 55 | } 56 | -------------------------------------------------------------------------------- /scripts/deployMinter.ts: -------------------------------------------------------------------------------- 1 | import { Address, beginCell, toNano } from '@ton/core'; 2 | import { Minter } from '../wrappers/jetton-minter'; 3 | import { Wallet } from '../wrappers/jetton-wallet'; 4 | import { compile, NetworkProvider } from '@ton/blueprint'; 5 | 6 | import { buildOnchainMetadata } from "./jetton-helpers"; 7 | 8 | export async function run(provider: NetworkProvider) { 9 | 10 | let nextAdminAddress = Address.parse("EQD8TJ8xEWB1SpnRE4d89YO3jl0W0EiBnNS4IBaHaUmdfizE"); 11 | // let toAddress = Address.parse("EQD8TJ8xEWB1SpnRE4d89YO3jl0W0EiBnNS4IBaHaUmdfizE"); 12 | 13 | const jettonParams = { 14 | name: "test USDT", 15 | description: "This is description for test USDT", 16 | symbol: "testUSDT", 17 | image: "https://i.ibb.co/J3rk47X/USDT-ocean.webp" 18 | }; 19 | 20 | // Create content Cell 21 | let jetton_content_metadata = buildOnchainMetadata(jettonParams); 22 | 23 | const minter = provider.open( 24 | Minter.createFromConfig( 25 | { 26 | total_supply: 0n, 27 | admin_address: provider.sender().address!!, 28 | next_admin_address: nextAdminAddress, 29 | jetton_wallet_code: await compile("jetton-wallet"), 30 | metadata_url: jetton_content_metadata, 31 | }, 32 | await compile('jetton-minter') 33 | ) 34 | ); 35 | 36 | let master_msg = beginCell() 37 | .storeUint(395134233, 32) // opCode: TokenTransferInternal 38 | .storeUint(3333, 64) // query_id 39 | .storeCoins(toNano('1000000')) // jetton_amount 40 | .storeAddress(nextAdminAddress) // from_address 41 | .storeAddress(null) // response_address 42 | .storeCoins(0) // forward_ton_amount 43 | .storeUint(0, 1) // whether forward_payload or not 44 | .endCell(); 45 | 46 | 47 | // await minter.sendDeploy(provider.sender(), toNano('0.05')); 48 | await minter.sendMint(provider.sender(), { 49 | value: toNano('1.5'), 50 | queryID: 10, 51 | toAddress: provider.sender().address!!, // the address that receive the new minting JettonToken 52 | tonAmount: toNano('0.4'), 53 | master_msg: master_msg 54 | } ) 55 | 56 | 57 | await provider.waitForDeploy(minter.address); 58 | let dd = await minter.getJettonData(); 59 | console.log('ID:: US', dd); 60 | } 61 | -------------------------------------------------------------------------------- /contracts/utils/jetton-utils.fc: -------------------------------------------------------------------------------- 1 | #include "workchain.fc"; 2 | 3 | const int STATUS_SIZE = 4; 4 | 5 | cell pack_jetton_wallet_data(int status, int balance, slice owner_address, slice jetton_master_address) inline { 6 | return begin_cell() 7 | .store_uint(status, STATUS_SIZE) ;; 4 bits 8 | .store_coins(balance) 9 | .store_slice(owner_address) 10 | .store_slice(jetton_master_address) 11 | .end_cell(); 12 | } 13 | 14 | cell calculate_jetton_wallet_state_init(slice owner_address, slice jetton_master_address, cell jetton_wallet_code) inline { 15 | {- 16 | https://github.com/ton-blockchain/ton/blob/8a9ff339927b22b72819c5125428b70c406da631/crypto/block/block.tlb#L144 17 | _ split_depth:(Maybe (## 5)) special:(Maybe TickTock) 18 | code:(Maybe ^Cell) data:(Maybe ^Cell) 19 | library:(Maybe ^Cell) = StateInit; 20 | -} 21 | return begin_cell() 22 | .store_uint(0, 2) ;; 0b00 - No split_depth; No special 23 | .store_maybe_ref(jetton_wallet_code) 24 | .store_maybe_ref( 25 | pack_jetton_wallet_data( 26 | 0, ;; status 27 | 0, ;; balance 28 | owner_address, 29 | jetton_master_address) 30 | ) 31 | .store_uint(0, 1) ;; Empty libraries 32 | .end_cell(); 33 | } 34 | 35 | slice calculate_jetton_wallet_address(cell state_init) inline { 36 | {- 37 | https://github.com/ton-blockchain/ton/blob/8a9ff339927b22b72819c5125428b70c406da631/crypto/block/block.tlb#L105 38 | addr_std$10 anycast:(Maybe Anycast) workchain_id:int8 address:bits256 = MsgAddressInt; 39 | -} 40 | return begin_cell() 41 | .store_uint(4, 3) ;; 0b100 = addr_std$10 tag; No anycast 42 | .store_int(MY_WORKCHAIN, 8) 43 | .store_uint(cell_hash(state_init), 256) 44 | .end_cell() 45 | .begin_parse(); 46 | } 47 | 48 | slice calculate_user_jetton_wallet_address(slice owner_address, slice jetton_master_address, cell jetton_wallet_code) inline { 49 | return calculate_jetton_wallet_address(calculate_jetton_wallet_state_init(owner_address, jetton_master_address, jetton_wallet_code)); 50 | } 51 | 52 | () check_either_forward_payload(slice s) impure inline { 53 | if (s.preload_uint(1)) { 54 | ;; forward_payload in ref 55 | (int remain_bits, int remain_refs) = slice_bits_refs(s); 56 | throw_unless(error::invalid_message, (remain_refs == 1) & (remain_bits == 1)); ;; we check that there is no excess in the slice 57 | } 58 | ;; else forward_payload in slice - arbitrary bits and refs 59 | } -------------------------------------------------------------------------------- /wrappers/jetton-wallet.ts: -------------------------------------------------------------------------------- 1 | import { TupleBuilder, Address, beginCell, Cell, Contract, contractAddress, ContractProvider, Sender, SendMode, ADNLAddress } from '@ton/core'; 2 | 3 | export type walletConfig = { 4 | owner_address: Address; 5 | jetton_master_address: Address; 6 | }; 7 | 8 | export function walletConfigToCell(config: walletConfig): Cell { 9 | return beginCell() 10 | .storeUint(0, 4) 11 | .storeCoins(0) 12 | .storeAddress(config.owner_address) 13 | .storeAddress(config.jetton_master_address) 14 | .endCell(); 15 | } 16 | 17 | export const Opcodes = { 18 | increase: 0x7e8764ef, 19 | }; 20 | 21 | export class Wallet implements Contract { 22 | constructor(readonly address: Address, readonly init?: { code: Cell; data: Cell }) {} 23 | 24 | static createFromAddress(address: Address) { 25 | return new Wallet(address); 26 | } 27 | 28 | static createFromConfig(config: walletConfig, code: Cell, workchain = 0) { 29 | const data = walletConfigToCell(config); 30 | const init = { code, data }; 31 | return new Wallet(contractAddress(workchain, init), init); 32 | } 33 | 34 | async sendDeploy(provider: ContractProvider, via: Sender, value: bigint) { 35 | await provider.internal(via, { 36 | value, 37 | sendMode: SendMode.PAY_GAS_SEPARATELY, 38 | body: beginCell().endCell(), 39 | }); 40 | } 41 | 42 | 43 | async sendIncrease( 44 | provider: ContractProvider, 45 | via: Sender, 46 | opts: { 47 | increaseBy: number; 48 | value: bigint; 49 | queryID?: number; 50 | } 51 | ) { 52 | await provider.internal(via, { 53 | value: opts.value, 54 | sendMode: SendMode.PAY_GAS_SEPARATELY, 55 | body: beginCell() 56 | .storeUint(Opcodes.increase, 32) 57 | .storeUint(opts.queryID ?? 0, 64) 58 | .storeUint(opts.increaseBy, 32) 59 | .endCell(), 60 | }); 61 | } 62 | 63 | async getJettonData(provider: ContractProvider): Promise<[bigint, Address, Address, Cell]> { 64 | const { stack } = await provider.get('get_wallet_data', []) 65 | return [ 66 | stack.readBigNumber(), // balance 67 | stack.readAddress(), // owner_address 68 | stack.readAddress(), // jetton_master 69 | stack.readCell() // wallet_code 70 | ] 71 | } 72 | 73 | async getStatus(provider: ContractProvider) { 74 | const result = await provider.get('get_status', []); 75 | return result.stack.readNumber(); 76 | } 77 | 78 | async getBalance(provider: ContractProvider): Promise { 79 | const state = await provider.getState() 80 | return state.balance 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /wrappers/jetton-minter.ts: -------------------------------------------------------------------------------- 1 | import { TupleBuilder, Address, beginCell, Cell, Contract, contractAddress, ContractProvider, Sender, SendMode } from '@ton/core'; 2 | 3 | export type MinterConfig = { 4 | total_supply: bigint; 5 | admin_address: Address; 6 | next_admin_address: Address; 7 | jetton_wallet_code: Cell; 8 | metadata_url: Cell; 9 | }; 10 | 11 | export function minterConfigToCell(config: MinterConfig): Cell { 12 | return beginCell() 13 | .storeCoins(config.total_supply) 14 | .storeAddress(config.admin_address) 15 | .storeAddress(config.next_admin_address) 16 | .storeRef(config.jetton_wallet_code) 17 | .storeRef(config.metadata_url) 18 | .endCell(); 19 | } 20 | 21 | export const Opcodes = { 22 | mint: 0x642b7d07, 23 | burn_notification: 0x7bdd97de, 24 | // increase: 0x7e8764ef, 25 | }; 26 | 27 | export class Minter implements Contract { 28 | constructor(readonly address: Address, readonly init?: { code: Cell; data: Cell }) {} 29 | 30 | static createFromAddress(address: Address) { 31 | return new Minter(address); 32 | } 33 | 34 | static createFromConfig(config: MinterConfig, code: Cell, workchain = 0) { 35 | const data = minterConfigToCell(config); 36 | const init = { code, data }; 37 | return new Minter(contractAddress(workchain, init), init); 38 | } 39 | 40 | async sendDeploy(provider: ContractProvider, via: Sender, value: bigint) { 41 | await provider.internal(via, { 42 | value, 43 | sendMode: SendMode.PAY_GAS_SEPARATELY, 44 | body: beginCell().endCell(), 45 | }); 46 | } 47 | 48 | async sendMint( 49 | provider: ContractProvider, 50 | via: Sender, 51 | opts: { 52 | value: bigint | string 53 | queryID?: number; 54 | toAddress: Address; 55 | tonAmount: bigint; 56 | master_msg: Cell; 57 | } 58 | ) { 59 | await provider.internal(via, { 60 | value: opts.value, 61 | sendMode: SendMode.PAY_GAS_SEPARATELY, 62 | body: beginCell() 63 | .storeUint(Opcodes.mint, 32) 64 | .storeUint(opts.queryID ?? 0, 64) 65 | .storeAddress(opts.toAddress) 66 | .storeCoins(opts.tonAmount) 67 | .storeRef(opts.master_msg) 68 | .endCell(), 69 | }); 70 | } 71 | 72 | async getJettonData(provider: ContractProvider): Promise<[bigint, boolean, Address, Cell, Cell]> { 73 | const { stack } = await provider.get('get_jetton_data', []) 74 | return [ 75 | stack.readBigNumber(), 76 | stack.readBoolean(), 77 | stack.readAddress(), 78 | stack.readCell(), 79 | stack.readCell() 80 | ] 81 | } 82 | 83 | async getWalletAddress(provider: ContractProvider, owner: Address): Promise
{ 84 | const tb = new TupleBuilder() 85 | tb.writeAddress(owner) 86 | const { stack } = await provider.get('get_wallet_address', tb.build()) 87 | return stack.readAddress() 88 | } 89 | 90 | async getBalance(provider: ContractProvider): Promise { 91 | const state = await provider.getState() 92 | return state.balance 93 | } 94 | 95 | async getNextAdminAddress(provider: ContractProvider) { 96 | const result = await provider.get('get_next_admin_address', []); 97 | return result.stack.readAddress(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /tests/Sample.spec.ts: -------------------------------------------------------------------------------- 1 | import { Blockchain, SandboxContract, TreasuryContract , printTransactionFees, 2 | prettyLogTransactions,} from '@ton/sandbox'; 3 | import { Cell, toNano, beginCell } from '@ton/core'; 4 | import { Minter } from '../wrappers/jetton-minter'; 5 | import { Wallet } from '../wrappers/jetton-wallet'; 6 | 7 | import '@ton/test-utils'; 8 | import { compile } from '@ton/blueprint'; 9 | 10 | 11 | import { buildOnchainMetadata } from "../scripts/jetton-helpers"; 12 | const jettonParams = { 13 | name: "test USDT", 14 | description: "This is description for test USDT", 15 | symbol: "testUSDT", 16 | image: "https://i.ibb.co/J3rk47X/USDT-ocean.webp" 17 | }; 18 | let jetton_content_metadata = buildOnchainMetadata(jettonParams); 19 | 20 | describe('Sample', () => { 21 | let code: Cell; 22 | 23 | let blockchain: Blockchain; 24 | let deployer: SandboxContract; 25 | let treasury: SandboxContract; 26 | let minter: SandboxContract; 27 | let jettonWallet_deployer: SandboxContract; 28 | 29 | beforeAll(async () => { 30 | code = await compile('jetton-minter'); 31 | }); 32 | 33 | 34 | beforeEach(async () => { 35 | blockchain = await Blockchain.create(); 36 | deployer = await blockchain.treasury('deployer'); 37 | treasury = await blockchain.treasury('treasury'); 38 | minter = blockchain.openContract( 39 | Minter.createFromConfig( 40 | { 41 | total_supply: 0n, 42 | admin_address: deployer.address!!, 43 | next_admin_address: treasury.address!!, 44 | jetton_wallet_code: await compile("jetton-wallet"), 45 | metadata_url: jetton_content_metadata 46 | }, 47 | code 48 | ) 49 | ); 50 | 51 | jettonWallet_deployer = blockchain.openContract( 52 | Wallet.createFromConfig( 53 | { owner_address: deployer.address, jetton_master_address: minter.address }, 54 | await compile("jetton-wallet") 55 | ) 56 | ); 57 | 58 | let master_msg = beginCell() 59 | .storeUint(395134233, 32) // opCode: TokenTransferInternal / 0x178d4519 60 | .storeUint(0, 64) // query_id 61 | .storeCoins(toNano('1000000')) // jetton_amount 62 | .storeAddress(minter.address) // from_address 63 | .storeAddress(deployer.address) // response_address 64 | .storeCoins(0) // forward_ton_amount 65 | .storeUint(0, 1) // whether forward_payload or not 66 | .endCell(); 67 | 68 | const deployResult = await minter.sendMint(deployer.getSender(), { // 0x642b7d07 69 | value: toNano('1.5'), 70 | queryID: 10, 71 | toAddress: deployer.address, 72 | tonAmount: toNano('0.4'), 73 | master_msg: master_msg 74 | }); 75 | 76 | expect(deployResult.transactions).toHaveTransaction({ 77 | from: deployer.address, 78 | to: minter.address, 79 | deploy: true, 80 | success: true, 81 | }); 82 | 83 | printTransactionFees(deployResult.transactions); 84 | prettyLogTransactions(deployResult.transactions); 85 | 86 | }); 87 | 88 | 89 | it('should deploy', async () => { 90 | console.log("Deployer Address: " + deployer.address); 91 | console.log("Minter Address: " + minter.address); 92 | 93 | 94 | let balanceDeployer = await jettonWallet_deployer.getBalance(); 95 | console.log("Balance: " + balanceDeployer); 96 | }); 97 | 98 | // it('should increase counter', async () => { 99 | // const increaseTimes = 3; 100 | // for (let i = 0; i < increaseTimes; i++) { 101 | // console.log(`increase ${i + 1}/${increaseTimes}`); 102 | 103 | // const increaser = await blockchain.treasury('increaser' + i); 104 | 105 | // const counterBefore = await sample.getCounter(); 106 | 107 | // console.log('counter before increasing', counterBefore); 108 | 109 | // const increaseBy = Math.floor(Math.random() * 100); 110 | 111 | // console.log('increasing by', increaseBy); 112 | 113 | // const increaseResult = await sample.sendIncrease(increaser.getSender(), { 114 | // increaseBy, 115 | // value: toNano('0.05'), 116 | // }); 117 | 118 | // expect(increaseResult.transactions).toHaveTransaction({ 119 | // from: increaser.address, 120 | // to: sample.address, 121 | // success: true, 122 | // }); 123 | 124 | // const counterAfter = await sample.getCounter(); 125 | 126 | // console.log('counter after increasing', counterAfter); 127 | 128 | // expect(counterAfter).toBe(counterBefore + increaseBy); 129 | // } 130 | // }); 131 | }); 132 | -------------------------------------------------------------------------------- /contracts/utils/gas.fc: -------------------------------------------------------------------------------- 1 | #include "./workchain.fc"; 2 | 3 | const ONE_TON = 1000000000; 4 | 5 | const MIN_STORAGE_DURATION = 5 * 365 * 24 * 3600; ;; 5 years 6 | 7 | ;;# Precompiled constants 8 | ;; 9 | ;;All of the contents are result of contract emulation tests 10 | ;; 11 | 12 | ;;## Minimal fees 13 | ;; 14 | ;;- Transfer [/sandbox_tests/JettonWallet.spec.ts#L935](L935) `0.028627415` TON 15 | ;;- Burn [/sandbox_tests/JettonWallet.spec.ts#L1185](L1185) `0.016492002` TON 16 | 17 | 18 | ;;## Storage 19 | ;; 20 | ;;Get calculated in a separate test file [/sandbox_tests/StateInit.spec.ts](StateInit.spec.ts) 21 | 22 | ;;- `JETTON_WALLET_BITS` [/sandbox_tests/StateInit.spec.ts#L92](L92) 23 | const JETTON_WALLET_BITS = 1033; 24 | 25 | ;;- `JETTON_WALLET_CELLS`: [/sandbox_tests/StateInit.spec.ts#L92](L92) 26 | const JETTON_WALLET_CELLS = 3; 27 | 28 | ;; difference in JETTON_WALLET_BITS/JETTON_WALLET_INITSTATE_BITS is difference in 29 | ;; StateInit and AccountStorage (https://github.com/ton-blockchain/ton/blob/master/crypto/block/block.tlb) 30 | ;; we count bits as if balances are max possible 31 | ;;- `JETTON_WALLET_INITSTATE_BITS` [/sandbox_tests/StateInit.spec.ts#L95](L95) 32 | const JETTON_WALLET_INITSTATE_BITS = 931; 33 | ;;- `JETTON_WALLET_INITSTATE_CELLS` [/sandbox_tests/StateInit.spec.ts#L95](L95) 34 | const JETTON_WALLET_INITSTATE_CELLS = 3; 35 | 36 | ;; jetton-wallet.fc#L163 - maunal bits counting 37 | const BURN_NOTIFICATION_BITS = 754; ;; body = 32+64+124+(3+8+256)+(3+8+256) 38 | const BURN_NOTIFICATION_CELLS = 1; ;; body always in ref 39 | 40 | ;;## Gas 41 | ;; 42 | ;;Gas constants are calculated in the main test suite. 43 | ;;First the related transaction is found, and then it's 44 | ;;resulting gas consumption is printed to the console. 45 | 46 | ;;- `SEND_TRANSFER_GAS_CONSUMPTION` [/sandbox_tests/JettonWallet.spec.ts#L853](L853) 47 | const SEND_TRANSFER_GAS_CONSUMPTION = 9255; 48 | 49 | ;;- `RECEIVE_TRANSFER_GAS_CONSUMPTION` [/sandbox_tests/JettonWallet.spec.ts#L862](L862) 50 | const RECEIVE_TRANSFER_GAS_CONSUMPTION = 10355; 51 | 52 | ;;- `SEND_BURN_GAS_CONSUMPTION` [/sandbox_tests/JettonWallet.spec.ts#L1154](L1154) 53 | const SEND_BURN_GAS_CONSUMPTION = 5791; 54 | 55 | ;;- `RECEIVE_BURN_GAS_CONSUMPTION` [/sandbox_tests/JettonWallet.spec.ts#L1155](L1155) 56 | const RECEIVE_BURN_GAS_CONSUMPTION = 6775; 57 | 58 | 59 | int calculate_jetton_wallet_min_storage_fee() inline { 60 | return get_storage_fee(MY_WORKCHAIN, MIN_STORAGE_DURATION, JETTON_WALLET_BITS, JETTON_WALLET_CELLS); 61 | } 62 | 63 | int forward_init_state_overhead() inline { 64 | return get_simple_forward_fee(MY_WORKCHAIN, JETTON_WALLET_INITSTATE_BITS, JETTON_WALLET_INITSTATE_CELLS); 65 | } 66 | 67 | () check_amount_is_enough_to_transfer(int msg_value, int forward_ton_amount, int fwd_fee) impure inline { 68 | int fwd_count = forward_ton_amount ? 2 : 1; ;; second sending (forward) will be cheaper that first 69 | 70 | int jetton_wallet_gas_consumption = get_precompiled_gas_consumption(); 71 | int send_transfer_gas_consumption = null?(jetton_wallet_gas_consumption) ? SEND_TRANSFER_GAS_CONSUMPTION : jetton_wallet_gas_consumption; 72 | int receive_transfer_gas_consumption = null?(jetton_wallet_gas_consumption) ? RECEIVE_TRANSFER_GAS_CONSUMPTION : jetton_wallet_gas_consumption; 73 | 74 | throw_unless( 75 | error::not_enough_gas, msg_value > 76 | forward_ton_amount + 77 | ;; 3 messages: wal1->wal2, wal2->owner, wal2->response 78 | ;; but last one is optional (it is ok if it fails) 79 | fwd_count * fwd_fee + 80 | forward_init_state_overhead() + ;; additional fwd fees related to initstate in iternal_transfer 81 | get_compute_fee(MY_WORKCHAIN, send_transfer_gas_consumption) + 82 | get_compute_fee(MY_WORKCHAIN, receive_transfer_gas_consumption) + 83 | calculate_jetton_wallet_min_storage_fee() 84 | ); 85 | 86 | ;; ~dump(get_compute_fee(MY_WORKCHAIN, send_transfer_gas_consumption) + get_compute_fee(MY_WORKCHAIN, receive_transfer_gas_consumption)); 87 | ;; ~dump( forward_ton_amount + 88 | ;; ;; 3 messages: wal1->wal2, wal2->owner, wal2->response 89 | ;; ;; but last one is optional (it is ok if it fails) 90 | ;; fwd_count * fwd_fee + 91 | ;; forward_init_state_overhead() + ;; additional fwd fees related to initstate in iternal_transfer 92 | ;; get_compute_fee(MY_WORKCHAIN, send_transfer_gas_consumption) + 93 | ;; get_compute_fee(MY_WORKCHAIN, receive_transfer_gas_consumption) + 94 | ;; calculate_jetton_wallet_min_storage_fee()); 95 | } 96 | 97 | () check_amount_is_enough_to_burn(int msg_value) impure inline { 98 | int jetton_wallet_gas_consumption = get_precompiled_gas_consumption(); 99 | int send_burn_gas_consumption = null?(jetton_wallet_gas_consumption) ? SEND_BURN_GAS_CONSUMPTION : jetton_wallet_gas_consumption; 100 | 101 | throw_unless(error::not_enough_gas, msg_value > 102 | get_forward_fee(MY_WORKCHAIN, BURN_NOTIFICATION_BITS, BURN_NOTIFICATION_CELLS) 103 | + get_compute_fee(MY_WORKCHAIN, send_burn_gas_consumption) 104 | + get_compute_fee(MY_WORKCHAIN, RECEIVE_BURN_GAS_CONSUMPTION) 105 | ); 106 | } -------------------------------------------------------------------------------- /contracts/jetton-wallet.fc: -------------------------------------------------------------------------------- 1 | ;; Jetton Wallet Smart Contract 2 | 3 | #pragma version >=0.4.3; 4 | 5 | #include "./imports/stdlib.fc"; 6 | #include "./utils/op-codes.fc"; 7 | #include "./utils/workchain.fc"; 8 | #include "./utils/jetton-utils.fc"; 9 | #include "./utils/gas.fc"; 10 | 11 | {- 12 | Storage 13 | 14 | Note, status == 0 means unlocked - user can freely transfer and recieve jettons (only admin can burn). 15 | (status & 1) bit means user can not send jettons 16 | (status & 2) bit means user can not receive jettons. 17 | Master (minter) smart-contract able to make outgoing actions (transfer, burn jettons) with any status. 18 | 19 | storage#_ status:uint4 20 | balance:Coins owner_address:MsgAddressInt 21 | jetton_master_address:MsgAddressInt = Storage; 22 | -} 23 | 24 | (int, int, slice, slice) load_data() inline { 25 | slice ds = get_data().begin_parse(); 26 | var data = ( 27 | ds~load_uint(STATUS_SIZE), ;; (4 bits) 28 | ds~load_coins(), ;; balance 29 | ds~load_msg_addr(), ;; owner_address 30 | ds~load_msg_addr() ;; jetton_master_address 31 | ); 32 | ds.end_parse(); 33 | return data; 34 | } 35 | 36 | () save_data(int status, int balance, slice owner_address, slice jetton_master_address) impure inline { 37 | set_data(pack_jetton_wallet_data(status, balance, owner_address, jetton_master_address)); 38 | } 39 | 40 | () send_jettons(slice in_msg_body, slice sender_address, int msg_value, int fwd_fee) impure inline_ref { 41 | ;; see transfer TL-B layout in jetton.tlb 42 | int query_id = in_msg_body~load_query_id(); 43 | int jetton_amount = in_msg_body~load_coins(); 44 | slice to_owner_address = in_msg_body~load_msg_addr(); 45 | check_same_workchain(to_owner_address); 46 | 47 | (int status, int balance, slice owner_address, slice jetton_master_address) = load_data(); 48 | 49 | int is_from_master = equal_slices_bits(jetton_master_address, sender_address); 50 | int outgoing_transfers_unlocked = ((status & 1) == 0); 51 | throw_unless(error::contract_locked, outgoing_transfers_unlocked | is_from_master); 52 | throw_unless(error::not_owner, equal_slices_bits(owner_address, sender_address) | is_from_master); 53 | 54 | balance -= jetton_amount; 55 | throw_unless(error::balance_error, balance >= 0); 56 | 57 | cell state_init = calculate_jetton_wallet_state_init(to_owner_address, jetton_master_address, my_code()); 58 | slice to_wallet_address = calculate_jetton_wallet_address(state_init); 59 | slice response_address = in_msg_body~load_msg_addr(); 60 | in_msg_body~skip_maybe_ref(); ;; custom_payload 61 | int forward_ton_amount = in_msg_body~load_coins(); 62 | 63 | check_either_forward_payload(in_msg_body); 64 | slice either_forward_payload = in_msg_body; 65 | 66 | ;; see internal TL-B layout in jetton.tlb 67 | cell msg_body = begin_cell() 68 | .store_op(op::internal_transfer) 69 | .store_query_id(query_id) 70 | .store_coins(jetton_amount) 71 | .store_slice(owner_address) 72 | .store_slice(response_address) 73 | .store_coins(forward_ton_amount) 74 | .store_slice(either_forward_payload) 75 | .end_cell(); 76 | 77 | ;; build MessageRelaxed, see TL-B layout in stdlib.fc#L733 78 | cell msg = begin_cell() 79 | .store_msg_flags_and_address_none(BOUNCEABLE) 80 | .store_slice(to_wallet_address) 81 | .store_coins(0) 82 | .store_statinit_ref_and_body_ref(state_init, msg_body) 83 | .end_cell(); 84 | 85 | check_amount_is_enough_to_transfer(msg_value, forward_ton_amount, fwd_fee); 86 | send_raw_message(msg, SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE | SEND_MODE_BOUNCE_ON_ACTION_FAIL); 87 | save_data(status, balance, owner_address, jetton_master_address); 88 | } 89 | 90 | () receive_jettons(slice in_msg_body, slice sender_address, int my_ton_balance, int msg_value) impure inline_ref { 91 | (int status, int balance, slice owner_address, slice jetton_master_address) = load_data(); 92 | int incoming_transfers_locked = ((status & 2) == 2); 93 | throw_if(error::contract_locked, incoming_transfers_locked); 94 | 95 | ;; see internal TL-B layout in jetton.tlb 96 | int query_id = in_msg_body~load_query_id(); 97 | int jetton_amount = in_msg_body~load_coins(); 98 | 99 | balance += jetton_amount; 100 | 101 | slice from_address = in_msg_body~load_msg_addr(); 102 | slice response_address = in_msg_body~load_msg_addr(); 103 | throw_unless(error::not_valid_wallet, 104 | equal_slices_bits(jetton_master_address, sender_address) 105 | | 106 | equal_slices_bits(calculate_user_jetton_wallet_address(from_address, jetton_master_address, my_code()), sender_address) 107 | ); 108 | int forward_ton_amount = in_msg_body~load_coins(); 109 | 110 | if (forward_ton_amount) { 111 | slice either_forward_payload = in_msg_body; 112 | 113 | ;; see transfer_notification TL-B layout in jetton.tlb 114 | cell msg_body = begin_cell() 115 | .store_op(op::transfer_notification) 116 | .store_query_id(query_id) 117 | .store_coins(jetton_amount) 118 | .store_slice(from_address) 119 | .store_slice(either_forward_payload) 120 | .end_cell(); 121 | 122 | ;; build MessageRelaxed, see TL-B layout in stdlib.fc#L733 123 | cell msg = begin_cell() 124 | .store_msg_flags_and_address_none(NON_BOUNCEABLE) 125 | .store_slice(owner_address) 126 | .store_coins(forward_ton_amount) 127 | .store_only_body_ref(msg_body) 128 | .end_cell(); 129 | 130 | send_raw_message(msg, SEND_MODE_PAY_FEES_SEPARATELY | SEND_MODE_BOUNCE_ON_ACTION_FAIL); 131 | } 132 | 133 | if (~ is_address_none(response_address)) { 134 | int to_leave_on_balance = my_ton_balance - msg_value + my_storage_due(); 135 | raw_reserve(max(to_leave_on_balance, calculate_jetton_wallet_min_storage_fee()), RESERVE_AT_MOST); 136 | 137 | ;; build MessageRelaxed, see TL-B layout in stdlib.fc#L733 138 | cell msg = begin_cell() 139 | .store_msg_flags_and_address_none(NON_BOUNCEABLE) 140 | .store_slice(response_address) 141 | .store_coins(0) 142 | .store_prefix_only_body() 143 | .store_op(op::excesses) 144 | .store_query_id(query_id) 145 | .end_cell(); 146 | send_raw_message(msg, SEND_MODE_CARRY_ALL_BALANCE | SEND_MODE_IGNORE_ERRORS); 147 | } 148 | 149 | save_data(status, balance, owner_address, jetton_master_address); 150 | } 151 | 152 | () burn_jettons(slice in_msg_body, slice sender_address, int msg_value) impure inline_ref { 153 | (int status, int balance, slice owner_address, slice jetton_master_address) = load_data(); 154 | int query_id = in_msg_body~load_query_id(); 155 | int jetton_amount = in_msg_body~load_coins(); 156 | slice response_address = in_msg_body~load_msg_addr(); 157 | in_msg_body~skip_maybe_ref(); ;; custom_payload 158 | in_msg_body.end_parse(); 159 | 160 | balance -= jetton_amount; 161 | int is_from_master = equal_slices_bits(jetton_master_address, sender_address); 162 | throw_unless(error::not_owner, is_from_master); 163 | throw_unless(error::balance_error, balance >= 0); 164 | 165 | ;; see burn_notification TL-B layout in jetton.tlb 166 | cell msg_body = begin_cell() 167 | .store_op(op::burn_notification) 168 | .store_query_id(query_id) 169 | .store_coins(jetton_amount) 170 | .store_slice(owner_address) 171 | .store_slice(response_address) 172 | .end_cell(); 173 | 174 | ;; build MessageRelaxed, see TL-B layout in stdlib.fc#L733 175 | cell msg = begin_cell() 176 | .store_msg_flags_and_address_none(BOUNCEABLE) 177 | .store_slice(jetton_master_address) 178 | .store_coins(0) 179 | .store_only_body_ref(msg_body) 180 | .end_cell(); 181 | 182 | check_amount_is_enough_to_burn(msg_value); 183 | 184 | send_raw_message(msg, SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE | SEND_MODE_BOUNCE_ON_ACTION_FAIL); 185 | 186 | save_data(status, balance, owner_address, jetton_master_address); 187 | } 188 | 189 | () on_bounce(slice in_msg_body) impure inline { 190 | in_msg_body~skip_bounced_prefix(); 191 | (int status, int balance, slice owner_address, slice jetton_master_address) = load_data(); 192 | int op = in_msg_body~load_op(); 193 | throw_unless(error::wrong_op, (op == op::internal_transfer) | (op == op::burn_notification)); 194 | in_msg_body~skip_query_id(); 195 | int jetton_amount = in_msg_body~load_coins(); 196 | save_data(status, balance + jetton_amount, owner_address, jetton_master_address); 197 | } 198 | 199 | {- 200 | --- Main --- 201 | -} 202 | () recv_internal(int my_ton_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure { 203 | slice in_msg_full_slice = in_msg_full.begin_parse(); 204 | int msg_flags = in_msg_full_slice~load_msg_flags(); 205 | if (is_bounced(msg_flags)) { 206 | on_bounce(in_msg_body); 207 | return (); 208 | } 209 | slice sender_address = in_msg_full_slice~load_msg_addr(); 210 | int fwd_fee_from_in_msg = in_msg_full_slice~retrieve_fwd_fee(); 211 | int fwd_fee = get_original_fwd_fee(MY_WORKCHAIN, fwd_fee_from_in_msg); ;; we use message fwd_fee for estimation of forward_payload costs 212 | 213 | int op = in_msg_body~load_op(); 214 | 215 | ;; outgoing transfer 216 | if (op == op::transfer) { 217 | send_jettons(in_msg_body, sender_address, msg_value, fwd_fee); 218 | return (); 219 | } 220 | 221 | ;; incoming transfer 222 | if (op == op::internal_transfer) { 223 | receive_jettons(in_msg_body, sender_address, my_ton_balance, msg_value); 224 | return (); 225 | } 226 | 227 | ;; burn 228 | if (op == op::burn) { 229 | burn_jettons(in_msg_body, sender_address, msg_value); 230 | return (); 231 | } 232 | 233 | if (op == op::set_status) { ;; 0xeed236d3 234 | ;; skip the query_id 235 | in_msg_body~skip_query_id(); 236 | 237 | ;; read the new status for this Jetton Wallet 238 | int new_status = in_msg_body~load_uint(STATUS_SIZE); 239 | in_msg_body.end_parse(); 240 | 241 | (_, int balance, slice owner_address, slice jetton_master_address) = load_data(); 242 | throw_unless(error::not_valid_wallet, equal_slices_bits(sender_address, jetton_master_address)); 243 | 244 | save_data(new_status, balance, owner_address, jetton_master_address); 245 | return (); 246 | } 247 | 248 | if (op == op::top_up) { 249 | return (); ;; just accept tons 250 | } 251 | 252 | throw(error::wrong_op); 253 | } 254 | 255 | ;; 256 | ;; Get Method 257 | ;; 258 | 259 | (int, slice, slice, cell) get_wallet_data() method_id { 260 | (_, int balance, slice owner_address, slice jetton_master_address) = load_data(); 261 | return (balance, owner_address, jetton_master_address, my_code()); 262 | } 263 | 264 | int get_status() method_id { 265 | (int status, _, _, _) = load_data(); 266 | return status; 267 | } -------------------------------------------------------------------------------- /contracts/jetton-minter.fc: -------------------------------------------------------------------------------- 1 | ;; Jetton minter smart contract 2 | 3 | #pragma version >=0.4.3; 4 | 5 | #include "./imports/stdlib.fc"; 6 | #include "./utils/op-codes.fc"; 7 | #include "./utils/workchain.fc"; 8 | #include "./utils/jetton-utils.fc"; 9 | #include "./utils/gas.fc"; 10 | 11 | {- 12 | storage#_ total_supply:Coins admin_address:MsgAddress next_admin_address:MsgAddress jetton_wallet_code:^Cell metadata_uri:^Cell = Storage; 13 | -} 14 | (int, slice, slice, cell, cell) load_data() inline { 15 | slice ds = get_data().begin_parse(); 16 | var data = ( 17 | ds~load_coins(), ;; total_supply 18 | ds~load_msg_addr(), ;; admin_address 19 | ds~load_msg_addr(), ;; next_admin_address 20 | ds~load_ref(), ;; jetton_wallet_code 21 | ds~load_ref() ;; metadata_url (contains snake slice without 0x0 prefix) 22 | ); 23 | 24 | ds.end_parse(); 25 | return data; 26 | } 27 | 28 | () save_data(int total_supply, slice admin_address, slice next_admin_address, cell jetton_wallet_code, cell metadata_uri) impure inline { 29 | set_data( 30 | begin_cell() 31 | .store_coins(total_supply) 32 | .store_slice(admin_address) 33 | .store_slice(next_admin_address) 34 | .store_ref(jetton_wallet_code) 35 | .store_ref(metadata_uri) 36 | .end_cell() 37 | ); 38 | } 39 | 40 | 41 | {- Private Functions / Utility -} 42 | () send_to_jetton_wallet(slice to_address, cell jetton_wallet_code, int ton_amount, cell master_msg, int need_state_init) impure inline { 43 | raw_reserve(ONE_TON, RESERVE_REGULAR); ;; reserve for storage fees 44 | 45 | cell state_init = calculate_jetton_wallet_state_init(to_address, my_address(), jetton_wallet_code); 46 | slice to_wallet_address = calculate_jetton_wallet_address(state_init); 47 | 48 | ;; build MessageRelaxed, see TL-B layout in stdlib.fc#L733 49 | var msg = begin_cell() 50 | .store_msg_flags_and_address_none(BOUNCEABLE) 51 | .store_slice(to_wallet_address) ;; dest 52 | .store_coins(ton_amount); 53 | 54 | if (need_state_init) { 55 | msg = msg.store_statinit_ref_and_body_ref(state_init, master_msg); 56 | } else { 57 | msg = msg.store_only_body_ref(master_msg); 58 | } 59 | 60 | send_raw_message(msg.end_cell(), SEND_MODE_PAY_FEES_SEPARATELY | SEND_MODE_BOUNCE_ON_ACTION_FAIL); 61 | } 62 | 63 | 64 | {- Main -} 65 | () recv_internal(int msg_value, cell in_msg_full, slice in_msg_body) impure { 66 | slice in_msg_full_slice = in_msg_full.begin_parse(); 67 | int msg_flags = in_msg_full_slice~load_msg_flags(); 68 | if (is_bounced(msg_flags)) { 69 | in_msg_body~skip_bounced_prefix(); 70 | 71 | ;; process only mint bounces 72 | ifnot (in_msg_body~load_op() == op::internal_transfer) { 73 | return (); 74 | } 75 | 76 | in_msg_body~skip_query_id(); 77 | int jetton_amount = in_msg_body~load_coins(); 78 | (int total_supply, slice admin_address, slice next_admin_address, cell jetton_wallet_code, cell metadata_uri) = load_data(); 79 | save_data(total_supply - jetton_amount, admin_address, next_admin_address, jetton_wallet_code, metadata_uri); 80 | return (); 81 | } 82 | 83 | slice sender_address = in_msg_full_slice~load_msg_addr(); 84 | int fwd_fee_from_in_msg = in_msg_full_slice~retrieve_fwd_fee(); 85 | int fwd_fee = get_original_fwd_fee(MY_WORKCHAIN, fwd_fee_from_in_msg); ;; we use message fwd_fee for estimation of forward_payload costs 86 | 87 | (int op, int query_id) = in_msg_body~load_op_and_query_id(); 88 | 89 | (int total_supply, slice admin_address, slice next_admin_address, cell jetton_wallet_code, cell metadata_uri) = load_data(); 90 | 91 | if (op == op::mint) { ;; 0x642b7d07 92 | throw_unless(error::not_owner, equal_slices_bits(sender_address, admin_address)); 93 | 94 | slice to_address = in_msg_body~load_msg_addr(); 95 | check_same_workchain(to_address); 96 | 97 | int ton_amount = in_msg_body~load_coins(); 98 | cell master_msg = in_msg_body~load_ref(); 99 | in_msg_body.end_parse(); 100 | 101 | ;; see internal_transfer TL-B layout in jetton.tlb 102 | slice master_msg_slice = master_msg.begin_parse(); 103 | throw_unless(error::invalid_op, master_msg_slice~load_op() == op::internal_transfer); 104 | master_msg_slice~skip_query_id(); 105 | int jetton_amount = master_msg_slice~load_coins(); 106 | master_msg_slice~load_msg_addr(); ;; from_address 107 | master_msg_slice~load_msg_addr(); ;; response_address 108 | int forward_ton_amount = master_msg_slice~load_coins(); ;; forward_ton_amount 109 | check_either_forward_payload(master_msg_slice); ;; either_forward_payload 110 | 111 | ;; a little more than needed, it’s ok since it’s sent by the admin and excesses will return back 112 | check_amount_is_enough_to_transfer(ton_amount, forward_ton_amount, fwd_fee); 113 | 114 | send_to_jetton_wallet(to_address, jetton_wallet_code, ton_amount, master_msg, TRUE); 115 | save_data(total_supply + jetton_amount, admin_address, next_admin_address, jetton_wallet_code, metadata_uri); 116 | return (); 117 | } 118 | 119 | if (op == op::burn_notification) { ;; 0x7bdd97de 120 | ;; see burn_notification TL-B layout in jetton.tlb 121 | int jetton_amount = in_msg_body~load_coins(); 122 | slice from_address = in_msg_body~load_msg_addr(); 123 | throw_unless(error::not_valid_wallet, 124 | equal_slices_bits(calculate_user_jetton_wallet_address(from_address, my_address(), jetton_wallet_code), sender_address) 125 | ); 126 | save_data(total_supply - jetton_amount, admin_address, next_admin_address, jetton_wallet_code, metadata_uri); 127 | 128 | slice response_address = in_msg_body~load_msg_addr(); 129 | in_msg_body.end_parse(); 130 | 131 | if (~ is_address_none(response_address)) { 132 | ;; build MessageRelaxed, see TL-B layout in stdlib.fc#L733 133 | var msg = begin_cell() 134 | .store_msg_flags_and_address_none(NON_BOUNCEABLE) 135 | .store_slice(response_address) ;; dest 136 | .store_coins(0) 137 | .store_prefix_only_body() 138 | .store_op(op::excesses) 139 | .store_query_id(query_id); 140 | 141 | send_raw_message( 142 | msg.end_cell(), 143 | SEND_MODE_IGNORE_ERRORS | SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE 144 | ); 145 | } 146 | return (); 147 | } 148 | 149 | if (op == op::provide_wallet_address) { ;; 0x2c76b973 150 | ;; see provide_wallet_address TL-B layout in jetton.tlb 151 | slice owner_address = in_msg_body~load_msg_addr(); 152 | int include_address? = in_msg_body~load_bool(); 153 | in_msg_body.end_parse(); 154 | 155 | cell included_address = include_address? 156 | ? begin_cell().store_slice(owner_address).end_cell() 157 | : null(); 158 | 159 | ;; build MessageRelaxed, see TL-B layout in stdlib.fc#L733 160 | var msg = begin_cell() 161 | .store_msg_flags_and_address_none(NON_BOUNCEABLE) 162 | .store_slice(sender_address) 163 | .store_coins(0) 164 | .store_prefix_only_body() 165 | .store_op(op::take_wallet_address) 166 | .store_query_id(query_id); 167 | 168 | if (is_same_workchain(owner_address)) { 169 | msg = msg.store_slice(calculate_user_jetton_wallet_address(owner_address, my_address(), jetton_wallet_code)); 170 | } else { 171 | msg = msg.store_address_none(); 172 | } 173 | 174 | cell msg_cell = msg.store_maybe_ref(included_address).end_cell(); 175 | 176 | send_raw_message(msg_cell, SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE | SEND_MODE_BOUNCE_ON_ACTION_FAIL); 177 | return (); 178 | } 179 | 180 | if (op == op::change_admin) { ;; 0x6501f354 181 | throw_unless(error::not_owner, equal_slices_bits(sender_address, admin_address)); 182 | next_admin_address = in_msg_body~load_msg_addr(); 183 | in_msg_body.end_parse(); 184 | save_data(total_supply, admin_address, next_admin_address, jetton_wallet_code, metadata_uri); 185 | return (); 186 | } 187 | 188 | if (op == op::claim_admin) { ;; 0xfb88e119 189 | in_msg_body.end_parse(); 190 | throw_unless(error::not_owner, equal_slices_bits(sender_address, next_admin_address)); 191 | save_data(total_supply, next_admin_address, address_none(), jetton_wallet_code, metadata_uri); 192 | return (); 193 | } 194 | 195 | ;; can be used to lock, unlock or reedem funds 196 | if (op == op::call_to) { ;; 0x235caf52 197 | throw_unless(error::not_owner, equal_slices_bits(sender_address, admin_address)); 198 | 199 | ;; read the in-message body info 200 | slice to_address = in_msg_body~load_msg_addr(); 201 | int ton_amount = in_msg_body~load_coins(); 202 | cell master_msg = in_msg_body~load_ref(); 203 | in_msg_body.end_parse(); 204 | 205 | slice master_msg_slice = master_msg.begin_parse(); 206 | int master_op = master_msg_slice~load_op(); 207 | master_msg_slice~skip_query_id(); 208 | 209 | ;; parse-validate messages 210 | if (master_op == op::transfer) { 211 | ;; see transfer TL-B layout in jetton.tlb 212 | master_msg_slice~load_coins(); ;; jetton_amount 213 | master_msg_slice~load_msg_addr(); ;; to_owner_address 214 | master_msg_slice~load_msg_addr(); ;; response_address 215 | master_msg_slice~skip_maybe_ref(); ;; custom_payload 216 | int forward_ton_amount = master_msg_slice~load_coins(); ;; forward_ton_amount 217 | check_either_forward_payload(master_msg_slice); ;; either_forward_payload 218 | 219 | check_amount_is_enough_to_transfer(ton_amount, forward_ton_amount, fwd_fee); 220 | 221 | } elseif (master_op == op::burn) { 222 | ;; see burn TL-B layout in jetton.tlb 223 | master_msg_slice~load_coins(); ;; jetton_amount 224 | master_msg_slice~load_msg_addr(); ;; response_address 225 | master_msg_slice~skip_maybe_ref(); ;; custom_payload 226 | master_msg_slice.end_parse(); 227 | 228 | check_amount_is_enough_to_burn(ton_amount); 229 | 230 | } elseif (master_op == op::set_status) { 231 | master_msg_slice~load_uint(STATUS_SIZE); ;; status 232 | master_msg_slice.end_parse(); 233 | } else { 234 | throw(error::invalid_op); 235 | } 236 | send_to_jetton_wallet(to_address, jetton_wallet_code, ton_amount, master_msg, FALSE); 237 | return (); 238 | } 239 | 240 | if (op == op::change_metadata_uri) { ;; 0xcb862902 241 | throw_unless(error::not_owner, equal_slices_bits(sender_address, admin_address)); 242 | save_data(total_supply, admin_address, next_admin_address, jetton_wallet_code, begin_cell().store_slice(in_msg_body).end_cell()); 243 | return (); 244 | } 245 | 246 | if (op == op::upgrade) { ;; 0x2508d66a 247 | throw_unless(error::not_owner, equal_slices_bits(sender_address, admin_address)); 248 | (cell new_data, cell new_code) = (in_msg_body~load_ref(), in_msg_body~load_ref()); 249 | in_msg_body.end_parse(); 250 | set_data(new_data); 251 | set_code(new_code); 252 | return (); 253 | } 254 | 255 | if (op == op::top_up) { ;; 0xd372158c 256 | return (); ;; just accept tons 257 | } 258 | 259 | throw(error::wrong_op); 260 | } 261 | 262 | cell build_content_cell(slice metadata_uri) inline { 263 | cell content_dict = new_dict(); 264 | content_dict~set_token_snake_metadata_entry("uri"H, metadata_uri); 265 | 266 | content_dict~set_token_snake_metadata_entry("decimals"H, "6"); 267 | return create_token_onchain_metadata(content_dict); 268 | } 269 | 270 | 271 | {- 272 | --- Get Method --- 273 | -} 274 | (int, int, slice, cell, cell) get_jetton_data() method_id { 275 | (int total_supply, slice admin_address, slice next_admin_address, cell jetton_wallet_code, cell metadata_uri) = load_data(); 276 | return ( 277 | total_supply, ;; total_supply 278 | TRUE, ;; mintable 279 | admin_address, ;; admin_address 280 | build_content_cell(metadata_uri.begin_parse()), ;; jetton_content 281 | jetton_wallet_code ;; jetton_wallet_code 282 | ); 283 | } 284 | 285 | slice get_wallet_address(slice owner_address) method_id { 286 | (int total_supply, slice admin_address, slice next_admin_address, cell jetton_wallet_code, cell metadata_uri) = load_data(); 287 | return calculate_user_jetton_wallet_address(owner_address, my_address(), jetton_wallet_code); 288 | } 289 | 290 | slice get_next_admin_address() method_id { 291 | (int total_supply, slice admin_address, slice next_admin_address, cell jetton_wallet_code, cell metadata_uri) = load_data(); 292 | return next_admin_address; 293 | } -------------------------------------------------------------------------------- /contracts/imports/stdlib.fc: -------------------------------------------------------------------------------- 1 | ;; Standard library for funC 2 | ;; 3 | 4 | {- 5 | This file is part of TON FunC Standard Library. 6 | 7 | FunC Standard Library is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU Lesser General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | FunC Standard Library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU Lesser General Public License for more details. 16 | 17 | -} 18 | 19 | {- 20 | # Tuple manipulation primitives 21 | The names and the types are mostly self-explaining. 22 | See [polymorhism with forall](https://ton.org/docs/#/func/functions?id=polymorphism-with-forall) 23 | for more info on the polymorphic functions. 24 | 25 | Note that currently values of atomic type `tuple` can't be cast to composite tuple type (e.g. `[int, cell]`) 26 | and vise versa. 27 | -} 28 | 29 | {- 30 | # Lisp-style lists 31 | 32 | Lists can be represented as nested 2-elements tuples. 33 | Empty list is conventionally represented as TVM `null` value (it can be obtained by calling [null()]). 34 | For example, tuple `(1, (2, (3, null)))` represents list `[1, 2, 3]`. Elements of a list can be of different types. 35 | -} 36 | 37 | ;;; Adds an element to the beginning of lisp-style list. 38 | forall X -> tuple cons(X head, tuple tail) asm "CONS"; 39 | 40 | ;;; Extracts the head and the tail of lisp-style list. 41 | forall X -> (X, tuple) uncons(tuple list) asm "UNCONS"; 42 | 43 | ;;; Extracts the tail and the head of lisp-style list. 44 | forall X -> (tuple, X) list_next(tuple list) asm(-> 1 0) "UNCONS"; 45 | 46 | ;;; Returns the head of lisp-style list. 47 | forall X -> X car(tuple list) asm "CAR"; 48 | 49 | ;;; Returns the tail of lisp-style list. 50 | tuple cdr(tuple list) asm "CDR"; 51 | 52 | ;;; Creates tuple with zero elements. 53 | tuple empty_tuple() asm "NIL"; 54 | 55 | ;;; Appends a value `x` to a `Tuple t = (x1, ..., xn)`, but only if the resulting `Tuple t' = (x1, ..., xn, x)` 56 | ;;; is of length at most 255. Otherwise throws a type check exception. 57 | forall X -> tuple tpush(tuple t, X value) asm "TPUSH"; 58 | forall X -> (tuple, ()) ~tpush(tuple t, X value) asm "TPUSH"; 59 | 60 | ;;; Creates a tuple of length one with given argument as element. 61 | forall X -> [X] single(X x) asm "SINGLE"; 62 | 63 | ;;; Unpacks a tuple of length one 64 | forall X -> X unsingle([X] t) asm "UNSINGLE"; 65 | 66 | ;;; Creates a tuple of length two with given arguments as elements. 67 | forall X, Y -> [X, Y] pair(X x, Y y) asm "PAIR"; 68 | 69 | ;;; Unpacks a tuple of length two 70 | forall X, Y -> (X, Y) unpair([X, Y] t) asm "UNPAIR"; 71 | 72 | ;;; Creates a tuple of length three with given arguments as elements. 73 | forall X, Y, Z -> [X, Y, Z] triple(X x, Y y, Z z) asm "TRIPLE"; 74 | 75 | ;;; Unpacks a tuple of length three 76 | forall X, Y, Z -> (X, Y, Z) untriple([X, Y, Z] t) asm "UNTRIPLE"; 77 | 78 | ;;; Creates a tuple of length four with given arguments as elements. 79 | forall X, Y, Z, W -> [X, Y, Z, W] tuple4(X x, Y y, Z z, W w) asm "4 TUPLE"; 80 | 81 | ;;; Unpacks a tuple of length four 82 | forall X, Y, Z, W -> (X, Y, Z, W) untuple4([X, Y, Z, W] t) asm "4 UNTUPLE"; 83 | 84 | ;;; Returns the first element of a tuple (with unknown element types). 85 | forall X -> X first(tuple t) asm "FIRST"; 86 | 87 | ;;; Returns the second element of a tuple (with unknown element types). 88 | forall X -> X second(tuple t) asm "SECOND"; 89 | 90 | ;;; Returns the third element of a tuple (with unknown element types). 91 | forall X -> X third(tuple t) asm "THIRD"; 92 | 93 | ;;; Returns the fourth element of a tuple (with unknown element types). 94 | forall X -> X fourth(tuple t) asm "3 INDEX"; 95 | 96 | ;;; Returns the first element of a pair tuple. 97 | forall X, Y -> X pair_first([X, Y] p) asm "FIRST"; 98 | 99 | ;;; Returns the second element of a pair tuple. 100 | forall X, Y -> Y pair_second([X, Y] p) asm "SECOND"; 101 | 102 | ;;; Returns the first element of a triple tuple. 103 | forall X, Y, Z -> X triple_first([X, Y, Z] p) asm "FIRST"; 104 | 105 | ;;; Returns the second element of a triple tuple. 106 | forall X, Y, Z -> Y triple_second([X, Y, Z] p) asm "SECOND"; 107 | 108 | ;;; Returns the third element of a triple tuple. 109 | forall X, Y, Z -> Z triple_third([X, Y, Z] p) asm "THIRD"; 110 | 111 | 112 | ;;; Push null element (casted to given type) 113 | ;;; By the TVM type `Null` FunC represents absence of a value of some atomic type. 114 | ;;; So `null` can actually have any atomic type. 115 | forall X -> X null() asm "PUSHNULL"; 116 | 117 | ;;; Moves a variable [x] to the top of the stack 118 | forall X -> (X, ()) ~impure_touch(X x) impure asm "NOP"; 119 | 120 | 121 | 122 | ;;; Returns the current Unix time as an Integer 123 | int now() asm "NOW"; 124 | 125 | ;;; Returns the internal address of the current smart contract as a Slice with a `MsgAddressInt`. 126 | ;;; If necessary, it can be parsed further using primitives such as [parse_std_addr]. 127 | slice my_address() asm "MYADDR"; 128 | 129 | ;;; Returns the balance of the smart contract as a tuple consisting of an int 130 | ;;; (balance in nanotoncoins) and a `cell` 131 | ;;; (a dictionary with 32-bit keys representing the balance of "extra currencies") 132 | ;;; at the start of Computation Phase. 133 | ;;; Note that RAW primitives such as [send_raw_message] do not update this field. 134 | [int, cell] get_balance() asm "BALANCE"; 135 | 136 | ;;; Returns the logical time of the current transaction. 137 | int cur_lt() asm "LTIME"; 138 | 139 | ;;; Returns the starting logical time of the current block. 140 | int block_lt() asm "BLOCKLT"; 141 | 142 | ;;; Computes the representation hash of a `cell` [c] and returns it as a 256-bit unsigned integer `x`. 143 | ;;; Useful for signing and checking signatures of arbitrary entities represented by a tree of cells. 144 | int cell_hash(cell c) asm "HASHCU"; 145 | 146 | ;;; Computes the hash of a `slice s` and returns it as a 256-bit unsigned integer `x`. 147 | ;;; The result is the same as if an ordinary cell containing only data and references from `s` had been created 148 | ;;; and its hash computed by [cell_hash]. 149 | int slice_hash(slice s) asm "HASHSU"; 150 | 151 | ;;; Computes sha256 of the data bits of `slice` [s]. If the bit length of `s` is not divisible by eight, 152 | ;;; throws a cell underflow exception. The hash value is returned as a 256-bit unsigned integer `x`. 153 | int string_hash(slice s) asm "SHA256U"; 154 | 155 | {- 156 | # Signature checks 157 | -} 158 | 159 | ;;; Checks the Ed25519-`signature` of a `hash` (a 256-bit unsigned integer, usually computed as the hash of some data) 160 | ;;; using [public_key] (also represented by a 256-bit unsigned integer). 161 | ;;; The signature must contain at least 512 data bits; only the first 512 bits are used. 162 | ;;; The result is `−1` if the signature is valid, `0` otherwise. 163 | ;;; Note that `CHKSIGNU` creates a 256-bit slice with the hash and calls `CHKSIGNS`. 164 | ;;; That is, if [hash] is computed as the hash of some data, these data are hashed twice, 165 | ;;; the second hashing occurring inside `CHKSIGNS`. 166 | int check_signature(int hash, slice signature, int public_key) asm "CHKSIGNU"; 167 | 168 | ;;; Checks whether [signature] is a valid Ed25519-signature of the data portion of `slice data` using `public_key`, 169 | ;;; similarly to [check_signature]. 170 | ;;; If the bit length of [data] is not divisible by eight, throws a cell underflow exception. 171 | ;;; The verification of Ed25519 signatures is the standard one, 172 | ;;; with sha256 used to reduce [data] to the 256-bit number that is actually signed. 173 | int check_data_signature(slice data, slice signature, int public_key) asm "CHKSIGNS"; 174 | 175 | {--- 176 | # Computation of boc size 177 | The primitives below may be useful for computing storage fees of user-provided data. 178 | -} 179 | 180 | ;;; Returns `(x, y, z, -1)` or `(null, null, null, 0)`. 181 | ;;; Recursively computes the count of distinct cells `x`, data bits `y`, and cell references `z` 182 | ;;; in the DAG rooted at `cell` [c], effectively returning the total storage used by this DAG taking into account 183 | ;;; the identification of equal cells. 184 | ;;; The values of `x`, `y`, and `z` are computed by a depth-first traversal of this DAG, 185 | ;;; with a hash table of visited cell hashes used to prevent visits of already-visited cells. 186 | ;;; The total count of visited cells `x` cannot exceed non-negative [max_cells]; 187 | ;;; otherwise the computation is aborted before visiting the `(max_cells + 1)`-st cell and 188 | ;;; a zero flag is returned to indicate failure. If [c] is `null`, returns `x = y = z = 0`. 189 | (int, int, int) compute_data_size(cell c, int max_cells) impure asm "CDATASIZE"; 190 | 191 | ;;; Similar to [compute_data_size?], but accepting a `slice` [s] instead of a `cell`. 192 | ;;; The returned value of `x` does not take into account the cell that contains the `slice` [s] itself; 193 | ;;; however, the data bits and the cell references of [s] are accounted for in `y` and `z`. 194 | (int, int, int) slice_compute_data_size(slice s, int max_cells) impure asm "SDATASIZE"; 195 | 196 | ;;; A non-quiet version of [compute_data_size?] that throws a cell overflow exception (`8`) on failure. 197 | (int, int, int, int) compute_data_size?(cell c, int max_cells) asm "CDATASIZEQ NULLSWAPIFNOT2 NULLSWAPIFNOT"; 198 | 199 | ;;; A non-quiet version of [slice_compute_data_size?] that throws a cell overflow exception (8) on failure. 200 | (int, int, int, int) slice_compute_data_size?(cell c, int max_cells) asm "SDATASIZEQ NULLSWAPIFNOT2 NULLSWAPIFNOT"; 201 | 202 | ;;; Throws an exception with exit_code excno if cond is not 0 (commented since implemented in compilator) 203 | ;; () throw_if(int excno, int cond) impure asm "THROWARGIF"; 204 | 205 | {-- 206 | # Debug primitives 207 | Only works for local TVM execution with debug level verbosity 208 | -} 209 | ;;; Dumps the stack (at most the top 255 values) and shows the total stack depth. 210 | () dump_stack() impure asm "DUMPSTK"; 211 | 212 | {- 213 | # Persistent storage save and load 214 | -} 215 | 216 | ;;; Returns the persistent contract storage cell. It can be parsed or modified with slice and builder primitives later. 217 | cell get_data() asm "c4 PUSH"; 218 | 219 | ;;; Sets `cell` [c] as persistent contract data. You can update persistent contract storage with this primitive. 220 | () set_data(cell c) impure asm "c4 POP"; 221 | 222 | {- 223 | # Continuation primitives 224 | -} 225 | ;;; Usually `c3` has a continuation initialized by the whole code of the contract. It is used for function calls. 226 | ;;; The primitive returns the current value of `c3`. 227 | cont get_c3() impure asm "c3 PUSH"; 228 | 229 | ;;; Updates the current value of `c3`. Usually, it is used for updating smart contract code in run-time. 230 | ;;; Note that after execution of this primitive the current code 231 | ;;; (and the stack of recursive function calls) won't change, 232 | ;;; but any other function call will use a function from the new code. 233 | () set_c3(cont c) impure asm "c3 POP"; 234 | 235 | ;;; Transforms a `slice` [s] into a simple ordinary continuation `c`, with `c.code = s` and an empty stack and savelist. 236 | cont bless(slice s) impure asm "BLESS"; 237 | 238 | {--- 239 | # Gas related primitives 240 | -} 241 | 242 | ;;; Sets current gas limit `gl` to its maximal allowed value `gm`, and resets the gas credit `gc` to zero, 243 | ;;; decreasing the value of `gr` by `gc` in the process. 244 | ;;; In other words, the current smart contract agrees to buy some gas to finish the current transaction. 245 | ;;; This action is required to process external messages, which bring no value (hence no gas) with themselves. 246 | ;;; 247 | ;;; For more details check [accept_message effects](https://ton.org/docs/#/smart-contracts/accept). 248 | () accept_message() impure asm "ACCEPT"; 249 | 250 | ;;; Sets current gas limit `gl` to the minimum of limit and `gm`, and resets the gas credit `gc` to zero. 251 | ;;; If the gas consumed so far (including the present instruction) exceeds the resulting value of `gl`, 252 | ;;; an (unhandled) out of gas exception is thrown before setting new gas limits. 253 | ;;; Notice that [set_gas_limit] with an argument `limit ≥ 2^63 − 1` is equivalent to [accept_message]. 254 | () set_gas_limit(int limit) impure asm "SETGASLIMIT"; 255 | 256 | ;;; Commits the current state of registers `c4` (“persistent data”) and `c5` (“actions”) 257 | ;;; so that the current execution is considered “successful” with the saved values even if an exception 258 | ;;; in Computation Phase is thrown later. 259 | () commit() impure asm "COMMIT"; 260 | 261 | ;;; Not implemented 262 | ;;; Computes the amount of gas that can be bought for `amount` nanoTONs, 263 | ;;; and sets `gl` accordingly in the same way as [set_gas_limit]. 264 | ;;() buy_gas(int amount) impure asm "BUYGAS"; 265 | 266 | ;;; Computes the minimum of two integers [x] and [y]. 267 | int min(int x, int y) asm "MIN"; 268 | 269 | ;;; Computes the maximum of two integers [x] and [y]. 270 | int max(int x, int y) asm "MAX"; 271 | 272 | ;;; Sorts two integers. 273 | (int, int) minmax(int x, int y) asm "MINMAX"; 274 | 275 | ;;; Computes the absolute value of an integer [x]. 276 | int abs(int x) asm "ABS"; 277 | 278 | {- 279 | # Slice primitives 280 | 281 | It is said that a primitive _loads_ some data, 282 | if it returns the data and the remainder of the slice 283 | (so it can also be used as [modifying method](https://ton.org/docs/#/func/statements?id=modifying-methods)). 284 | 285 | It is said that a primitive _preloads_ some data, if it returns only the data 286 | (it can be used as [non-modifying method](https://ton.org/docs/#/func/statements?id=non-modifying-methods)). 287 | 288 | Unless otherwise stated, loading and preloading primitives read the data from a prefix of the slice. 289 | -} 290 | 291 | 292 | ;;; Converts a `cell` [c] into a `slice`. Notice that [c] must be either an ordinary cell, 293 | ;;; or an exotic cell (see [TVM.pdf](https://ton-blockchain.github.io/docs/tvm.pdf), 3.1.2) 294 | ;;; which is automatically loaded to yield an ordinary cell `c'`, converted into a `slice` afterwards. 295 | slice begin_parse(cell c) asm "CTOS"; 296 | 297 | ;;; Checks if [s] is empty. If not, throws an exception. 298 | () end_parse(slice s) impure asm "ENDS"; 299 | 300 | ;;; Loads the first reference from the slice. 301 | (slice, cell) load_ref(slice s) asm(-> 1 0) "LDREF"; 302 | 303 | ;;; Preloads the first reference from the slice. 304 | cell preload_ref(slice s) asm "PLDREF"; 305 | 306 | {- Functions below are commented because are implemented on compilator level for optimisation -} 307 | 308 | ;;; Loads a signed [len]-bit integer from a slice [s]. 309 | ;; (slice, int) ~load_int(slice s, int len) asm(s len -> 1 0) "LDIX"; 310 | 311 | ;;; Loads an unsigned [len]-bit integer from a slice [s]. 312 | ;; (slice, int) ~load_uint(slice s, int len) asm( -> 1 0) "LDUX"; 313 | 314 | ;;; Preloads a signed [len]-bit integer from a slice [s]. 315 | ;; int preload_int(slice s, int len) asm "PLDIX"; 316 | 317 | ;;; Preloads an unsigned [len]-bit integer from a slice [s]. 318 | ;; int preload_uint(slice s, int len) asm "PLDUX"; 319 | 320 | ;;; Loads the first `0 ≤ len ≤ 1023` bits from slice [s] into a separate `slice s''`. 321 | ;; (slice, slice) load_bits(slice s, int len) asm(s len -> 1 0) "LDSLICEX"; 322 | 323 | ;;; Preloads the first `0 ≤ len ≤ 1023` bits from slice [s] into a separate `slice s''`. 324 | ;; slice preload_bits(slice s, int len) asm "PLDSLICEX"; 325 | 326 | ;;; Loads serialized amount of TonCoins (any unsigned integer up to `2^128 - 1`). 327 | (slice, int) load_grams(slice s) asm(-> 1 0) "LDGRAMS"; 328 | (slice, int) load_coins(slice s) asm(-> 1 0) "LDVARUINT16"; 329 | 330 | ;;; Returns all but the first `0 ≤ len ≤ 1023` bits of `slice` [s]. 331 | slice skip_bits(slice s, int len) asm "SDSKIPFIRST"; 332 | (slice, ()) ~skip_bits(slice s, int len) asm "SDSKIPFIRST"; 333 | 334 | ;;; Returns the first `0 ≤ len ≤ 1023` bits of `slice` [s]. 335 | slice first_bits(slice s, int len) asm "SDCUTFIRST"; 336 | 337 | ;;; Returns all but the last `0 ≤ len ≤ 1023` bits of `slice` [s]. 338 | slice skip_last_bits(slice s, int len) asm "SDSKIPLAST"; 339 | (slice, ()) ~skip_last_bits(slice s, int len) asm "SDSKIPLAST"; 340 | 341 | ;;; Returns the last `0 ≤ len ≤ 1023` bits of `slice` [s]. 342 | slice slice_last(slice s, int len) asm "SDCUTLAST"; 343 | 344 | ;;; Loads a dictionary `D` (HashMapE) from `slice` [s]. 345 | ;;; (returns `null` if `nothing` constructor is used). 346 | (slice, cell) load_dict(slice s) asm(-> 1 0) "LDDICT"; 347 | 348 | ;;; Preloads a dictionary `D` from `slice` [s]. 349 | cell preload_dict(slice s) asm "PLDDICT"; 350 | 351 | ;;; Loads a dictionary as [load_dict], but returns only the remainder of the slice. 352 | slice skip_dict(slice s) asm "SKIPDICT"; 353 | (slice, ()) ~skip_dict(slice s) asm "SKIPDICT"; 354 | 355 | ;;; Loads (Maybe ^Cell) from `slice` [s]. 356 | ;;; In other words loads 1 bit and if it is true 357 | ;;; loads first ref and return it with slice remainder 358 | ;;; otherwise returns `null` and slice remainder 359 | (slice, cell) load_maybe_ref(slice s) asm(-> 1 0) "LDOPTREF"; 360 | 361 | ;;; Preloads (Maybe ^Cell) from `slice` [s]. 362 | cell preload_maybe_ref(slice s) asm "PLDOPTREF"; 363 | 364 | 365 | ;;; Returns the depth of `cell` [c]. 366 | ;;; If [c] has no references, then return `0`; 367 | ;;; otherwise the returned value is one plus the maximum of depths of cells referred to from [c]. 368 | ;;; If [c] is a `null` instead of a cell, returns zero. 369 | int cell_depth(cell c) asm "CDEPTH"; 370 | 371 | 372 | {- 373 | # Slice size primitives 374 | -} 375 | 376 | ;;; Returns the number of references in `slice` [s]. 377 | int slice_refs(slice s) asm "SREFS"; 378 | 379 | ;;; Returns the number of data bits in `slice` [s]. 380 | int slice_bits(slice s) asm "SBITS"; 381 | 382 | ;;; Returns both the number of data bits and the number of references in `slice` [s]. 383 | (int, int) slice_bits_refs(slice s) asm "SBITREFS"; 384 | 385 | ;;; Checks whether a `slice` [s] is empty (i.e., contains no bits of data and no cell references). 386 | int slice_empty?(slice s) asm "SEMPTY"; 387 | 388 | ;;; Checks whether `slice` [s] has no bits of data. 389 | int slice_data_empty?(slice s) asm "SDEMPTY"; 390 | 391 | ;;; Checks whether `slice` [s] has no references. 392 | int slice_refs_empty?(slice s) asm "SREMPTY"; 393 | 394 | ;;; Returns the depth of `slice` [s]. 395 | ;;; If [s] has no references, then returns `0`; 396 | ;;; otherwise the returned value is one plus the maximum of depths of cells referred to from [s]. 397 | int slice_depth(slice s) asm "SDEPTH"; 398 | 399 | {- 400 | # Builder size primitives 401 | -} 402 | 403 | ;;; Returns the number of cell references already stored in `builder` [b] 404 | int builder_refs(builder b) asm "BREFS"; 405 | 406 | ;;; Returns the number of data bits already stored in `builder` [b]. 407 | int builder_bits(builder b) asm "BBITS"; 408 | 409 | ;;; Returns the depth of `builder` [b]. 410 | ;;; If no cell references are stored in [b], then returns 0; 411 | ;;; otherwise the returned value is one plus the maximum of depths of cells referred to from [b]. 412 | int builder_depth(builder b) asm "BDEPTH"; 413 | 414 | {- 415 | # Builder primitives 416 | It is said that a primitive _stores_ a value `x` into a builder `b` 417 | if it returns a modified version of the builder `b'` with the value `x` stored at the end of it. 418 | It can be used as [non-modifying method](https://ton.org/docs/#/func/statements?id=non-modifying-methods). 419 | 420 | All the primitives below first check whether there is enough space in the `builder`, 421 | and only then check the range of the value being serialized. 422 | -} 423 | 424 | ;;; Creates a new empty `builder`. 425 | builder begin_cell() asm "NEWC"; 426 | 427 | ;;; Converts a `builder` into an ordinary `cell`. 428 | cell end_cell(builder b) asm "ENDC"; 429 | 430 | ;;; Stores a reference to `cell` [c] into `builder` [b]. 431 | builder store_ref(builder b, cell c) asm(c b) "STREF"; 432 | 433 | ;;; Stores an unsigned [len]-bit integer `x` into `b` for `0 ≤ len ≤ 256`. 434 | ;; builder store_uint(builder b, int x, int len) asm(x b len) "STUX"; 435 | 436 | ;;; Stores a signed [len]-bit integer `x` into `b` for` 0 ≤ len ≤ 257`. 437 | ;; builder store_int(builder b, int x, int len) asm(x b len) "STIX"; 438 | 439 | 440 | ;;; Stores `slice` [s] into `builder` [b] 441 | builder store_slice(builder b, slice s) asm "STSLICER"; 442 | 443 | ;;; Stores (serializes) an integer [x] in the range `0..2^128 − 1` into `builder` [b]. 444 | ;;; The serialization of [x] consists of a 4-bit unsigned big-endian integer `l`, 445 | ;;; which is the smallest integer `l ≥ 0`, such that `x < 2^8l`, 446 | ;;; followed by an `8l`-bit unsigned big-endian representation of [x]. 447 | ;;; If [x] does not belong to the supported range, a range check exception is thrown. 448 | ;;; 449 | ;;; Store amounts of TonCoins to the builder as VarUInteger 16 450 | builder store_grams(builder b, int x) asm "STGRAMS"; 451 | builder store_coins(builder b, int x) asm "STVARUINT16"; 452 | 453 | ;;; Stores dictionary `D` represented by `cell` [c] or `null` into `builder` [b]. 454 | ;;; In other words, stores a `1`-bit and a reference to [c] if [c] is not `null` and `0`-bit otherwise. 455 | builder store_dict(builder b, cell c) asm(c b) "STDICT"; 456 | 457 | ;;; Stores (Maybe ^Cell) to builder: 458 | ;;; if cell is null store 1 zero bit 459 | ;;; otherwise store 1 true bit and ref to cell 460 | builder store_maybe_ref(builder b, cell c) asm(c b) "STOPTREF"; 461 | 462 | 463 | {- 464 | # Address manipulation primitives 465 | The address manipulation primitives listed below serialize and deserialize values according to the following TL-B scheme: 466 | ```TL-B 467 | addr_none$00 = MsgAddressExt; 468 | addr_extern$01 len:(## 8) external_address:(bits len) 469 | = MsgAddressExt; 470 | anycast_info$_ depth:(#<= 30) { depth >= 1 } 471 | rewrite_pfx:(bits depth) = Anycast; 472 | addr_std$10 anycast:(Maybe Anycast) 473 | workchain_id:int8 address:bits256 = MsgAddressInt; 474 | addr_var$11 anycast:(Maybe Anycast) addr_len:(## 9) 475 | workchain_id:int32 address:(bits addr_len) = MsgAddressInt; 476 | _ _:MsgAddressInt = MsgAddress; 477 | _ _:MsgAddressExt = MsgAddress; 478 | 479 | int_msg_info$0 ihr_disabled:Bool bounce:Bool bounced:Bool 480 | src:MsgAddress dest:MsgAddressInt 481 | value:CurrencyCollection ihr_fee:Grams fwd_fee:Grams 482 | created_lt:uint64 created_at:uint32 = CommonMsgInfoRelaxed; 483 | ext_out_msg_info$11 src:MsgAddress dest:MsgAddressExt 484 | created_lt:uint64 created_at:uint32 = CommonMsgInfoRelaxed; 485 | ``` 486 | A deserialized `MsgAddress` is represented by a tuple `t` as follows: 487 | 488 | - `addr_none` is represented by `t = (0)`, 489 | i.e., a tuple containing exactly one integer equal to zero. 490 | - `addr_extern` is represented by `t = (1, s)`, 491 | where slice `s` contains the field `external_address`. In other words, ` 492 | t` is a pair (a tuple consisting of two entries), containing an integer equal to one and slice `s`. 493 | - `addr_std` is represented by `t = (2, u, x, s)`, 494 | where `u` is either a `null` (if `anycast` is absent) or a slice `s'` containing `rewrite_pfx` (if anycast is present). 495 | Next, integer `x` is the `workchain_id`, and slice `s` contains the address. 496 | - `addr_var` is represented by `t = (3, u, x, s)`, 497 | where `u`, `x`, and `s` have the same meaning as for `addr_std`. 498 | -} 499 | 500 | ;;; Loads from slice [s] the only prefix that is a valid `MsgAddress`, 501 | ;;; and returns both this prefix `s'` and the remainder `s''` of [s] as slices. 502 | (slice, slice) load_msg_addr(slice s) asm(-> 1 0) "LDMSGADDR"; 503 | 504 | ;;; Decomposes slice [s] containing a valid `MsgAddress` into a `tuple t` with separate fields of this `MsgAddress`. 505 | ;;; If [s] is not a valid `MsgAddress`, a cell deserialization exception is thrown. 506 | tuple parse_addr(slice s) asm "PARSEMSGADDR"; 507 | 508 | ;;; Parses slice [s] containing a valid `MsgAddressInt` (usually a `msg_addr_std`), 509 | ;;; applies rewriting from the anycast (if present) to the same-length prefix of the address, 510 | ;;; and returns both the workchain and the 256-bit address as integers. 511 | ;;; If the address is not 256-bit, or if [s] is not a valid serialization of `MsgAddressInt`, 512 | ;;; throws a cell deserialization exception. 513 | (int, int) parse_std_addr(slice s) asm "REWRITESTDADDR"; 514 | 515 | ;;; A variant of [parse_std_addr] that returns the (rewritten) address as a slice [s], 516 | ;;; even if it is not exactly 256 bit long (represented by a `msg_addr_var`). 517 | (int, slice) parse_var_addr(slice s) asm "REWRITEVARADDR"; 518 | 519 | {- 520 | # Dictionary primitives 521 | -} 522 | 523 | 524 | ;;; Sets the value associated with [key_len]-bit key signed index in dictionary [dict] to [value] (cell), 525 | ;;; and returns the resulting dictionary. 526 | cell idict_set_ref(cell dict, int key_len, int index, cell value) asm(value index dict key_len) "DICTISETREF"; 527 | (cell, ()) ~idict_set_ref(cell dict, int key_len, int index, cell value) asm(value index dict key_len) "DICTISETREF"; 528 | 529 | ;;; Sets the value associated with [key_len]-bit key unsigned index in dictionary [dict] to [value] (cell), 530 | ;;; and returns the resulting dictionary. 531 | cell udict_set_ref(cell dict, int key_len, int index, cell value) asm(value index dict key_len) "DICTUSETREF"; 532 | (cell, ()) ~udict_set_ref(cell dict, int key_len, int index, cell value) asm(value index dict key_len) "DICTUSETREF"; 533 | 534 | cell idict_get_ref(cell dict, int key_len, int index) asm(index dict key_len) "DICTIGETOPTREF"; 535 | (cell, int) idict_get_ref?(cell dict, int key_len, int index) asm(index dict key_len) "DICTIGETREF" "NULLSWAPIFNOT"; 536 | (cell, int) udict_get_ref?(cell dict, int key_len, int index) asm(index dict key_len) "DICTUGETREF" "NULLSWAPIFNOT"; 537 | (cell, cell) idict_set_get_ref(cell dict, int key_len, int index, cell value) asm(value index dict key_len) "DICTISETGETOPTREF"; 538 | (cell, cell) udict_set_get_ref(cell dict, int key_len, int index, cell value) asm(value index dict key_len) "DICTUSETGETOPTREF"; 539 | (cell, int) idict_delete?(cell dict, int key_len, int index) asm(index dict key_len) "DICTIDEL"; 540 | (cell, int) udict_delete?(cell dict, int key_len, int index) asm(index dict key_len) "DICTUDEL"; 541 | (slice, int) idict_get?(cell dict, int key_len, int index) asm(index dict key_len) "DICTIGET" "NULLSWAPIFNOT"; 542 | (slice, int) udict_get?(cell dict, int key_len, int index) asm(index dict key_len) "DICTUGET" "NULLSWAPIFNOT"; 543 | (cell, slice, int) idict_delete_get?(cell dict, int key_len, int index) asm(index dict key_len) "DICTIDELGET" "NULLSWAPIFNOT"; 544 | (cell, slice, int) udict_delete_get?(cell dict, int key_len, int index) asm(index dict key_len) "DICTUDELGET" "NULLSWAPIFNOT"; 545 | (cell, (slice, int)) ~idict_delete_get?(cell dict, int key_len, int index) asm(index dict key_len) "DICTIDELGET" "NULLSWAPIFNOT"; 546 | (cell, (slice, int)) ~udict_delete_get?(cell dict, int key_len, int index) asm(index dict key_len) "DICTUDELGET" "NULLSWAPIFNOT"; 547 | cell udict_set(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTUSET"; 548 | (cell, ()) ~udict_set(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTUSET"; 549 | cell idict_set(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTISET"; 550 | (cell, ()) ~idict_set(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTISET"; 551 | cell dict_set(cell dict, int key_len, slice index, slice value) asm(value index dict key_len) "DICTSET"; 552 | (cell, ()) ~dict_set(cell dict, int key_len, slice index, slice value) asm(value index dict key_len) "DICTSET"; 553 | (cell, int) udict_add?(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTUADD"; 554 | (cell, int) udict_replace?(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTUREPLACE"; 555 | (cell, int) idict_add?(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTIADD"; 556 | (cell, int) idict_replace?(cell dict, int key_len, int index, slice value) asm(value index dict key_len) "DICTIREPLACE"; 557 | cell udict_set_builder(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTUSETB"; 558 | (cell, ()) ~udict_set_builder(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTUSETB"; 559 | cell idict_set_builder(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTISETB"; 560 | (cell, ()) ~idict_set_builder(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTISETB"; 561 | cell dict_set_builder(cell dict, int key_len, slice index, builder value) asm(value index dict key_len) "DICTSETB"; 562 | (cell, ()) ~dict_set_builder(cell dict, int key_len, slice index, builder value) asm(value index dict key_len) "DICTSETB"; 563 | (cell, int) udict_add_builder?(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTUADDB"; 564 | (cell, int) udict_replace_builder?(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTUREPLACEB"; 565 | (cell, int) idict_add_builder?(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTIADDB"; 566 | (cell, int) idict_replace_builder?(cell dict, int key_len, int index, builder value) asm(value index dict key_len) "DICTIREPLACEB"; 567 | (cell, int, slice, int) udict_delete_get_min(cell dict, int key_len) asm(-> 0 2 1 3) "DICTUREMMIN" "NULLSWAPIFNOT2"; 568 | (cell, (int, slice, int)) ~udict::delete_get_min(cell dict, int key_len) asm(-> 0 2 1 3) "DICTUREMMIN" "NULLSWAPIFNOT2"; 569 | (cell, int, slice, int) idict_delete_get_min(cell dict, int key_len) asm(-> 0 2 1 3) "DICTIREMMIN" "NULLSWAPIFNOT2"; 570 | (cell, (int, slice, int)) ~idict::delete_get_min(cell dict, int key_len) asm(-> 0 2 1 3) "DICTIREMMIN" "NULLSWAPIFNOT2"; 571 | (cell, slice, slice, int) dict_delete_get_min(cell dict, int key_len) asm(-> 0 2 1 3) "DICTREMMIN" "NULLSWAPIFNOT2"; 572 | (cell, (slice, slice, int)) ~dict::delete_get_min(cell dict, int key_len) asm(-> 0 2 1 3) "DICTREMMIN" "NULLSWAPIFNOT2"; 573 | (cell, int, slice, int) udict_delete_get_max(cell dict, int key_len) asm(-> 0 2 1 3) "DICTUREMMAX" "NULLSWAPIFNOT2"; 574 | (cell, (int, slice, int)) ~udict::delete_get_max(cell dict, int key_len) asm(-> 0 2 1 3) "DICTUREMMAX" "NULLSWAPIFNOT2"; 575 | (cell, int, slice, int) idict_delete_get_max(cell dict, int key_len) asm(-> 0 2 1 3) "DICTIREMMAX" "NULLSWAPIFNOT2"; 576 | (cell, (int, slice, int)) ~idict::delete_get_max(cell dict, int key_len) asm(-> 0 2 1 3) "DICTIREMMAX" "NULLSWAPIFNOT2"; 577 | (cell, slice, slice, int) dict_delete_get_max(cell dict, int key_len) asm(-> 0 2 1 3) "DICTREMMAX" "NULLSWAPIFNOT2"; 578 | (cell, (slice, slice, int)) ~dict::delete_get_max(cell dict, int key_len) asm(-> 0 2 1 3) "DICTREMMAX" "NULLSWAPIFNOT2"; 579 | (int, slice, int) udict_get_min?(cell dict, int key_len) asm (-> 1 0 2) "DICTUMIN" "NULLSWAPIFNOT2"; 580 | (int, slice, int) udict_get_max?(cell dict, int key_len) asm (-> 1 0 2) "DICTUMAX" "NULLSWAPIFNOT2"; 581 | (int, cell, int) udict_get_min_ref?(cell dict, int key_len) asm (-> 1 0 2) "DICTUMINREF" "NULLSWAPIFNOT2"; 582 | (int, cell, int) udict_get_max_ref?(cell dict, int key_len) asm (-> 1 0 2) "DICTUMAXREF" "NULLSWAPIFNOT2"; 583 | (int, slice, int) idict_get_min?(cell dict, int key_len) asm (-> 1 0 2) "DICTIMIN" "NULLSWAPIFNOT2"; 584 | (int, slice, int) idict_get_max?(cell dict, int key_len) asm (-> 1 0 2) "DICTIMAX" "NULLSWAPIFNOT2"; 585 | (int, cell, int) idict_get_min_ref?(cell dict, int key_len) asm (-> 1 0 2) "DICTIMINREF" "NULLSWAPIFNOT2"; 586 | (int, cell, int) idict_get_max_ref?(cell dict, int key_len) asm (-> 1 0 2) "DICTIMAXREF" "NULLSWAPIFNOT2"; 587 | (int, slice, int) udict_get_next?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTUGETNEXT" "NULLSWAPIFNOT2"; 588 | (int, slice, int) udict_get_nexteq?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTUGETNEXTEQ" "NULLSWAPIFNOT2"; 589 | (int, slice, int) udict_get_prev?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTUGETPREV" "NULLSWAPIFNOT2"; 590 | (int, slice, int) udict_get_preveq?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTUGETPREVEQ" "NULLSWAPIFNOT2"; 591 | (int, slice, int) idict_get_next?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTIGETNEXT" "NULLSWAPIFNOT2"; 592 | (int, slice, int) idict_get_nexteq?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTIGETNEXTEQ" "NULLSWAPIFNOT2"; 593 | (int, slice, int) idict_get_prev?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTIGETPREV" "NULLSWAPIFNOT2"; 594 | (int, slice, int) idict_get_preveq?(cell dict, int key_len, int pivot) asm(pivot dict key_len -> 1 0 2) "DICTIGETPREVEQ" "NULLSWAPIFNOT2"; 595 | 596 | ;;; Creates an empty dictionary, which is actually a null value. Equivalent to PUSHNULL 597 | cell new_dict() asm "NEWDICT"; 598 | ;;; Checks whether a dictionary is empty. Equivalent to cell_null?. 599 | int dict_empty?(cell c) asm "DICTEMPTY"; 600 | 601 | 602 | {- Prefix dictionary primitives -} 603 | (slice, slice, slice, int) pfxdict_get?(cell dict, int key_len, slice key) asm(key dict key_len) "PFXDICTGETQ" "NULLSWAPIFNOT2"; 604 | (cell, int) pfxdict_set?(cell dict, int key_len, slice key, slice value) asm(value key dict key_len) "PFXDICTSET"; 605 | (cell, int) pfxdict_delete?(cell dict, int key_len, slice key) asm(key dict key_len) "PFXDICTDEL"; 606 | 607 | ;;; Returns the value of the global configuration parameter with integer index `i` as a `cell` or `null` value. 608 | cell config_param(int x) asm "CONFIGOPTPARAM"; 609 | ;;; Checks whether c is a null. Note, that FunC also has polymorphic null? built-in. 610 | int cell_null?(cell c) asm "ISNULL"; 611 | 612 | ;;; Creates an output action which would reserve exactly amount nanotoncoins (if mode = 0), at most amount nanotoncoins (if mode = 2), or all but amount nanotoncoins (if mode = 1 or mode = 3), from the remaining balance of the account. It is roughly equivalent to creating an outbound message carrying amount nanotoncoins (or b − amount nanotoncoins, where b is the remaining balance) to oneself, so that the subsequent output actions would not be able to spend more money than the remainder. Bit +2 in mode means that the external action does not fail if the specified amount cannot be reserved; instead, all remaining balance is reserved. Bit +8 in mode means `amount <- -amount` before performing any further actions. Bit +4 in mode means that amount is increased by the original balance of the current account (before the compute phase), including all extra currencies, before performing any other checks and actions. Currently, amount must be a non-negative integer, and mode must be in the range 0..15. 613 | () raw_reserve(int amount, int mode) impure asm "RAWRESERVE"; 614 | ;;; Similar to raw_reserve, but also accepts a dictionary extra_amount (represented by a cell or null) with extra currencies. In this way currencies other than TonCoin can be reserved. 615 | () raw_reserve_extra(int amount, cell extra_amount, int mode) impure asm "RAWRESERVEX"; 616 | ;;; Sends a raw message contained in msg, which should contain a correctly serialized object Message X, with the only exception that the source address is allowed to have dummy value addr_none (to be automatically replaced with the current smart contract address), and ihr_fee, fwd_fee, created_lt and created_at fields can have arbitrary values (to be rewritten with correct values during the action phase of the current transaction). Integer parameter mode contains the flags. Currently mode = 0 is used for ordinary messages; mode = 128 is used for messages that are to carry all the remaining balance of the current smart contract (instead of the value originally indicated in the message); mode = 64 is used for messages that carry all the remaining value of the inbound message in addition to the value initially indicated in the new message (if bit 0 is not set, the gas fees are deducted from this amount); mode' = mode + 1 means that the sender wants to pay transfer fees separately; mode' = mode + 2 means that any errors arising while processing this message during the action phase should be ignored. Finally, mode' = mode + 32 means that the current account must be destroyed if its resulting balance is zero. This flag is usually employed together with +128. 617 | () send_raw_message(cell msg, int mode) impure asm "SENDRAWMSG"; 618 | ;;; Creates an output action that would change this smart contract code to that given by cell new_code. Notice that this change will take effect only after the successful termination of the current run of the smart contract 619 | () set_code(cell new_code) impure asm "SETCODE"; 620 | 621 | ;;; Generates a new pseudo-random unsigned 256-bit integer x. The algorithm is as follows: if r is the old value of the random seed, considered as a 32-byte array (by constructing the big-endian representation of an unsigned 256-bit integer), then its sha512(r) is computed; the first 32 bytes of this hash are stored as the new value r' of the random seed, and the remaining 32 bytes are returned as the next random value x. 622 | int random() impure asm "RANDU256"; 623 | ;;; Generates a new pseudo-random integer z in the range 0..range−1 (or range..−1, if range < 0). More precisely, an unsigned random value x is generated as in random; then z := x * range / 2^256 is computed. 624 | int rand(int range) impure asm "RAND"; 625 | ;;; Returns the current random seed as an unsigned 256-bit Integer. 626 | int get_seed() impure asm "RANDSEED"; 627 | ;;; Sets the random seed to unsigned 256-bit seed. 628 | () set_seed(int x) impure asm "SETRAND"; 629 | ;;; Mixes unsigned 256-bit integer x into the random seed r by setting the random seed to sha256 of the concatenation of two 32-byte strings: the first with the big-endian representation of the old seed r, and the second with the big-endian representation of x. 630 | () randomize(int x) impure asm "ADDRAND"; 631 | ;;; Equivalent to randomize(cur_lt());. 632 | () randomize_lt() impure asm "LTIME" "ADDRAND"; 633 | 634 | ;;; Checks whether the data parts of two slices coinside 635 | int equal_slices_bits(slice a, slice b) asm "SDEQ"; 636 | ;;; Checks whether b is a null. Note, that FunC also has polymorphic null? built-in. 637 | int builder_null?(builder b) asm "ISNULL"; 638 | ;;; Concatenates two builders 639 | builder store_builder(builder to, builder from) asm "STBR"; 640 | 641 | ;; CUSTOM: 642 | 643 | ;; TVM UPGRADE 2023-07 https://docs.ton.org/learn/tvm-instructions/tvm-upgrade-2023-07 644 | ;; In mainnet since 20 Dec 2023 https://t.me/tonblockchain/226 645 | 646 | ;;; Retrieves code of smart-contract from c7 647 | cell my_code() asm "MYCODE"; 648 | 649 | ;;; Creates an output action and returns a fee for creating a message. Mode has the same effect as in the case of SENDRAWMSG 650 | int send_message(cell msg, int mode) impure asm "SENDMSG"; 651 | 652 | ;; TVM V6 https://github.com/ton-blockchain/ton/blob/testnet/doc/GlobalVersions.md#version-6 653 | int get_compute_fee(int workchain, int gas_used) asm(gas_used workchain) "GETGASFEE"; 654 | int get_storage_fee(int workchain, int seconds, int bits, int cells) asm(cells bits seconds workchain) "GETSTORAGEFEE"; 655 | int get_forward_fee(int workchain, int bits, int cells) asm(cells bits workchain) "GETFORWARDFEE"; 656 | int get_precompiled_gas_consumption() asm "GETPRECOMPILEDGAS"; 657 | 658 | int get_simple_compute_fee(int workchain, int gas_used) asm(gas_used workchain) "GETGASFEESIMPLE"; 659 | int get_simple_forward_fee(int workchain, int bits, int cells) asm(cells bits workchain) "GETFORWARDFEESIMPLE"; 660 | int get_original_fwd_fee(int workchain, int fwd_fee) asm(fwd_fee workchain) "GETORIGINALFWDFEE"; 661 | int my_storage_due() asm "DUEPAYMENT"; 662 | 663 | tuple get_fee_cofigs() asm "UNPACKEDCONFIGTUPLE"; 664 | 665 | ;; BASIC 666 | 667 | const int TRUE = -1; 668 | const int FALSE = 0; 669 | 670 | const int MASTERCHAIN = -1; 671 | const int BASECHAIN = 0; 672 | 673 | ;;; skip (Maybe ^Cell) from `slice` [s]. 674 | (slice, ()) ~skip_maybe_ref(slice s) asm "SKIPOPTREF"; 675 | 676 | (slice, int) ~load_bool(slice s) inline { 677 | return s.load_int(1); 678 | } 679 | 680 | builder store_bool(builder b, int value) inline { 681 | return b.store_int(value, 1); 682 | } 683 | 684 | ;; ADDRESS NONE 685 | ;; addr_none$00 = MsgAddressExt; https://github.com/ton-blockchain/ton/blob/8a9ff339927b22b72819c5125428b70c406da631/crypto/block/block.tlb#L100 686 | 687 | builder store_address_none(builder b) inline { 688 | return b.store_uint(0, 2); 689 | } 690 | 691 | slice address_none() asm "