### 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