### Full Jetton Token Interaction Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/JettonContracts.md Demonstrates a complete workflow for interacting with Jetton tokens, including client setup, accessing master and wallet data, and retrieving balances. ```typescript import { TonClient } from '@ton/ton'; import { JettonMaster, JettonWallet } from '@ton/ton'; import { Address } from '@ton/core'; const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', }); // Create a provider const provider = client.provider(Address.parse('EQCD...')); // Access Jetton master const jettonAddress = Address.parse('EQCxE6mUtQ...'); const jetton = JettonMaster.create(jettonAddress); // Get master data const jettonData = await jetton.getJettonData(provider); console.log('Total supply:', jettonData.totalSupply.toString()); console.log('Mintable:', jettonData.mintable); // Get wallet for an owner const ownerAddress = Address.parse('EQA9V...'); const walletAddress = await jetton.getWalletAddress(provider, ownerAddress); console.log('Wallet address:', walletAddress.toString()); // Get wallet balance const jettonWallet = JettonWallet.create(walletAddress); const walletBalance = await jettonWallet.getBalance(provider); console.log('Wallet balance:', walletBalance.toString()); ``` -------------------------------- ### TON JS Client Usage Example Source: https://github.com/ton-org/ton/blob/main/README.md Demonstrates how to create a TON client, generate keys, create a wallet contract, get the balance, and construct a transfer. ```ts import { TonClient, WalletContractV4, internal } from "@ton/ton"; import { mnemonicNew, mnemonicToPrivateKey } from "@ton/crypto"; // Create Client const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', }); // Generate new key const mnemonic = await mnemonicNew(); const keyPair = await mnemonicToPrivateKey(mnemonic); // Create wallet contract const wallet = WalletContractV4.create({ workchain: 0, // basechain publicKey: keyPair.publicKey, }); const contract = client.open(wallet); // Get balance const balance = await contract.getBalance(); // Create a transfer const seqno = await contract.getSeqno(); const transfer = await contract.createTransfer({ seqno, secretKey: keyPair.secretKey, messages: [internal({ value: '1.5', to: 'EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N', body: 'Hello world', })] }); ``` -------------------------------- ### MultisigWallet Usage Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/MultisigContracts.md Example demonstrating how to create and deploy a multisig wallet, create an order, and have owners sign it. ```APIDOC ## Usage Example ```typescript import { MultisigWallet, MultisigOrder } from '@ton/ton'; import { internal, toNano, SendMode } from '@ton/core'; // Create a 2-of-3 multisig wallet const publicKeys = [pubkey1, pubkey2, pubkey3]; const wallet = new MultisigWallet(publicKeys, 0, 0, 2); // Get provider const provider = client.provider(wallet.address, wallet.init); // Deploy the wallet await wallet.deployExternal(provider); // Create an order const order = new MultisigOrder({ messages: [ internal({ to: recipientAddress, value: toNano('0.05'), body: comment('Hello from multisig'), }), ], sendMode: SendMode.PAY_GAS_SEPARATELY, }); // First signer sends the order await wallet.sendOrder(order, owner1SecretKey, provider); // Second signer confirms await wallet.sendOrder(order, owner2SecretKey, provider); // Once k signatures are reached, the order executes automatically ``` ``` -------------------------------- ### parseProposalSetup Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses the voting proposal setup configuration from a slice. Use this to get details about how proposals are set up. ```APIDOC ## parseProposalSetup ### Description Parses voting proposal setup configuration. ### Parameters #### Path Parameters - **slice** (Slice) - Required - Slice containing proposal setup configuration ### Returns - **ProposalSetup** - ProposalSetup object ``` -------------------------------- ### Interact with Jettons Source: https://github.com/ton-org/ton/blob/main/_autodocs/README.md Examples for retrieving Jetton master data, getting a Jetton wallet address, and checking a Jetton wallet's balance. Requires Jetton master and owner addresses. ```typescript // Get master data const jetton = JettonMaster.create(masterAddress); const data = await jetton.getJettonData(provider); // Get wallet address const walletAddr = await jetton.getWalletAddress(provider, ownerAddress); // Check balance const wallet = JettonWallet.create(walletAddr); const balance = await wallet.getBalance(provider); ``` -------------------------------- ### Install TON Libraries Source: https://github.com/ton-org/ton/blob/main/_autodocs/INDEX.md Installs the necessary TON libraries for your project. Ensure you have Node.js and npm installed. ```bash npm install @ton/ton @ton/core @ton/crypto ``` -------------------------------- ### Parse Proposal Setup Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses the setup configuration for voting proposals. Use this to understand the parameters governing proposal submissions. ```typescript function parseProposalSetup(slice: Slice): ProposalSetup ``` -------------------------------- ### Get Installed Plugins Array Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Retrieves an array of addresses for all installed plugins on the wallet. Requires a ContractProvider instance. ```typescript async getPluginsArray(provider: ContractProvider): Promise ``` -------------------------------- ### WalletContractV4 Plugin Management Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Shows how to manage plugins for the wallet, including installation, uninstallation, and checking installation status. ```APIDOC ## WalletContractV4 Plugin Management ### Description Manages plugins for the WalletContractV4, allowing dynamic addition, removal, and querying of installed plugins. ### Methods - **sendAddPlugin(provider, options)**: Installs a new plugin to the wallet. - **sendRemovePlugin(provider, options)**: Uninstalls a plugin from the wallet. - **getPluginsArray(provider)**: Retrieves an array of all installed plugin addresses. - **getIsPluginInstalled(provider, pluginAddress)**: Checks if a specific plugin is installed. ### Parameters for sendAddPlugin/sendRemovePlugin - **provider**: The TonClient provider instance. - **options** (object) - **seqno** (number) - The sequence number for the transaction. - **secretKey** (Buffer) - The secret key for signing the transaction. - **address** (string) - The address of the plugin contract. - **forwardAmount** (BigNumber) - The amount of TON to forward with the operation. - **queryId** (BigNumber, optional for sendAddPlugin) - A unique query ID. ``` -------------------------------- ### Install TON JS Client Dependencies Source: https://github.com/ton-org/ton/blob/main/README.md Install the necessary packages for the TON JS Client using yarn. ```bash yarn add @ton/ton @ton/crypto @ton/core buffer ``` -------------------------------- ### Basic TonClient Configuration Source: https://github.com/ton-org/ton/blob/main/_autodocs/configuration.md Initializes a TonClient with the essential endpoint configuration. Use this for simple setups. ```typescript import { TonClient } from '@ton/ton'; const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', }); ``` -------------------------------- ### Check if Plugin is Installed Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Checks if a specific plugin is installed on the wallet. Requires a ContractProvider and the plugin's Address. ```typescript async getIsPluginInstalled( provider: ContractProvider, pluginAddress: Address ): Promise ``` -------------------------------- ### WalletContractV4 Plugin Management Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Shows how to manage plugins for a WalletContractV4. Includes installing, uninstalling, and checking the status of plugins. ```typescript // Install plugin await wallet.sendAddPlugin(provider, { seqno, secretKey: keyPair.secretKey, address: pluginAddress, forwardAmount: toNano('0.01'), queryId: 0n, }); // Uninstall plugin await wallet.sendRemovePlugin(provider, { seqno, secretKey: keyPair.secretKey, address: pluginAddress, forwardAmount: toNano('0.01'), }); // Check installed plugins const plugins = await wallet.getPluginsArray(provider); const isInstalled = await wallet.getIsPluginInstalled(provider, pluginAddress); ``` -------------------------------- ### Complete TON Fee Calculation Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/FeeCalculations.md Demonstrates a full fee calculation process, including fetching config, parsing prices, and computing external, forward, and storage fees. Ensure you have a working implementation for `getConfigCell` and a defined `destinationAddress`. ```typescript import { TonClient, computeExternalMessageFees, computeMessageForwardFees, computeStorageFees, configParse18, configParse28, parseFullConfig, loadConfigParamsAsSlice, } from '@ton/ton'; import { beginCell, Cell } from '@ton/core'; const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', }); // Get blockchain config (from contract state) const configCell = await getConfigCell(); // implementation-specific // Parse config const configMap = parseFullConfig(configCell); // Get message pricing (param 18) const msgPricesSlice = loadConfigParamsAsSlice(configCell, 18); const msgPrices = configParse18(msgPricesSlice); // Get storage pricing (param 28) const storagePricesSlice = loadConfigParamsAsSlice(configCell, 28); const storagePrices = configParse28(storagePricesSlice); // Create a message const message = beginCell() .storeUint(0x12345, 32) .storeAddress(destinationAddress) .storeCoins(toNano('0.05')) .endCell(); // Calculate external message fees const externalFees = computeExternalMessageFees(msgPrices.prices, message); console.log(`External message fees: ${externalFees.toString()} nanotons`); // Calculate forward fees const forwardFees = computeMessageForwardFees(msgPrices.prices, message); console.log(`Forward fees: ${forwardFees.fees.toString()} nanotons`); console.log(`Bounce fees: ${forwardFees.remaining.toString()} nanotons`); // Calculate storage fees const now = Math.floor(Date.now() / 1000); const storageFees = computeStorageFees({ now, lastPaid: now - 86400, // 1 day ago storagePrices: storagePrices.prices, storageStat: { cells: 5000, bits: 100000, publicCells: 0, }, special: false, masterchain: false, }); console.log(`Storage fees: ${storageFees.toString()} nanotons`); // Total fees const totalFees = externalFees + forwardFees.fees + storageFees; console.log(`Total estimated fees: ${totalFees.toString()} nanotons`); ``` -------------------------------- ### Parse Config Parameter 7 Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 7, which specifies extra currencies to mint. This function throws an error if the parameter is missing. ```typescript const config7 = configParse7(slice); console.log(`Extra currency to mint: ${config7.toMint}`); ``` -------------------------------- ### Configure HTTP Adapter with Proxy Support Source: https://github.com/ton-org/ton/blob/main/_autodocs/configuration.md Sets up a TON client to use a custom HTTP adapter with proxy support using http-proxy-agent. Ensure axios and http-proxy-agent are installed. ```typescript import axios from 'axios'; import { HttpProxyAgent, HttpsProxyAgent } from 'http-proxy-agent'; const httpAgent = new HttpProxyAgent('http://proxy:8080'); const httpsAgent = new HttpsProxyAgent('https://proxy:8080'); const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', httpAdapter: axios.getAdapter([httpAgent, httpsAgent]), }); ``` -------------------------------- ### WalletContractV4 Basic Usage Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Illustrates common operations such as getting the balance, sequence number, and sending transfers. ```APIDOC ## WalletContractV4 Basic Usage ### Description Provides examples for interacting with an opened WalletContractV4 instance, including checking balance, sequence number, and sending transactions. ### Methods - **getBalance(provider)**: Retrieves the current balance of the wallet. - **getSeqno(provider)**: Retrieves the current sequence number of the wallet. - **sendTransfer(provider, options)**: Sends a transaction from the wallet. ### Parameters for sendTransfer - **provider**: The TonClient provider instance. - **options** (object) - **seqno** (number) - The sequence number for the transaction. - **secretKey** (Buffer) - The secret key for signing the transaction. - **messages** (Array) - An array of messages to be included in the transfer. ``` -------------------------------- ### getIsPluginInstalled Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Checks if a specific plugin is installed on the wallet by its contract address. ```APIDOC ## getIsPluginInstalled ### Description Checks if a plugin is installed on the wallet. ### Method `async getIsPluginInstalled(provider: ContractProvider, pluginAddress: Address): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **pluginAddress** (Address) - Required - Plugin contract address ### Response #### Success Response (200) - **installed** (boolean) - true if plugin is installed, false otherwise ``` -------------------------------- ### Parse Config Parameter 6 Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 6, which contains minting prices for new accounts. Returns null if the parameter is missing. ```typescript const config6 = configParse6(slice); if (config6) { console.log(`Mint new price: ${config6.mintNewPrice}`); console.log(`Mint add price: ${config6.mintAddPrice}`); } ``` -------------------------------- ### Fee Calculation Source: https://github.com/ton-org/ton/blob/main/_autodocs/README.md Examples for parsing TON configuration to obtain message and storage prices, and then calculating forward, external, and storage fees. Requires configuration data and relevant parameters. ```typescript // Parse config to get pricing const configMap = parseFullConfig(configCell); const msgPrices = configParse18(configMap.get(18)?.beginParse()); const storagePrices = configParse28(configMap.get(28)?.beginParse()); // Calculate fees const fwdFees = computeFwdFees(msgPrices.prices, 10n, 1500n); const externalFees = computeExternalMessageFees(msgPrices.prices, messageCell); const storageFees = computeStorageFees({ now: Math.floor(Date.now() / 1000), lastPaid: lastPaidTime, storagePrices: storagePrices.prices, storageStat: { cells: 5000, bits: 100000, publicCells: 0 }, special: false, masterchain: false, }); ``` -------------------------------- ### Validate Configuration Parameters Source: https://github.com/ton-org/ton/blob/main/_autodocs/README.md Ensure that required configuration parameters are present before using them. This example checks for a specific parameter in a configuration map. ```typescript const param = configMap.get(16); if (!param) { console.error('Missing required config parameter'); } ``` -------------------------------- ### Basic Wallet Operations Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Demonstrates how to interact with a WalletContractV4 instance using a TonClient provider. Includes getting balance, sequence number, and sending a transfer. ```typescript const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', }); const provider = client.open(wallet); // Get balance const balance = await wallet.getBalance(provider); // Get seqno const seqno = await wallet.getSeqno(provider); // Send transfer await wallet.sendTransfer(provider, { seqno, secretKey: keyPair.secretKey, messages: [ internal({ to: destinationAddress, value: toNano('0.05'), body: comment('Hello'), }), ], }); ``` -------------------------------- ### Parse Config Parameter 8 Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 8, which is the masterchain address. This function throws an error if the parameter is missing. ```typescript const config8 = configParse8(slice); console.log(`Masterchain address: ${config8.address.toString()}`); ``` -------------------------------- ### Parse Master Address Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses the masterchain address from config parameter 0. Use this when the parameter might be missing. ```typescript const masterAddress = configParseMasterAddress(param0); console.log(masterAddress?.toString()); ``` -------------------------------- ### Parse Voting Setup Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses the general voting configuration. This function retrieves settings related to the voting process. ```typescript function parseVotingSetup(slice: Slice): VotingSetup ``` -------------------------------- ### Default Wallet ID Calculation Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Shows the default calculation for wallet IDs based on the workchain, and an example of using a custom ID. ```typescript walletId = 698983191 + workchain // Basechain (0) walletId = 698983191 // Custom ID for multi-wallet walletId = 42 ``` -------------------------------- ### Parse Config Parameter 5 Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 5, which includes the blackhole address and fee burning ratios. This function throws an error if the parameter is invalid. ```typescript const config5 = configParse5(slice); console.log(config5.blackholeAddr?.toString()); console.log(config5.feeBurnNominator / config5.feeBurnDenominator); ``` -------------------------------- ### Parse Config Parameter 12 Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 12, which contains workchain descriptors. This function throws an error if the parameter is invalid. ```typescript const config12 = configParse12(slice); for (const wcId in config12.workchains) { console.log(`Workchain ${wcId}: ${config12.workchains[wcId].name}`); } ``` -------------------------------- ### Full TonClient Configuration Source: https://github.com/ton-org/ton/blob/main/_autodocs/configuration.md Initializes a TonClient with all available configuration options, including endpoint, timeout, API key, and a custom HTTP adapter. Use this for advanced setups requiring specific network or authentication settings. ```typescript import { TonClient } from '@ton/ton'; import { httpAgent, httpsAgent } from 'http'; const client = new TonClient({ // Required: Toncenter API endpoint endpoint: 'https://toncenter.com/api/v2/jsonRPC', // Optional: HTTP request timeout (milliseconds) timeout: 30000, // Optional: API key for authenticated endpoints apiKey: process.env.TONCENTER_API_KEY, // Optional: Custom axios HTTP adapter httpAdapter: customAdapter, }); ``` -------------------------------- ### Parse Config Parameter 9 Example Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 9, which lists mandatory parameter IDs. This function throws an error if the parameter is missing. ```typescript const config9 = configParse9(slice); console.log(`Mandatory parameters: ${config9.mandatory.join(', ')}`); ``` -------------------------------- ### Initialize and Use WalletContractV4 Source: https://github.com/ton-org/ton/blob/main/_autodocs/types.md Demonstrates how to initialize TonClient, create a WalletContractV4 instance, prepare transfer arguments, and create a transaction. ```typescript import { TonClient, TonClientParameters, WalletContractV4, Wallet4SendArgsSigned, } from '@ton/ton'; import { Address, toNano } from '@ton/core'; // Configuration const params: TonClientParameters = { endpoint: 'https://toncenter.com/api/v2/jsonRPC', timeout: 30000, }; // Initialize const client = new TonClient(params); // Create wallet const wallet = WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey, }); // Prepare transfer const args: Wallet4SendArgsSigned = { seqno: 0, messages: [internal({...})], sendMode: SendMode.PAY_GAS_SEPARATELY, secretKey: keyPair.secretKey, }; // Send const transfer = wallet.createTransfer(args); ``` -------------------------------- ### Basic TON Client and Wallet Usage Source: https://github.com/ton-org/ton/blob/main/_autodocs/README.md Demonstrates how to initialize a TON client, generate a new wallet using a mnemonic, create a wallet contract object, and check its balance. Requires @ton/ton, @ton/core, and @ton/crypto. ```typescript import { TonClient, WalletContractV4 } from '@ton/ton'; import { mnemonicToPrivateKey, mnemonicNew } from '@ton/crypto'; // Create client const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', }); // Generate new wallet const mnemonic = await mnemonicNew(); const keyPair = await mnemonicToPrivateKey(mnemonic); // Create wallet contract const wallet = WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey, }); // Open wallet in client const walletContract = client.open(wallet); // Check balance const balance = await walletContract.getBalance(); console.log('Balance:', balance.toString()); ``` -------------------------------- ### JettonWallet.create Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/JettonContracts.md Initializes a JettonWallet instance, representing a user's wallet contract for holding Jetton tokens. ```APIDOC ## JettonWallet.create ### Description Creates an instance of the JettonWallet contract, which represents a user's wallet contract for holding Jetton tokens. ### Method Signature ```typescript static create(address: Address): JettonWallet ``` ### Parameters #### Path Parameters - **address** (Address) - Required - Jetton wallet contract address ### Returns - **JettonWallet** - JettonWallet instance ### Example ```typescript const wallet = JettonWallet.create( Address.parse('EQDyk_LCRg...') ); ``` ``` -------------------------------- ### Deploy Wallet Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Deploys the wallet by sending the first transaction. This is typically done when the initial `getSeqno` returns 0. Requires the provider, secret key, and a list of messages. ```APIDOC ## Deploy Wallet ### Description Deploys the wallet by sending the first transaction. This is typically done when the initial `getSeqno` returns 0. ### Method `sendTransfer(provider: Provider, options: { seqno: number, secretKey: Buffer, messages: Message[] }): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **seqno** (number) - Must be 0 for initial deployment. - **secretKey** (Buffer) - The secret key for signing the deployment transaction. - **messages** (Message[]) - An array of messages to include in the deployment transaction. ### Request Example ```typescript const seqno = await wallet.getSeqno(provider); if (seqno === 0) { await wallet.sendTransfer(provider, { seqno: 0, secretKey: keyPair.secretKey, messages: [ internal({ to: ownerAddress, value: toNano('0.1'), body: comment('Deployment'), }), ], }); } ``` ### Response #### Success Response (200) Indicates the deployment transaction has been sent successfully. #### Response Example None (void return type) ``` -------------------------------- ### Get Latest Block Information Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/TonClient4.md Retrieves the most recent block information from the TON blockchain. This is useful for getting the latest state or sequence number. ```typescript const lastBlock = await client.getLastBlock(); console.log(lastBlock.seqno); ``` -------------------------------- ### Run Contract Get Method Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/TonClient.md Invokes a contract's read-only method (get method) and returns the result from the stack. This method throws an error if the contract method returns a non-zero exit code. ```typescript const result = await client.runMethod(contractAddress, 'get_balance', []); const balance = result.stack.readBigNumber(); ``` -------------------------------- ### Create a Multisig Wallet Instance Source: https://github.com/ton-org/ton/blob/main/_autodocs/configuration.md Instantiate a MultisigWallet with owner public keys, workchain, wallet ID, and the number of required signatures (k). ```typescript import { MultisigWallet } from '@ton/ton'; const publicKeys = [key1, key2, key3]; const wallet = new MultisigWallet( publicKeys, // All owner public keys 0, // workchain 0, // walletId 2, // k (signatures required) { provider: client.provider(address, null), client: client, } ); ``` -------------------------------- ### Call Contract Get Method Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/HttpApi.md Executes a read-only 'get' method on a TON contract using JSON-RPC. Accepts the contract address, method name, and an optional stack of parameters. Returns gas used, exit code, and the result stack. ```typescript async callGetMethod( address: Address, name: string, stack: TupleItem[] = [] ): Promise<{ gas_used: number; exit_code: number; stack: any[] }> ``` -------------------------------- ### Multiple Wallet Configuration Source: https://github.com/ton-org/ton/blob/main/_autodocs/configuration.md Set up and open multiple wallets (hot and cold) using WalletContractV4. Assumes 'client' and key pairs ('hotKeyPair', 'coldKeyPair') are already defined. ```typescript import { WalletContractV4 } from '@ton/ton'; const wallets = { hot: WalletContractV4.create({ workchain: 0, publicKey: hotKeyPair.publicKey, }), cold: WalletContractV4.create({ workchain: 0, publicKey: coldKeyPair.publicKey, }), }; const hotWallet = client.open(wallets.hot); const coldWallet = client.open(wallets.cold); ``` -------------------------------- ### getPluginsArray Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Retrieves an array containing the contract addresses of all installed plugins on the wallet. ```APIDOC ## getPluginsArray ### Description Retrieves the list of installed plugins. ### Method `async getPluginsArray(provider: ContractProvider): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **plugins** (Address[]) - Array of plugin addresses ``` -------------------------------- ### Multisig Wallet Deployment and Order Execution Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/MultisigContracts.md Shows how to create, deploy, and manage a multisig wallet. It includes creating an order, signing it with multiple owners, and the automatic execution upon reaching the required number of signatures. ```typescript import { MultisigWallet, MultisigOrder } from '@ton/ton'; import { internal, toNano, SendMode } from '@ton/core'; // Create a 2-of-3 multisig wallet const publicKeys = [pubkey1, pubkey2, pubkey3]; const wallet = new MultisigWallet(publicKeys, 0, 0, 2); // Get provider const provider = client.provider(wallet.address, wallet.init); // Deploy the wallet await wallet.deployExternal(provider); // Create an order const order = new MultisigOrder({ messages: [ internal({ to: recipientAddress, value: toNano('0.05'), body: comment('Hello from multisig'), }), ], sendMode: SendMode.PAY_GAS_SEPARATELY, }); // First signer sends the order await wallet.sendOrder(order, owner1SecretKey, provider); // Second signer confirms await wallet.sendOrder(order, owner2SecretKey, provider); // Once k signatures are reached, the order executes automatically ``` -------------------------------- ### Migrate from V3 to V4 Wallet Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Demonstrates creating V3 and V4 wallets with the same keys, highlighting the resulting different addresses and the need for new V4 deployment. ```typescript // V3 wallet const v3Wallet = WalletContractV3R2.create({ workchain: 0, publicKey: keyPair.publicKey, }); // V4 wallet (same keys) const v4Wallet = WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey, walletId: 0, // New wallet ID, different address }); // Different addresses! console.log(v3Wallet.address.toString()); console.log(v4Wallet.address.toString()); // New deployment needed for V4 ``` -------------------------------- ### getShards Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/HttpApi.md Gets shard information for a specific masterchain block sequence number. ```APIDOC ## getShards ### Description Gets shards for a masterchain block. ### Method GET (assumed, for retrieving a list of related resources) ### Endpoint `/getShards` (assumed, based on method name) ### Parameters #### Path Parameters None #### Query Parameters - **seqno** (number) - Required - The masterchain sequence number for which to retrieve shards. ### Request Example ```json { "seqno": 12345 } ``` ### Response #### Success Response (200) - Returns an array of shard information objects. - **workchain** (number) - **shard** (string) - **seqno** (number) #### Response Example ```json [ { "workchain": 0, "shard": "-9223372036854775808", "seqno": 12345 }, { "workchain": 1, "shard": "0", "seqno": 12345 } ] ``` ``` -------------------------------- ### Multisig Operations Source: https://github.com/ton-org/ton/blob/main/_autodocs/README.md Demonstrates creating a multisig wallet, deploying it, defining an order with messages, and signing/executing the order with multiple keys. Requires public keys and owner keys. ```typescript // Create wallet const wallet = new MultisigWallet(publicKeys, 0, 0, 2); // Deploy await wallet.deployExternal(provider); // Create order const order = new MultisigOrder({ messages: [ internal({ to: recipient, value: toNano('0.05'), body: messageCell, }), ], }); // Sign and execute await wallet.sendOrder(order, owner1Key, provider); await wallet.sendOrder(order, owner2Key, provider); ``` -------------------------------- ### Get Wallet Balance Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Retrieves the wallet's balance in nanotons. Requires a ContractProvider instance. ```typescript async getBalance(provider: ContractProvider): Promise ``` ```typescript const balance = await wallet.getBalance(provider); console.log(balance.toString()); // balance in nanotons ``` -------------------------------- ### Create Custom TON Providers Source: https://github.com/ton-org/ton/blob/main/_autodocs/configuration.md Demonstrates how to create custom TON providers for direct creation or via contract opening. Requires Address and init parameters. ```typescript const address = Address.parse('EQA...'); const init = { code: codeCell, data: dataCell, }; // Direct provider creation const provider = client.provider(address, init); // Via contract opening const contract = client.open(contractInstance); ``` -------------------------------- ### getMasterchainInfo Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/HttpApi.md Gets the latest masterchain block information, including its initialization and last block details. ```APIDOC ## getMasterchainInfo ### Description Gets the latest masterchain block information. ### Method GET (assumed, for retrieving general network information) ### Endpoint `/getMasterchainInfo` (assumed, based on method name) ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **init** (object) - Initialization details of the masterchain. - **workchain** (number) - **seqno** (number) - **last** (object) - Information about the last masterchain block. - **workchain** (number) - **shard** (string) - **seqno** (number) - **state_root_hash** (string) - The root hash of the current masterchain state. #### Response Example ```json { "init": { "workchain": -1, "seqno": 12345 }, "last": { "workchain": -1, "shard": "-9223372036854775808", "seqno": 12345 }, "state_root_hash": "0x..." } ``` ``` -------------------------------- ### Create WalletContractV4 Instance Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Use the static `create` method to instantiate a WalletContractV4. Provide the workchain, public key, and optionally a wallet ID or signature domain. ```typescript static create({ workchain: number; publicKey: Buffer; walletId?: number; domain?: SignatureDomain; }): WalletContractV4 ``` ```typescript import { WalletContractV4, } from '@ton/ton'; import { mnemonicToPrivateKey, } from '@ton/crypto'; const mnemonic = [...]; // your mnemonic const keyPair = await mnemonicToPrivateKey(mnemonic); const wallet = WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey, }); ``` -------------------------------- ### getBlockTransactions Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/HttpApi.md Gets transactions within a specific block. Requires workchain, sequence number, and shard ID. ```APIDOC ## getBlockTransactions ### Description Gets transactions within a specific block. Requires workchain, sequence number, and shard ID. ### Method GET (assumed based on 'get' prefix and lack of body) ### Endpoint /getBlockTransactions ### Parameters #### Query Parameters - **workchain** (number) - Required - Workchain ID - **seqno** (number) - Required - Block sequence number - **shard** (string) - Required - Shard ID ### Response #### Success Response (200) - **id** (object) - Block identifier - **workchain** (number) - **shard** (string) - **seqno** (number) - **req_count** (number) - Number of requested transactions - **incomplete** (boolean) - Indicates if the result is incomplete - **transactions** (array) - List of transactions - **account** (string) - **lt** (string) - **hash** (string) - **mode** (number) ``` -------------------------------- ### Handling Multisig Wallet Deployment Errors Source: https://github.com/ton-org/ton/blob/main/_autodocs/errors.md Demonstrates how to catch and resolve 'no provider' errors during external multisig wallet deployment by providing the necessary provider. ```typescript const wallet = new MultisigWallet(keys, 0, 0, 2); await wallet.deployExternal(); // Error: no provider ``` ```typescript const provider = client.provider(wallet.address, wallet.init); await wallet.deployExternal(provider); ``` -------------------------------- ### Create MultisigWallet Instance Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/MultisigContracts.md Instantiate a MultisigWallet by providing owner public keys, workchain, wallet ID, and the required number of signatures (k). Optionally, you can specify the address, provider, or TonClient. ```typescript import { MultisigWallet } from '@ton/ton'; const publicKeys = [pubkey1, pubkey2, pubkey3]; const wallet = new MultisigWallet( publicKeys, 0, // workchain 0, // walletId 2 // require 2-of-3 signatures ); ``` -------------------------------- ### Get Block Transactions Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/HttpApi.md Retrieves transactions for a specific block identified by workchain, sequence number, and shard. ```typescript async getBlockTransactions( workchain: number, seqno: number, shard: string ): Promise<{ id: { workchain: number; shard: string; seqno: number }; req_count: number; incomplete: boolean; transactions: Array<{ account: string; lt: string; hash: string; mode: number }>; }> ``` -------------------------------- ### WalletContractV4 Creation Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContracts.md Demonstrates how to create a new WalletContractV4 instance with specified parameters. ```APIDOC ## WalletContractV4 Creation ### Description Creates a new instance of WalletContractV4. This is the recommended wallet contract for new development. ### Parameters - **workchain** (number) - The workchain ID for the wallet. - **publicKey** (Buffer) - The public key associated with the wallet. - **walletId** (number, optional) - The wallet ID. Defaults to 0. - **domain** (string | undefined, optional) - The domain for signature separation. Optional for testnet. ``` -------------------------------- ### Create JettonWallet Instance Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/JettonContracts.md Creates a JettonWallet instance using the provided Jetton wallet contract address. ```typescript const wallet = JettonWallet.create( Address.parse('EQDyk_LCRg...') ); ``` -------------------------------- ### runMethod Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/TonClient.md Invokes a contract's get method and returns the stack result. Throws an error if exit_code is non-zero. ```APIDOC ## runMethod ### Description Invokes a contract's get method and returns the stack result. Throws an error if exit_code is non-zero. ### Method async runMethod(address: Address, name: string, stack: TupleItem[] = []): Promise<{ gas_used: number; stack: TupleReader }> ### Parameters #### Path Parameters - **address** (Address) - Required - Contract address - **name** (string) - Required - Method name to invoke - **stack** (TupleItem[]) - Optional - Parameters for the method ### Response #### Success Response - **gas_used** (number) - Gas units consumed - **stack** (TupleReader) - Result stack that can be read using methods like readNumber(), readAddress(), etc. ### Throws Error if exit_code is non-zero ### Request Example ```typescript const result = await client.runMethod(contractAddress, 'get_balance', []); const balance = result.stack.readBigNumber(); ``` ``` -------------------------------- ### Get Jetton Wallet Address Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/JettonContracts.md Retrieves the Jetton wallet address associated with a specific owner's address. ```typescript const walletAddress = await jetton.getWalletAddress(provider, ownerAddress); ``` -------------------------------- ### configParse6 Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 6, which contains the prices for minting new accounts. It returns an object with minting prices or null if the parameter is missing. ```APIDOC ## configParse6 ### Description Parses configuration parameter 6 (minting prices for new accounts). ### Method ```typescript function configParse6(slice: Slice | null | undefined): { mintNewPrice: bigint; mintAddPrice: bigint; } | null ``` ### Parameters #### Path Parameters - **slice** (Slice | null | undefined) - Required - Config parameter 6 slice ### Returns - **Object | null** - Minting prices object or null if parameter is missing ``` -------------------------------- ### runMethodWithError Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/TonClient.md Invokes a contract's get method without throwing on non-zero exit codes. Returns the exit code. ```APIDOC ## runMethodWithError ### Description Invokes a contract's get method without throwing on non-zero exit codes. Returns the exit code. ### Method async runMethodWithError(address: Address, name: string, params: any[] = []): Promise<{ gas_used: number; stack: TupleReader; exit_code: number }> ### Parameters #### Path Parameters - **address** (Address) - Required - Contract address - **name** (string) - Required - Method name to invoke - **params** (any[]) - Optional - Parameters for the method ### Response #### Success Response - **gas_used** (number) - Gas units consumed - **stack** (TupleReader) - Result stack - **exit_code** (number) - Method exit code ### Request Example ```typescript const result = await client.runMethodWithError(contractAddress, 'get_data', []); if (result.exit_code === 0) { console.log(result.stack.readNumber()); } ``` ``` -------------------------------- ### Get Masterchain Sequence Number Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/TonClient4.md Retrieves the current sequence number of the masterchain. This is useful for synchronizing with the latest chain state. ```typescript const masterSeqno = await client.getMasterchainSeqno(); ``` -------------------------------- ### Get Jetton Wallet Balance Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/JettonContracts.md Retrieves the Jetton token balance for a specific wallet. Returns 0n if the wallet is not active. ```typescript const balance = await jettonWallet.getBalance(provider); console.log(balance.toString()); // balance in smallest units ``` -------------------------------- ### Configure TonClient for Testnet Source: https://github.com/ton-org/ton/blob/main/_autodocs/configuration.md Set up a TonClient instance for the TON testnet, including the necessary domain configuration for testnet. ```typescript const testnetClient = new TonClient({ endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC', }); const wallet = WalletContractV4.create({ workchain: 0, publicKey: key, domain: { networkId: -3, // -3 for testnet address: Address.parse('Eqc1111111111111111111111111111111111111111111_'), }, }); ``` -------------------------------- ### Query Blockchain Data Source: https://github.com/ton-org/ton/blob/main/_autodocs/README.md Examples for retrieving blockchain information such as account balances, method results, transaction history, and block details. ```typescript // Get balance const balance = await client.getBalance(address); // Call get method const result = await client.runMethod(address, 'method_name', []); // Get transactions const txs = await client.getTransactions(address, { limit: 10, inclusive: false, }); // Get block info const block = await client4.getBlock(seqno); const account = await client4.getAccount(seqno, address); ``` -------------------------------- ### configParse7 Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ConfigParser.md Parses configuration parameter 7, which specifies extra currencies to mint. It returns an object with the extra currency information or throws an error if the parameter is missing. ```APIDOC ## configParse7 ### Description Parses configuration parameter 7 (extra currencies to mint). ### Method ```typescript function configParse7(slice: Slice | null | undefined): { toMint: ExtraCurrency; } ``` ### Parameters #### Path Parameters - **slice** (Slice | null | undefined) - Required - Config parameter 7 slice ### Returns - **Object** - Object containing extra currency minting info ### Throws - Error if parameter is missing ``` -------------------------------- ### Get Active Election ID Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/ElectorContract.md Retrieves the current active election ID. Use this method to check if an election is currently in progress. ```typescript async getActiveElectionId(provider: ContractProvider): Promise const electionId = await elector.getActiveElectionId(provider); if (electionId) { console.log(`Active election: ${electionId}`); } else { console.log('No active election'); } ``` -------------------------------- ### WalletContractV4.create Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Creates a new WalletContractV4 instance. This is the primary method for instantiating a wallet. ```APIDOC ## WalletContractV4.create ### Description Creates a new WalletContractV4 instance. This is the primary method for instantiating a wallet. ### Method `static create(args: { workchain: number; publicKey: Buffer; walletId?: number; domain?: SignatureDomain }): WalletContractV4` ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **workchain** (number) - Required - Workchain ID (0 for basechain, -1 for masterchain) - **publicKey** (Buffer) - Required - Public key (32 bytes) - **walletId** (number) - Optional - Wallet identifier for multi-signature support. Defaults to `698983191 + workchain`. - **domain** (SignatureDomain) - Optional - Optional signature domain for domain separation. ### Response #### Success Response - **WalletContractV4 instance** - The newly created WalletContractV4 instance. ### Request Example ```typescript import { WalletContractV4 } from '@ton/ton'; import { mnemonicToPrivateKey } from '@ton/crypto'; const mnemonic = [...]; // your mnemonic const keyPair = await mnemonicToPrivateKey(mnemonic); const wallet = WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey, }); ``` ``` -------------------------------- ### getOwnerIdByPubkey Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/MultisigContracts.md Gets the owner index for a given public key. This method helps in identifying the owner associated with a specific public key. ```APIDOC ## getOwnerIdByPubkey ### Description Gets the owner index for a given public key. ### Method getOwnerIdByPubkey(publicKey: Buffer): number ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const ownerId = wallet.getOwnerIdByPubkey(publicKey); ``` ### Response #### Success Response (200) number - Owner index #### Response Example None **Throws:** Error if public key is not an owner **Parameters:** - **publicKey** (Buffer) - Required - Public key to look up ``` -------------------------------- ### MultisigWallet Constructor Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/MultisigContracts.md Creates a new MultisigWallet instance. This constructor allows for the initialization of a multi-signature wallet with specified owners, workchain, wallet ID, and the required number of signatures (k). Optional parameters include pre-computing the address or providing a contract provider and TonClient. ```APIDOC ## Constructor MultisigWallet ### Description Creates a new MultisigWallet instance. ### Parameters #### Path Parameters - **publicKeys** (Buffer[]) - Required - Array of owner public keys - **workchain** (number) - Required - Workchain ID - **walletId** (number) - Required - Wallet ID for multi-signature - **k** (number) - Required - Required number of signatures #### Query Parameters - **opts.address** (Address) - Optional - Pre-computed wallet address - **opts.provider** (ContractProvider) - Optional - Contract provider - **opts.client** (TonClient) - Optional - TonClient instance ### Request Example ```typescript import { MultisigWallet } from '@ton/ton'; const publicKeys = [pubkey1, pubkey2, pubkey3]; const wallet = new MultisigWallet( publicKeys, 0, // workchain 0, // walletId 2 // require 2-of-3 signatures ); ``` ``` -------------------------------- ### callGetMethod Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/HttpApi.md Calls a contract's get method via JSON-RPC, allowing interaction with contract state without sending a transaction. ```APIDOC ## callGetMethod ### Description Calls a contract's get method via JSON-RPC. ### Method POST (assumed, for calling a method that may read state) ### Endpoint `/callGetMethod` (assumed, based on method name) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **address** (Address) - Required - Contract address - **name** (string) - Required - Method name - **stack** (TupleItem[]) - Optional - Stack parameters for the method call ### Request Example ```json { "address": "", "name": "getBalance", "stack": [ {"type": "cell", "bytes": "..."} ] } ``` ### Response #### Success Response (200) - **gas_used** (number) - Gas consumed by the method call. - **exit_code** (number) - The exit code of the method execution. - **stack** (any[]) - The resulting stack from the method call. #### Response Example ```json { "gas_used": 100, "exit_code": 0, "stack": [ {"type": "num", "value": "1000000000"} ] } ``` ``` -------------------------------- ### Send Add and Deploy Plugin Request Source: https://github.com/ton-org/ton/blob/main/_autodocs/api-reference/WalletContractV4.md Adds and deploys a new plugin in a single transaction. Requires workchain, stateInit, body, and forward amount. ```typescript async sendAddAndDeployPlugin(provider: ContractProvider, args: T): Promise ```