TonWeb

repository·master·Indexed 20 days ago

https://github.com/toncenter/tonweb

A JavaScript SDK for The Open Network (TON) blockchain. TonWeb provides tools to interact with the blockchain, manage wallets, and construct binary messages (Cells/BOC) for smart contracts. It supports both browser-based environments and NodeJS, offering a comprehensive API for blockchain queries, wallet deployment, and low-level bit manipulation via BitString and Cell classes.

Tokens
23.2K
Snippets
89
Records
101
Agent score
72%

What's inside tonweb

  1. Explore TonWeb core classes and utilities

    master

    TonWeb provides several core classes and utility modules for interacting with the TON blockchain:

    • TonWeb.utils: Utility functions.
    • TonWeb.Address: Class for handling TON addresses.
    • TonWeb.boc: Class for handling Bag of Cells (BOC).
    • TonWeb.Contract: Class for interacting with smart contracts.
    • tonweb.wallet: Object containing wallet-related functionality.
  2. Use Lockup Wallets for restricted or temporary funds

    master

    Lockup wallets provide two main security features for managing funds:

    1. Temporary Locked: Funds cannot be spent at all until a specific time $X$.
    2. Temporary Restricted: Funds can only be sent to a predefined _white list (e.g., an elector) until a specific time $X$.

    Key constraints:

    • The wallet has exactly one immutable whitelist set at the time of contract deployment.
    • It supports multiple packages of locked or restricted money, each with its own time threshold.
    • Creating new locked/restricted packages requires the owner of the second public key (which is also immutable and set at deployment).
  3. Understand V4 Wallet plugins and functionality

    master

    V4 wallets differ from previous versions by supporting plugin functionality. Trusted conjugated contracts can implement complex logic while still being able to utilize all funds from the main wallet.

    This architecture allows the wallet to be extended for:

    • Partial, infinite, or programmatic allowances.
    • Special connectors for specific DApps.
    • Custom user-governed add-ons.

    For more details, refer to the original wallet-contract repository.

  4. Understand V1 Wallet revisions

    master

    V1 wallets are early TON smart contracts for managing TON coins. They primarily handle external messages to verify signatures and sequence numbers (seqno).

    • V1 (Original): Basic implementation for signature verification and seqno management.
    • V1 Revision 2: Adds a seqno get-method to retrieve the current sequence number.
    • V1 Revision 3: Adds both a seqno get-method and a get_public_key get-method.
  5. Understand the Wallet with Lockup balance categories

    master

    A Lockup-capable wallet manages three distinct categories of balances. When spending, the contract automatically checks which coins have satisfied their timelocks to make them liquid.

    1. Liquid: Coins that can be spent unconditionally.
    2. Locked: Coins that can be spent only after a specific timelock expires.
    3. Restricted: Coins that can be spent either after a timelock expires OR if sent to a whitelisted address.

    Note that Locked and Restricted coins are not single pools, but multiple pools, each with its own unique timelock.

  6. Understand V3 Wallet revisions and features

    master

    The V3 wallet introduces the subwallet_id parameter. This allows a user to create multiple distinct wallets using the same public key, preventing message replay attacks between different wallets.

    There are two primary revisions:

    • Original V3: Standard implementation.
    • Revision 2: Includes an additional get_public_key get-method to retrieve the wallet's public key.
  7. Understand V2 Wallet revisions

    master

    V2 wallets introduced several improvements over V1, including a valid_until parameter in messages and the ability to send up to 4 internal messages in a single transaction by processing each reference in the incoming message.

    • V2 Revision 1: Includes the valid_until parameter and multi-message support.
    • V2 Revision 2: Adds a get_public_key get-method to the existing V2 functionality.
  8. Implement UI for Lockup wallet balances and transactions

    master

    When building a UI for a Lockup wallet, follow these requirements:

    Balance Display

    The UI must display three separate balances. The sum of these three equals the total account balance:

    • liquid
    • locked
    • restricted

    Note: The contract's get methods recalculate the liquid balance based on the current time of the node (or the toncenter backend when using the tonweb client).

    Transaction Warnings

    If a user attempts to spend an amount that exceeds the liquid balance (minus estimated fees), the UI must warn the user: if the destination address is not whitelisted or the timelock has not expired, the transaction will fail, but the network fee will still be charged.

  9. Implement a custom smart contract by extending tonweb.Contract

    master

    Since TON does not have a standardized ABI or JSON interface, you must extend the tonweb.Contract abstract class to interact with your smart contracts. To implement a custom contract, you need to:

    1. Extend Contract: Create a class that inherits from tonweb.Contract.
    2. Initialize: Pass a provider and an options object (containing the contract code) to the super constructor.
    3. Define Methods: Manually attach methods to the this.method object.
    4. Override Lifecycle Methods: Implement createDataCell() and createSigningMessage() to enable deployment functionality.

    tonweb.Contract provides static helper functions to assist in composing messages:

    • Contract.createStateInit
    • Contract.createInternalMessageHeader
    • Contract.createExternalMessageHeader
    • Contract.createCommonMsgInfo
    export class MyContract extends Contract {
        constructor(provider, options) {
            options.code = hexToBytes('abcd..');
            super(provider, options);
    
            this.method.myMethod = ...
        }
    
        // @override
        createDataCell() {
            // Implementation required for deployment
        }
    
        // @override
        createSigningMessage() {
            // Implementation required for deployment
        }
    }
  10. Verify Lockup wallet integrity before funding

    master

    Before a funder provides coins with a timelock condition, they should verify the following to ensure the contract behaves as expected:

    1. The contract hash must match the expected one.
    2. The funder's public key (config_public_key) must be available to the funder.
    3. All whitelisted addresses must be permitted by the funder.
  11. Interact with wallet smart contracts using TonWeb

    master

    TonWeb provides an interface to interact with TON wallet smart contracts. Since there is no single standard wallet in TON, TonWeb implements various wallet smart contracts from the official TON repository. By default, tonweb.wallet.create initializes a Wallet V3 interface, but you can specify different configurations or use specific contract classes directly.

    const nacl = TonWeb.utils.nacl;
    const tonweb = new TonWeb();
    const keyPair = nacl.sign.keyPair();
    
    // Create interface to wallet smart contract (defaults to wallet v3)
    let wallet = tonweb.wallet.create({publicKey: keyPair.publicKey, wc: 0});
    
    // OR create interface using only an address
    let walletByAddress = tonweb.wallet.create({address: 'EQDjVXa_oltdBP64Nc__p397xLCvGm2IcZ1ba7anSW0NAkeP'});
  12. Use TonWeb as an alternative to Fift for binary messages

    master

    You can use tonweb globally to build binary messages for smart contracts, similar to how Fift is used.

    1. Install globally:
    npm install -g tonweb
    1. Set your NODE_PATH to include global npm modules:
    export NODE_PATH=$(npm root --quiet -g)
    1. Create a script (e.g., your_script.js) using require('tonweb') and run it with node.
    npm install -g tonweb
    export NODE_PATH=$(npm root --quiet -g)