TON JavaScript/TypeScript Client

repository·main·Indexed 42 days ago

https://github.com/ton-org/ton

A cross-platform JavaScript/TypeScript client for interacting with the TON (The Open Network) blockchain. Version 16.3.0 provides tools for wallet management (V1 through V5), balance retrieval, asset transfers, and Jetton interaction. It includes TonClient and TonClient4 for API interaction, as well as utilities for multisig wallets and blockchain configuration parsing.

Tokens
12.6K
Snippets
53
Records
63
Agent score
51%

What's inside TON

  1. Install @ton/ton and dependencies

    main

    To use the TON JS Client, install the core library along with its required dependencies: @ton/ton, @ton/crypto, and buffer.

    If you are using the library in a browser environment, you must include a buffer polyfill before using the library to ensure compatibility.

    yarn add @ton/ton @ton/crypto @ton/buffer
    // Add before using library in browser environments
    require("buffer");
  2. Basic usage: Create a client, wallet, and perform transfers

    main

    To interact with the TON blockchain, you must initialize a TonClient with an HTTP API endpoint. You can use public endpoints for Mainnet or Testnet.

    Common workflow:

    1. Initialize Client: Use new TonClient({ endpoint: '...' }).
    2. Manage Keys: Use @ton/crypto to generate mnemonics and private keys.
    3. Open Wallet: Use WalletContractV4.create to define the wallet and client.open(wallet) to create a contract instance that can interact with the blockchain.
    4. Get Balance: Call contract.getBalance().
    5. Transfer Funds: Retrieve the current seqno via contract.getSeqno(), then use contract.createTransfer with an array of internal messages.
    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',
      })]
    });
  3. How contract providers work in TonClient4

    main

    When you use client.open(contract) or client.provider(address), you receive a ContractProvider. This abstraction allows you to interact with a smart contract as if it were a local object, while the provider handles the underlying network calls.

    Key capabilities of a ContractProvider:

    • getState(): Fetches the current state (balance, code, data, last transaction) of the contract.
    • get(name, args): Executes a contract getter method.
    • external(message): Sends an external message to the contract.
    • internal(via, message): Sends an internal message (via a specified provider) to the contract.
    • getTransactions(...): Fetches transaction history specifically for that contract address.
    const contract = client.open(myContract);
    const state = await contract.getState();
    const result = await contract.get('get_balance', []);
  4. Understand V5R1 Wallet ID Contexts

    main

    A V5R1 Wallet ID is a 32-bit integer derived from global_id ^ context_id. The context_id determines how the wallet is identified:

    1. Client Context (WalletIdV5R1ClientContext)

    Used for standard client wallets. It contains:

    • walletVersion: Must be "v5r1".
    • workchain: An 8-bit signed integer.
    • subwalletNumber: A 15-bit unsigned integer.

    2. Custom Context (WalletIdV5R1CustomContext)

    Used for backoffice or specialized contexts. It is represented as a 31-bit unsigned integer.

    You can distinguish between these contexts using the isWalletIdV5R1ClientContext utility function.

    import { isWalletIdV5R1ClientContext } from "@ton/ton";
    
    // If context is an object, it's a Client Context
    if (isWalletIdV5R1ClientContext(walletId.context)) {
        console.log("This is a client wallet with workchain:", walletId.context.workchain);
    } else {
        // Otherwise it is a 31-bit number (Custom Context)
        console.log("This is a custom context ID:", walletId.context);
    }
  5. Initialize TonClient

    main

    To connect to the TON blockchain, instantiate the TonClient class with a configuration object. You must provide an endpoint (the API URL). Optional parameters include timeout (in milliseconds), apiKey, and a custom httpAdapter (using axios).

    import { TonClient } from "@ton/ton";
    
    const client = new TonClient({
        endpoint: "https://your-ton-api-endpoint.com",
        timeout: 5000,
        apiKey: "YOUR_API_KEY"
    });
  6. Initialize TonClient4

    main

    To connect to a TON blockchain endpoint, instantiate the TonClient4 class. You must provide an endpoint URL. You can optionally configure a request timeout, a custom axios adapter, or a request interceptor for custom HTTP logic.

    import { TonClient4 } from '@ton/ton';
    
    const client = new TonClient4({
        endpoint: 'https://your-ton-endpoint.com',
        timeout: 10000,
        // requestInterceptor: (config) => { ... }
    });
  7. Debug tests using SINGLETHREADED mode

    main

    By default, tests run using multiple worker threads for speed. If you need to debug tests, run them in single-threaded mode by setting the SINGLETHREADED environment variable to 1.

    SINGLETHREADED=1 yarn run test
  8. Configure TonClient endpoints

    main

    The TonClient requires an HTTP API endpoint. Use the following public endpoints:

    • Mainnet: https://toncenter.com/api/v2/jsonRPC
    • Testnet: https://testnet.toncenter.com/api/v2/jsonRPC
  9. Get balance and seqno from WalletContractV2R2

    main

    The WalletContractV2R2 instance provides methods to query the current state of the wallet on-chain using a ContractProvider.

    • getBalance(provider): Returns the current balance of the wallet.
    • getSeqno(provider): Returns the current sequence number (seqno). If the contract is not in an active state, it returns 0.
    const balance = await wallet.getBalance(provider);
    const seqno = await wallet.getSeqno(provider);
  10. Interact with Jettons using JettonMaster and JettonWallet

    main
    To work with Jettons (fungible tokens on TON), use JettonMaster to interact with the Jetton Master contract and JettonWallet to interact with individual user Jetton wallets.
  11. Manage Multisig wallets and orders

    main

    For multi-signature requirements, use the following components:

    • MultisigWallet: The contract representing the multisig account.
    • MultisigOrderBuilder: A utility to construct multisig orders.
    • MultisigOrder: Represents a specific pending or active multisig order.
  12. Instantiate WalletContractV1R1

    main

    Use WalletContractV1R1.create() to instantiate a new instance of the V1R1 wallet contract. You must provide the workchain, the user's publicKey as a Buffer, and an optional domain of type SignatureDomain.

    import { WalletContractV1R1 } from '@ton/ton';
    
    const wallet = WalletContractV1R1.create({
        workchain: 0,
        publicKey: Buffer.from('...'),
        domain: undefined // optional
    });
    
    console.log(wallet.address.toString());