# Ever SDK

Client libraries for DApp development in TVM blockchains (Everscale, Gosh, TON, Venom Blockchain, etc.).

Core Ever-SDK client library is written in Rust, with bindings in 11 programming languages.

**Get quick help in our telegram channel:**

[![Channel on Telegram](https://img.shields.io/badge/chat-on%20telegram-9cf.svg)](https://t.me/ever_sdk)

* [Ever SDK](#ever-sdk)
  * [Supported languages](#supported-languages)
    * [Rust (core library)](#rust-core-library)
    * [Official Javascript(Typescript) binding](#official-javascripttypescript-binding)
    * [Community bindings](#community-bindings)
    * [If you did not find the language you need](#if-you-did-not-find-the-language-you-need)
  * [Use-cases](#use-cases)
  * [Quick Start](#quick-start)
  * [How to avoid Soft Breaking Problems](#how-to-avoid-soft-breaking-problems)
  * [Build client library](#build-client-library)
  * [Build artifacts](#build-artifacts)
  * [Run tests](#run-tests)
  * [Download precompiled binaries](#download-precompiled-binaries)

## Supported languages

### Rust (core library)

Repository: <https://github.com/everx-labs/ever-sdk>

**What is Core Client Library?**

Core Client Library is written in Rust that can be dynamically linked. It provides all heavy-computation components and functions, such as TON Virtual Machine, TON Transaction Executor, ABI-related functions, boc-related functions, crypto functions.

The decision to create the Rust library was made after a period of time using pure JavaScript to implement these use cases.

We ended up with very slow work of pure JavaScript and decided to move all this to Rust library and link it to Javascript as a compiled binary including a wasm module for browser applications.

Also, this approach provided an opportunity to easily create bindings for any programming language and platform, thus, to make it possible to develop distributed applications (DApps) for any possible use-cases, such as: mobile DApps, web DApps, server-side DApps, enterprise DApp etc.

Client Library exposes all the functionality through a few of exported functions. All interaction with library is performed using JSON-RPC like protocol.

### Official Javascript(Typescript) binding

Repository: [JavaScript SDK](https://github.com/everx-labs/ever-sdk-js)

You need to install core package and the package with binary for your platform. [See the documentation.](https://github.com/everx-labs/ever-sdk-js#library-distribution)

| Platform                       | Package                                                                                                              |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| core package for all platforms | [@eversdk/core](https://github.com/everx-labs/ever-sdk-js#install-core-package)                                      |
| Node.js                        | [@eversdk/lib-node](https://github.com/everx-labs/ever-sdk-js#nodejs)                                                |
| Web                            | [@eversdk/lib-web](https://github.com/everx-labs/ever-sdk-js#web)                                                    |
| React-Native                   | [@eversdk/lib-react-native](https://github.com/everx-labs/ever-sdk-js#react-native)                                  |
| React-Native with JSI support  | [@eversdk/lib-react-native-jsi](https://github.com/everx-labs/ever-sdk-js/tree/master/packages/lib-react-native-jsi) |

### Community bindings

| Language | Repository                                                                                                                                                                               |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Clojure  | [serge-medvedev/tonos-client-clojure](https://github.com/serge-medvedev/tonos-client-clojure)                                                                                            |
| Golang   | <p><a href="https://github.com/radianceteam/ton-client-go">radianceteam/ton-client-go</a><br><a href="https://github.com/markgenuine/ever-client-go">markgenuine/ever-client-go</a></p>  |
| Java     | <p><a href="https://github.com/radianceteam/ton-client-java">radianceteam/ton-client-java</a><br><a href="https://github.com/deplant/java4ever-binding">laugan/java4ever-binding</a></p> |
| Kotlin   | [mdorofeev/ton-client-kotlin](https://github.com/mdorofeev/ton-client-kotlin)                                                                                                            |
| Lua      | [serge-medvedev/tonos-client-lua](https://github.com/serge-medvedev/tonos-client-lua)                                                                                                    |
| .NET     | [everscale-actions/everscale-dotnet](https://github.com/everscale-actions/everscale-dotnet)                                                                                              |
| PHP      | <p><a href="https://github.com/extraton/php-ton-client">extraton/php-ton-client</a><br><a href="https://github.com/radianceteam/ton-client-php">radianceteam/ton-client-php</a></p>      |
| Python   | [move-ton/ton-client-py](https://github.com/move-ton/ton-client-py)                                                                                                                      |
| Ruby     | [nerzh/ton-client-ruby](https://github.com/nerzh/ton-client-ruby)                                                                                                                        |
| Scala    | [radianceteam/ton-client-scala](https://github.com/radianceteam/ton-client-scala)                                                                                                        |
| Swift    | [nerzh/ton-client-swift](https://github.com/nerzh/ton-client-swift)                                                                                                                      |

### If you did not find the language you need

* use library module `json_interface` which provides access to library functions through JSON-RPC interface. This interface exports several extern "C" functions. So you can build a dynamic or static link library and link it to your application as any other external libraries. The JSON Interface is fully "C" compliant. You can find description in section [JSON Interface](/ever-sdk/for-binding-developers/json_interface).
* write your own binding to chosen language and share it with community.

If you choose using JSON Interface please read this document [JSON Interface](/ever-sdk/for-binding-developers/json_interface).\
Here you can find directions how to use `json_interface` and write your own binding.

## Use-cases

With Ever-SDK you can implement logic of any complexity on TVM compatible blockchains (Everscale, Gosh, TON, Venom, etc.).

* Create and send messages to blockchain
* Process messages reliably (supports retries and message expiration mechanics)
* Supports TON Solidity and ABI compatible contracts
* Emulate transactions locally
* Run get methods
* Get account state
* Query blockchain data (blocks, transactions, messages)
* Subscribe to events and any other blockchain updates (literally)
* Sign data/check signature, calculate hashes (sha256, sha512), encrypt/decrypt data
* Validate addresses
* Work with blockchain native types (bag of cells or BOCs): encode, decode, calculate hash, etc
* Works on top of GraphQL API and compatible with Evernode-SE/DS, Evercloud.

## Quick Start

Get your endpoint at [dashboard.evercloud.dev](https://dashboard.evercloud.dev/) or run Evernode-SE (local node) or Dapp Server (self-hosted blockchain node).

See the list of available TVM networks: <https://docs.everplatform.dev/products/evercloud/networks-endpoints>

[Quick Start (Javascript binding)](/ever-sdk/quick_start)

[Error descriptions](/ever-sdk/reference/error_codes)

[JavaScript SDK Types and Methods (API Reference)](https://everx-labs.github.io/ever-sdk-js/)

[Core Types and Methods (API Reference)](/ever-sdk/reference/types-and-methods/modules)

[Guides](/ever-sdk/guides/installation/add_sdk_to_your_app)

## How to avoid Soft Breaking Problems

Soft Breaking is API changes that include only new optional fields in the existing structures. These changes are fully backward compatible for JSON Interface.

But in Rust such changes can produce some problems with an old client code.

Look at the example below:

1. There is an API v1.0 function `foo` and the corresponding params structure:

```rust
#[derive(Default)]
struct ParamsOfFoo {
    pub foo: String,
}

pub fn foo(params: ParamsOfFoo)
```

1. Application uses this function in this way:

```rust
foo(ParamsOfFoo {
    foo: "foo".into(),
});
```

1. API v.1.1 introduces new field in `ParamsOfFoo`:

```rust
#[derive(Default)]
struct ParamsOfFoo {
    pub foo: String,
    pub bar: Option<String>,
}
```

From the perspective of JSON-interface it isn't breaking change because the new parameter is optional. But code snippet (2) will produce Rust compilation error.

1. To avoid such problems we recommend to use default implementation inside structure initialisation:

```rust
foo(ParamsOfFoo {
    foo: "foo".into(),
    ..Default::default(),
});
```

For all Ton Client API structures `Default` trait is implemented.

## Build client library

The best way to build client libraries is to use build scripts from this repo.

**Note**: The scripts are written in JavaScript, so you have to install Node.js (v.10 or newer) to run them. Also make sure you have the latest version of Rust installed.

To build a binary for a specific target (or binding), navigate to the relevant folder and run `node build.js`.

The resulting binaries are placed to `bin` folder in the gz-compressed format.

Note that the build script generates binaries compatible with the platform used to run the script. For example, if you run it on macOS, you get binaries targeted at Darwin (macOS) platform.

**Note**: You need latest version of rust. Upgrade it with `rustup update` command. Check version with `rustc --version`, it should be above or equal to `1.47.0`.

## Build artifacts

Rebuild `api.json`:

```shell
cd evercli
cargo run api -o ../tools
```

Rebuild `docs`:

```shell
cd tools
npm i
tsc
node index docs -o ../docs
```

Rebuild `modules.ts`:

```shell
cd tools
npm i
tsc
node index binding -l ts -o ../../ever-sdk-js/packages/core/src
```

## Run tests

To run test suite use standard Rust test command

```
cargo test
```

SDK tests need [EVER OS API](https://docs.everplatform.dev/reference/graphql-api/networks) endpoint to run on. Such an API is exposed by a [DApp Server](https://github.com/everx-labs/evernode-ds) which runs in real networks and by local blockchain [Evernode SE](https://github.com/everx-labs/evernode-se).

Evernode SE is used by default with address `http://localhost` and port 80. If you launch it on another port you need to specify it explicitly like this: `http://localhost:port`. If you have Evernode SE running on another address or if you need to run tests on a real Everscale network, use the following environment variables to override the default parameters

```
TON_USE_SE: true/false - flag defining if tests run against Evernode SE or a real network (DApp Server)
TON_NETWORK_ADDRESS - Dapp server or Evernode SE addresses separated by comma.
TON_GIVER_SECRET - Giver secret key. If not defined, default Evernode SE giver keys are used
TON_GIVER_ADDRESS - Address of the giver to use for prepaying accounts before deploying test contracts. If not defined, the address is calculated using `GiverV2.tvc` and configured public key
EVERCLOUD_AUTH_PROJECT – Evercloud project id used to authorise tests that requires main net interaction 
```

## Download precompiled binaries

Instead of building library yourself, you can download the **latest** precompiled binaries from EverX SDK Binaries Store.

| Platform | Major | Download links                                                                                                                                             |
| -------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Win32    | 0     | [`ever_client.lib`](https://binaries.everx-labs.io/tonclient_0_win32_lib.gz), [`ever_client.dll`](https://binaries.everx-labs.io/tonclient_0_win32_dll.gz) |
|          | 1     | [`ever_client.lib`](https://binaries.everx-labs.io/tonclient_1_win32_lib.gz), [`ever_client.dll`](https://binaries.everx-labs.io/tonclient_1_win32_dll.gz) |
| macOS    | 0     | [`libton_client.dylib`](https://binaries.everx-labs.io/tonclient_0_darwin.gz)                                                                              |
|          | 1     | (x86\_64)[`libton_client.dylib`](https://binaries.everx-labs.io/tonclient_1_darwin.gz)                                                                     |
|          | 1     | (aarch64)[`libton_client.dylib`](https://binaries.everx-labs.io/tonclient_1_darwin_arm64.gz)                                                               |
| Linux    | 0     | [`libton_client.so`](https://binaries.everx-labs.io/tonclient_0_linux.gz)                                                                                  |
|          | 1     | [`libton_client.so`](https://binaries.everx-labs.io/tonclient_1_linux.gz)                                                                                  |

If you want an older version of library (e.g. `0.25.0` for macOS), you need to choose a link to your platform from the list above and replace `0` with a version: [https://binaries.everx-labs.io/tonclient\_**0\_25\_0**\_darwin.gz](https://binaries.everx-labs.io/tonclient_0_25_0_darwin.gz)

*Downloaded archive is gzipped file*


# Quick start (JavaScript)

Create your first DApp and run it on local blockchain

* [Prerequisites](#prerequisites)
* [Prepare development environment](#prepare-development-environment)
* [Start local node (SE)](#start-local-node-se)
* [Install demo application](#install-demo-application)
* [What the script does](#what-the-script-does)
* [Sample code](#sample-code)
* [Run it!](#run-it)
* [Source code](#source-code)

## Prerequisites

Node.js latest version installed [Docker](https://www.docker.com/get-started) latest version installed

## Prepare development environment

Install [EVERDEV CLI](https://github.com/everx-labs/everdev) that will help you easily start local node, compile your contracts, install demo projects and create new empty projects.

```shell
$ npm install -g everdev
```

## Start local node (SE)

We will run our test on local blockchain for testing ([Evernode SE](https://github.com/everx-labs/evernode-se), start it with this command (docker should be launched).

```
$ everdev se start
```

## Install demo application

Create a working folder. Then create a node.js demo project with EVERDEV

```
$ everdev js demo hello-wallet
$ cd hello-wallet
$ npm i
```

## What the script does

The script implements the following logic:

1. Links the project with Node.js [Ever-SDK](https://github.com/everx-labs/ever-sdk) binary. If you plan to use JS SDK in Web, link it with Wasm binary. Read more [here](https://github.com/everx-labs/ever-sdk-js).
2. `TONClient` instance is created and initialized with [Evernode SE](https://github.com/everx-labs/evernode-se) ("<http://localhost>", local blockchain) endpoint. See the list of other available [endpoints](https://docs.everplatform.dev/reference/graphql-api/networks).
3. Future address is calculated from the code and data of the contract (data includes signing keys)
4. Flag `useGiver: true` allows to sponsor deploy with Evernode SE giver that is hard coded as the default Account giver. [You can re-assign it to your own giver](/ever-sdk/guides/work_with_contracts/deploy#transfer-funds-to-the-future-address).

## Sample code

{% tabs %}
{% tab title="Core API Implementation" %}

```javascript
(async () => {
    try {
        // Generate an ed25519 key pair
        const walletKeys = await client.crypto.generate_random_sign_keys();

        // Calculate future wallet address.
        const walletAddress = await calcWalletAddress(walletKeys);

        // Send some tokens to `walletAddress` before deploy
        await getTokensFromGiver(walletAddress, 1_000_000_000);

        // Deploy wallet
        await deployWallet(walletKeys);

        // Get wallet's account info and print balance
        const accountState = await getAccount(walletAddress);
        console.log("Hello wallet balance is", accountState.balance)

        // Run account's get method `getTimestamp`
        let walletTimestamp = await runGetMethod('getTimestamp', walletAddress, accountState.boc );
        console.log("`timestamp` value is", walletTimestamp)

        // Perform 2 seconds sleep, so that we receive an updated timestamp
        await new Promise(r => setTimeout(r, 2000));
        // Execute `touch` method for newly deployed Hello wallet contract
        // Remember the logical time of the generated transaction
        let transLt = await runOnChain(walletAddress, "touch");

        // Run contract's get method locally after account is updated
        walletTimestamp = await runGetMethodAfterLt('getTimestamp', walletAddress, transLt);
        console.log("Updated `timestamp` value is", walletTimestamp)

        // Send some tokens from Hello wallet to a random account
        // Remember the logical time of the generated transaction
        const destAddress = await genRandomAddress();
        transLt = await sendValue(walletAddress, destAddress, 100_000_000, walletKeys);

        console.log('Normal exit');
        process.exit(0);
    } catch (error) {
        if (error.code === 504) {
            console.error(
                [
                    'Network is inaccessible. You have to start Evernode SE using `everdev se start`',
                    'If you run SE on another port or ip, replace http://localhost endpoint with',
                    'http://localhost:port or http://ip:port in index.js file.',
                ].join('\n'),
            );
        } else {
            console.error(error);
            process.exit(1);
        }
    }
})();

async function calcWalletAddress(keys) {
    // Get future `Hello`Wallet contract address from `encode_message` result
    const { address } = await client.abi.encode_message(buildDeployOptions(keys));
    console.log(`Future address of Hello wallet contract is: ${address}`);
    return address;
}

function buildDeployOptions(keys) {
    // Prepare parameters for deploy message encoding
    // See more info about `encode_message` method parameters here:
    // https://github.com/everx-labs/ever-sdk/blob/master/docs/reference/types-and-methods/mod_abi.md#encode_message
    const deployOptions = {
        abi: {
            type: 'Contract',
            value: HelloWallet.abi,
        },
        deploy_set: {
            tvc: HelloWallet.tvc,
            initial_data: {},
        },
        call_set: {
            function_name: 'constructor',
            input: {},
        },
        signer: {
            type: 'Keys',
            keys,
        },
    };
    return deployOptions;
}

// Request funds from Giver contract
async function getTokensFromGiver(dest, value) {
    console.log(`Transfering ${value} tokens from giver to ${dest}`);

    const params = {
        send_events: false,
        message_encode_params: {
            address: GIVER_ADDRESS,
            abi: abiContract(GIVER_ABI),
            call_set: {
                function_name: 'sendTransaction',
                input: {
                    dest,
                    value,
                    bounce: false,
                },
            },
            signer: {
                type: 'Keys',
                keys: GIVER_KEYS,
            },
        },
    };
    await client.processing.process_message(params);
    console.log('Success. Tokens were transfered\n');
}

async function deployWallet(walletKeys) {
    // Deploy `Hello wallet` contract
    // See more info about `process_message` here:
    // https://github.com/everx-labs/ever-sdk/blob/master/docs/reference/types-and-methods/mod_processing.md#process_message
    console.log('Deploying Hello wallet contract');
    await client.processing.process_message({
        send_events: false,
        message_encode_params: buildDeployOptions(walletKeys),
    });
    console.log('Success. Contract was deployed\n');
}

async function runOnChain(address, methodName) {
    // Encode the message with external call
    const params = {
        send_events: false,
        message_encode_params: {
            address,
            abi: {
                type: 'Contract',
                value: HelloWallet.abi,
            },
            call_set: {
                function_name: methodName,
                input: {},
            },
            signer: signerNone(),
        },
    };
    console.log(`Calling ${methodName} function`);
    const response = await client.processing.process_message(params);
    const { id, lt } = response.transaction;
    console.log('Success. TransactionId is: %s\n', id);
    return lt;
}


// Sometimes it is needed to execute getmethods after on-chain calls.
// This means that the downloaded account state should have the changes made by the on-chain call. 
// To ensure it, we need to remember the transaction lt (logical time) of the last call
// and then wait for the account state to have lt > the transaction lt. 
// Note that account.last_trans_lt is always bigger than transaction.lt because this field stores the end lt of transaction interval
// For more information about transaction lt interval read TON Blockchain spec https://test.ton.org/tblkch.pdf P. 4.2.1
async function waitForAccountUpdate(address, transLt) {
    console.log('Waiting for account update');
    const startTime = Date.now();
    const account = await client.net.wait_for_collection({
        collection: 'accounts',
        filter: {
            id: { eq: address },
            last_trans_lt: { gt: transLt },
        },
        result: 'boc',
    });
    const duration = Math.floor((Date.now() - startTime) / 1000);
    console.log(`Success. Account was updated, it took ${duration} sec.\n`);
    return account;
}


async function getAccount(address) {

    // `boc` or bag of cells - native blockchain data layout. Account's boc contains full account state (code and data) that
    // we will  need to execute get methods.
    const query = `
        query {
          blockchain {
            account(
              address: "${address}"
            ) {
               info {
                balance(format: DEC)
                boc
              }
            }
          }
        }`
    const {result}  = await client.net.query({query})
    const info = result.data.blockchain.account.info
    return info
}
async function runGetMethod(methodName, address, accountState) {
    // Execute the get method `getTimestamp` on the latest account's state
    // This can be managed in 3 steps:
    // 1. Download the latest Account State (BOC) 
    // 2. Encode message
    // 3. Execute the message locally on the downloaded state

    // Encode the message with `getTimestamp` call
    const { message } = await client.abi.encode_message({
        // Define contract ABI in the Application
        // See more info about ABI type here:
        // https://github.com/everx-labs/ever-sdk/blob/master/docs/reference/types-and-methods/mod_abi.md#abi
        abi: {
            type: 'Contract',
            value: HelloWallet.abi,
        },
        address,
        call_set: {
            function_name: methodName,
            input: {},
        },
        signer: { type: 'None' },
    });

    // Execute `getTimestamp` get method  (execute the message locally on TVM)
    // See more info about run_tvm method here:
    // https://github.com/everx-labs/ever-sdk/blob/master/docs/reference/types-and-methods/mod_tvm.md#run_tvm
    console.log('Run `getTimestamp` get method');
    const response = await client.tvm.run_tvm({
        message,
        account: accountState,
        abi: {
            type: 'Contract',
            value: HelloWallet.abi,
        },
    });
    return response.decoded.output
}


async function runGetMethodAfterLt(methodName, address, transLt) {
    // Wait for the account state to be more or equal the spesified logical time
    const accountState = await waitForAccountUpdate(address, transLt).then(({ result }) => result.boc);
    const result = await runGetMethod(methodName, address, accountState);
    return result;
    
}

async function sendValue(address, dest, amount, keys) {
    // Encode the message with `sendValue` function call
    const sendValueParams = {
        send_events: false,
        message_encode_params: {
            address,
            // Define contract ABI in the Application
            // See more info about ABI type here:
            // https://github.com/everx-labs/ever-sdk/blob/master/docs/reference/types-and-methods/mod_abi.md#abi
            abi: {
                type: 'Contract',
                value: HelloWallet.abi,
            },
            call_set: {
                function_name: 'sendValue',
                input: {
                    dest,
                    amount,
                    bounce: false,
                },
            },
            signer: signerKeys(keys),
        },
    };
    console.log(`Sending ${amount} tokens to ${dest}`);
    // Call `sendValue` function
    const response = await client.processing.process_message(sendValueParams);
    console.log('Success. Target account will recieve: %d tokens\n', response.fees.total_output);
    return response.transaction.lt;
}
```

{% endtab %}

{% tab title="AppKit API Implementation" %}

```javascript
async function main(client) {
    // Generate an ed25519 key pair for new account
    const keys = await TonClient.default.crypto.generate_random_sign_keys();

    const helloAcc = new Account(HelloWallet, {
        signer: signerKeys(keys),
        client,
    });

    const address = await helloAcc.getAddress();
    console.log(`Future address of the contract will be: ${address}`);

    // Request contract deployment funds form a local Evernode SE giver
    // not suitable for other networks.
    // Deploy `hello` contract.
    await helloAcc.deploy({ useGiver: true });
    console.log(`Hello contract was deployed at address: ${address}`);

    // Call `touch` function on-chain
    // On-chain execution can be done with `run` function. 
    let response = await helloAcc.run("touch", {});
    console.log(`touch execution transaction is  ${response.transaction.id}`);

    // Read local variable `timestamp` with a get method `getTimestamp`
    // This can be done with `runLocal` function. The execution of runLocal is performed off-chain and does not 
    // cost any gas.
    response = await helloAcc.runLocal("getTimestamp", {});
    console.log("getTimestamp value:", response.decoded.output)

    // Send some money to the random address
    const randomAddress = 
        "0:" + 
        Buffer.from((await client.crypto.generate_random_bytes({length: 32})).bytes, "base64").toString("hex");
    response = await helloAcc.run("sendValue", {
        dest: randomAddress,
        amount: 100_000_000, // 0.1 token
        bounce: true, // delivery will fail and money will be returned back because the random account does not exist.
    });
    console.log(`The tokens were sent, but soon they will come back because bounce = true and destination address does not exist`);
}

(async () => {
    const client = new TonClient({
        network: {
            // Local Evernode-SE instance URL here
            endpoints: ["http://localhost"]
        }
    });
    try {
        console.log("Hello localhost!");
        await main(client);
        process.exit(0);
    } catch (error) {
        if (error.code === 504) {
            console.error(`Network is inaccessible. You have to start Evernode SE using \`everdev se start\`.\n If you run SE on another port or ip, replace http://localhost endpoint with http://localhost:port or http://ip:port in index.js file.`);
        } else {
            console.error(error);
        }
    }
    client.close();
})();
```

{% endtab %}
{% endtabs %}

## Run it!

### Core API

Run:

```
$ node core
```

You will see the result of core.js file execution. Core.js file demonstrades core ever-sdk api. It is the same for all ever-sdk bindings.

```
node core
Future address of Hello wallet contract is: 0:1863addf562c5ab98f3761787458e47406675379a4dc6eb36042ba84bde5cb8d
Transfering 1000000000 tokens from giver to 0:1863addf562c5ab98f3761787458e47406675379a4dc6eb36042ba84bde5cb8d
Success. Tokens were transfered

Deploying Hello wallet contract
Success. Contract was deployed

Hello wallet balance is 986483999
Run `getTimestamp` get method
`timestamp` value is {
  value0: '0x000000000000000000000000000000000000000000000000000000006373fbb4'
}
Calling touch function
Success. TransactionId is: 1a34fbfc336ff8212793077c68bff9f49c6c3f270492afa55ca616ef40b22bec

Waiting for account update
Success. Account was updated, it took 0 sec.

Run `getTimestamp` get method
Updated `timestamp` value is {
  value0: '0x000000000000000000000000000000000000000000000000000000006373fbb6'
}
Sending 100000000 tokens to 0:9f98e8de89e19093145afe134017a783daf8bac5dee04b8810c57a348020764c
Success. Target account will recieve: 99000000 tokens

Normal exit
```

### Appkit API

Run:

```
$ node appkit
```

You will see the result of appkit.js file execution. Appkit.js demonstrates high level Appkit package.

```
Hello localhost!
Future address of the contract will be: 0:5aab70b197897e47ee65faca0ebe24244fd1373d31de2ae39aca28029e0f3469
Hello contract was deployed at address: 0:5aab70b197897e47ee65faca0ebe24244fd1373d31de2ae39aca28029e0f3469
touch execution transaction is  495d0b02905ac541b54407283e52155fbfcbcc804a82ca40d5da96e433fe2f6b
getTimestamp value: {
  value0: '0x000000000000000000000000000000000000000000000000000000006373fa68'
}
The tokens were sent, but soon they will come back because bounce = true and destination address does not exist
```

## Source code

You can find full source code of this sample here

<https://github.com/everx-labs/sdk-samples/tree/master/demo/hello-wallet>


# Add EVER to your backend

This document describes the various ways to accomplish the most important tasks of running a backend project that supports EVER.

## Introduction

This document describes the various ways to accomplish the most important tasks of running a backend application that supports EVER.

There are a few different ways to accomplish the necessary tasks:

* Blockchain access may be set up either through the [Evercloud](https://docs.everplatform.dev/products/evercloud/get-started) or through your own supernode - the [DApp server](https://docs.everplatform.dev/products/dapp-server-ds).
* User account management can be accomplished either through the [everdev](https://docs.everos.dev/everdev/) command line tool or integrate into your backend with EVER-SDK client libraries. Both of these approaches are compatible with either of the blockchain access setups.

## Setting up Blockchain Access

### Using Evercloud

Using [Evercloud](https://docs.everplatform.dev/products/evercloud/get-started) allows you to work with TVM blockchains without having to run your own node. Everdev and SDK can connect to it, as if it were a regular node. It has the same API as a node, and provides all neede capabilities.

This page lists the [cloud endpoints](https://docs.everplatform.dev/products/evercloud/networks-endpoints). To get access credentials go through this [guide](https://docs.everplatform.dev/products/evercloud/get-started).

Whenever you have to specify a network endpoint in the examples given below, use the endpoints and credentials you receive in the [Evercloud dashboard](https://dashboard.evercloud.dev/projects).

{% hint style="info" %}
Note: We recommend testing out the full setup on the developer network first.
{% endhint %}

### Using DApp Server

If you prefer to run your own node, you may set up your own [DApp server](https://docs.everplatform.dev/products/dapp-server-ds). It is a client supernode, that may be set up on your own servers and provide full access to TVM networks. To connect to it with Everdev or SDK, it needs to have a domain name and a DNS record. You can specify its URL whenever you have to set the network in the examples given below.

Get the setup scripts in this repository: <https://github.com/everx-labs/evernode-ds>

#### 1. System Requirements

<table><thead><tr><th width="169">Configuration</th><th>CPU (cores)</th><th>RAM (GiB)</th><th>Storage (GiB)</th><th>Network (Gbit/s)</th></tr></thead><tbody><tr><td>Recommended</td><td>24</td><td>128</td><td>2000</td><td>1</td></tr></tbody></table>

NVMe SSD disks are recommended for storage.

{% hint style="info" %}
For simplicity, all services are deployed on one host and the system requirements for it are high, so it makes sense to distribute services across different servers.\
After understanding this installation process, you can easily customize it for yourself.

[itgoldio/everscale-dapp-server](https://github.com/itgoldio/everscale-dapp-server): Consider this project if you prefer deployment via Ansible.
{% endhint %}

#### 2.1 Prerequisites

* Host OS: Linux (all scripts tested on Ubuntu 20.04).
* DApp server is accessed via HTTPS, so your server must have a fully qualified domain name.\
  A self-signed certificate will be received on start-up and will be renewed automatically.
* Installed Git, Docker Engine, Docker CLI, Docker Compose v2 or later.

#### 2.2 Configuration

**2.2.1 Set variables**

Check `configure.sh` and set at least these environment variables:

* NETWORK\_TYPE
* EVERNODE\_FQDN
* LETSENCRYPT\_EMAIL

**2.2.2 Generate credentials to access the ArangoDB web interface**

Generate credentials (usernames and password) for basic authentication and update `.htpasswd` file.\
You can generate it by running `htpasswd -nb <name> <password>`

**2.2.3 Run configuration script**

```
$ ./configure.sh
```

This script creates `./deploy` directory

#### 2.3 Deployment

Run `./up.sh`.

After the script completes normally (it takes 30 min approx.), the node starts synchronizing its state, which can take several hours.\
Use the following command to check the progress:

```
    docker exec rnode /ton-node/tools/console -C /ton-node/configs/console.json --cmd getstats
```

Script output example:

```
everx-labs console 0.1.286
COMMIT_ID: 5efe6bb8f2a974ba0e6b1ea3e58233632236e182
BUILD_DATE: 2022-10-17 02:32:44 +0300
COMMIT_DATE: 2022-08-12 00:22:07 +0300
GIT_BRANCH: master
{
	"sync_status":	"synchronization_finished",
	"masterchainblocktime":	1665988670,
	"masterchainblocknumber":	9194424,
	"node_version":	"0.51.1",
	"public_overlay_key_id":	"S4TaVdGitzTApe7GFCj8DbuRIkVEbg+ODzBxhQGIUG0=",
	"timediff":	6,
	"shards_timediff":	6,
     ----%<---------------------
}
```

If the `timediff` parameter is less than 10 seconds, synchronization with masterchain is complete.\
`"sync_status": "synchronization finished"` means synchronization with workchains is complete

## Setting up Wallet Account

Currently we can recommend the [SetcodeMultisig](https://github.com/EverSurf/multisig2) contract for use in user accounts. It is well tested and secure, supports multiple custodians, and can be set up to require several independent signatures for any transfers.

### Using CLI tool

[Everdev](https://docs.everos.dev/everdev/), the command line tool for development on the Everscale blockchain, allows to write scripts to deploy any smart contracts to the blockchain, call all contract methods, sign transactions, and generally manage an account.

It works with both Evercloud and DApp server.

#### 1. Install Everdev

```sh
$ npm install -g everdev
```

It requires [NPM](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) to be installed.

If you experience any problems with installation, check out our [troubleshooting](https://docs.everos.dev/everdev/troubleshooting) section.

#### 2. Configure network connection

Everdev has a built-in [network](https://docs.everos.dev/everdev/command-line-interface/network-tool) tool to manage your networks and access credentials.

**Using Evercloud endpoints**

Add your Evercloud endpoint to everdev and make it default:

```
everdev network add networkName <your-evercloud-endpoint>
everdev network default networkName
```

**Using DApp Server endpoint**

* If you are setting up a connection via your own DApp server, user the following command to add it to the network list (it will be named `dappserver`).

```shell
everdev network add dappserver <your_dapp_server_endpoint>
```

To set your `dappserver` network as default, use the following command:

```sh
everdev network default dappserver
```

#### 3. Set a giver contract on your network

On Everscale, you need to sponsor a contract address in advance to be able to deploy the contract.

Everdev provides a way to set an account of your choice as a giver for deployment operations, so you will not have to do a separate step of sending tokens to a new contract address every time you deploy something. This contract can some multisig wallet, for example your [Surf](https://ever.surf/) account.

**Note**: To work automatically, the giver contract should have only one custodian.

To set it up, first save the custodian keys of your giver account into a signer that will be used to sign giver transactions (Learn more about the signer tool [here](https://docs.everos.dev/everdev/command-line-interface/signer-tool)):

```sh
everdev signer add giver_sign signer_secret_key_or_seed_phrase_in_quotes
```

Then add the giver address specifying the signer to be used with it.

```sh
everdev network giver network_name giver_address --signer giver_sign --type giver_type
```

Where

`giver_type` is the type of the giver contract you selected (GiverV1 | GiverV2 | GiverV3 | SafeMultisigWallet | MsigV2| SetcodeMultisigWallet)

{% hint style="warning" %}
We recommend using [Multisig 2.0 ](https://github.com/EverSurf/multisig2)as giver, for that use `MsigV2` giver\_type.
{% endhint %}

#### 4. Get wallet account contract files

We recommend using[ Multisig 2.0](https://github.com/EverSurf/multisig2) contracts as a wallet. They can be found [here](https://github.com/EverSurf/multisig2). In this guide SetcodeMultisig specifically is used.

Download the contract files and place them in the working folder. Direct links to its files are as follows:

**.tvc** - Compiled contract code

SetcodeMultisig.tvc direct link:

{% embed url="<https://github.com/EverSurf/multisig2/raw/main/build/SetcodeMultisig.tvc>" %}

**.abi.json** - application binary interface, describing the functions of the contract

SetcodeMultisig.abi.json direct link:

{% embed url="<https://raw.githubusercontent.com/EverSurf/multisig2/main/build/SetcodeMultisig.abi.json>" %}

Execute the commands of the following steps from the directory with the contract files.

#### 5. Create wallet account signer

To generate your wallet account signer enter the following command:

```shell
everdev signer generate wallet_signer
```

Or, if you already have a seed phrase, add it like this:

```
everdev signer add "your-seed-phrase-here"
```

To deploy multisig wallet account you will need to specify the public key of the signer. To view it, use the following command:

```sh
everdev signer info wallet_signer
```

The keys will be displayed in terminal (if you imported the seed phrase, it will be displayed here as well):

```sh
{
    "name": "wallet_signer",
    "description": "",
    "keys": {
        "public": "8f8779e7c1944b133a423df96d06ae770c996f19d63438dbf2f569a29529b248",
        "secret": "ce57d2666d0d2c737a03ca4e6cfa38c5ca088dbcef43eb0353896feca8aea2a5"
    }
}

```

Usually a single owner (with a single signer) per wallet account is optimal for any tasks that require automation. However, it is possible to set up accounts with multiple owners. In this case, each of the owners has to generate their own signer and provide their public keys to the deployer. Also, the signer used to deploy the account doesn't have to be among its owners.

#### 6. Deploy the wallet account contract to blockchain

Use the following command for a simple one-owner account:

```shell
everdev contract deploy SetcodeMultisig.abi.json constructor --signer wallet_signer --input owners:[<owner_public_key>],reqConfirms:1,lifetime:3600 --value 1000000000
```

Where

`value` parameter is the amount of nanotokens to be spent on deployment (can be omitted, in which case 10 tokens from giver will be spent)

`owner_public_key` is usually [the public key](#6.-create-deposit-account-signer) of `wallet_signer` in the form `0x...`.

`lifetime` - time in seconds that a transaction in multi-owner accounts will persits and be available for signing by other owners. For a simple multi owner account may be set to any value, as it will be executed immediately anyway.

Example:

{% code overflow="wrap" %}

```sh
everdev contract deploy SetcodeMultisig.abi.json constructor --signer wallet_signer --input owners:[0x8f8779e7c1944b133a423df96d06ae770c996f19d63438dbf2f569a29529b248],reqConfirms:1,lifetime:3600 --value 1000000000
```

{% endcode %}

For more complex cases (multiple owners etc.) view Everdev contract tool [docs](https://docs.everos.dev/everdev/command-line-interface/contract-management).

Once the contract is deployed, its address will be displayed in terminal.

```sh
everdev contract deploy SetcodeMultisig.abi.json constructor --signer wallet_signer --input owners:[0x3da1909b7a4bd11fd9a1d79ca9713a9a8645880e0a7a12f9691c68e95d56fe75],reqConfirms:1,lifetime:3600 --value 10000000000

Configuration

  Network: dev (devnet.evercloud.dev)
  Signer:  wallet_signer (public 8f8779e7c1944b133a423df96d06ae770c996f19d63438dbf2f569a29529b248)

Address:   0:95c35b94e98c1b5c7716a9129ed5bb0798c8c336465fd8d1eb0d385e3d969494 (calculated from TVC and signer public)

Parameters of constructor:

  owners (uint256[]): ["0x3da1909b7a4bd11fd9a1d79ca9713a9a8645880e0a7a12f9691c68e95d56fe75"]
  reqConfirms (uint8): "1"
  lifetime (uint32): "3600"

Deploying...
Contract is deployed at address: 0:95c35b94e98c1b5c7716a9129ed5bb0798c8c336465fd8d1eb0d385e3d969494

```

### Using SDK

You may integrate above described process of wallet account deployment into your backend code. The functionality is supported in SDK.

A sample is available in [this repository](https://github.com/everx-labs/sdk-samples/tree/master/demo/msig-wallet) and an overview is given below.

{% hint style="info" %}
[Bindings](https://docs.everos.dev/ever-sdk/#community-bindings) for a large number of languages have been developed for SDK.
{% endhint %}

Note, that similar to the Everdev approach described above, you have to sponsor a user account before deploying contract code. The sample assumes you use the devnet faucet of [Evercloud Dashboard](https://dashboard.evercloud.dev/), where you can request test tokens to the contract address generated by the sample. In a production environment you may set up a giver to sponsor your contract deployment operations. An example of such a set up can be found in this [sample](https://github.com/everx-labs/sdk-samples/tree/master/demo/hello-wallet).

The recommended [SetcodeMultisig](https://github.com/everx-labs/sdk-samples/blob/master/demo/msig-wallet/contract/SetcodeMultisig.sol) contract is used.

```typescript

 async function main(client: TonClient) {
    // 
    // 1. ------------------ Deploy multisig wallet --------------------------------
    // 
    // Generate a key pair for the wallet to be deployed
    const keypair = await client.crypto.generate_random_sign_keys();

    // TODO: Save generated keypair!
    console.log('Generated wallet keys:', JSON.stringify(keypair))
    console.log('Do not forget to save the keys!')

    // To deploy a wallet we need its TVC and ABI files
    const msigTVC: string =
        readFileSync(path.resolve(__dirname, "../contract/SetcodeMultisig.tvc")).toString("base64")
    const msigABI: string =
        readFileSync(path.resolve(__dirname, "../contract/SetcodeMultisig.abi.json")).toString("utf8")

    // We need to know the future address of the wallet account,
    // because its balance must be positive for the contract to be deployed
    // Future address can be calculated by encoding the deploy message.
    // https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_abi#encode_message

    const messageParams: ParamsOfEncodeMessage = {
        abi: { type: 'Json', value: msigABI },
        deploy_set: { tvc: msigTVC, initial_data: {} },
        signer: { type: 'Keys', keys: keypair },
        processing_try_index: 1
    }

    const encoded: ResultOfEncodeMessage = await client.abi.encode_message(messageParams)

    const msigAddress = encoded.address

    console.log(`You can topup your wallet from dashboard at https://dashboard.evercloud.dev`)
    console.log(`Please send >= ${MINIMAL_BALANCE} tokens to ${msigAddress}`)
    console.log(`awaiting...`)

    // Blocking here, waiting for account balance changes.
    // It is assumed that at this time you go to dashboard.evercloud.dev
    // and replenish this account.
    let balance: number
    for (; ;) {
        // The idiomatic way to send a request is to specify 
        // query and variables as separate properties.
        const getBalanceQuery = `
                query getBalance($address: String!) {
                    blockchain {
                    account(address: $address) {
                            info {
                            balance
                        }
                    }
                }
            }
            `
        const resultOfQuery: ResultOfQuery = await client.net.query({
            query: getBalanceQuery,
            variables: { address: msigAddress }
        })

        const nanotokens = parseInt(resultOfQuery.result.data.blockchain.account.info?.balance, 16)
        if (nanotokens > MINIMAL_BALANCE * 1e9) {
            balance = nanotokens / 1e9
            break
        }
        // TODO: rate limiting
        await sleep(1000)
    }
    console.log(`Account balance is: ${balance.toString(10)} tokens`)

    console.log(`Deploying wallet contract to address: ${msigAddress} and waiting for transaction...`)

    // This function returns type `ResultOfProcessMessage`, see: 
    // https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_processing#process_message
    let result: ResultOfProcessMessage = await client.processing.process_message({
        message_encode_params: {
            ...messageParams,  // use the same params as for `encode_message`,
            call_set: {        // plus add `call_set`
                function_name: 'constructor',
                input: {
                    owners: [`0x${keypair.public}`],
                    reqConfirms: 1,
                    lifetime: 3600
                }
            },
        },
        send_events: false,
    })
    console.log('Contract deployed. Transaction hash', result.transaction?.id)
    assert.equal(result.transaction?.status, 3)
    assert.equal(result.transaction?.status_name, "finalized")

    //
```

## Monitoring transactions

Lets assume we need to reliably know when customers receive or transfer funds from their wallets. Samples of transaction [pagination](https://github.com/everx-labs/sdk-samples/tree/master/demo/paginate-transactions) and [subscription](https://github.com/everx-labs/sdk-samples/tree/master/demo/subscribe-transactions) are available in the samples repository. An overview of the relevant parts is given below.

In these samples JS SDK is used. [Bindings](https://docs.everos.dev/ever-sdk/#community-bindings) for a large number of languages have been developed for SDK.

### Pagination

The [pagination](https://github.com/everx-labs/sdk-samples/tree/master/demo/paginate-transactions) sample queries and displays transactions in workchain 0 (workchain where simple transfers happen, -1 workchain is masterchain where you can find service transactions and validator transactions) from the beginning. We can get all the transaction and filter by account addresses on the backend side.

**Note**: By default the Blockchain API queries, such as the one used here provide only data from the past 7 days. To retrieve older data, make sure to use the `archive: true` flag, as shown in the sample:

```typescript
   async function main(client: TonClient) {
    // In this example, we want the query to return 2 items per page.
    const itemsPerPage = 25

    // Pagination connection pattern requires a cursor, which will be set latter
    let cursor: string = undefined

    // The idiomatic way to send a request is to specify 
    // query and variables as separate properties.
    const transactionsQuery = `
        query listTransactions($cursor: String, $count: Int) {
            blockchain {
                transactions(
                    workchain: 0
                    archive: true
                    first: $count
                    after: $cursor
                 ) {
                    edges {
                        node { 
                            id
                            balance_delta
                            account_addr
                            # other transaction fields
                     }
                    }
                    pageInfo { hasNextPage endCursor }
                }
            }
        }`

    for (; ;) {
        const queryResult: ResultOfQuery = await client.net.query({
            query: transactionsQuery,
            variables: {
                count: itemsPerPage,
                cursor
            }
        });
        const transactions = queryResult.result.data.blockchain.transactions;

        for (const edge of transactions.edges) {
            console.log("Transaction id:", edge.node.id);
        }
        if (transactions.pageInfo.hasNextPage === false) {
            break;
        }
        // To read next page we initialize the cursor:
        cursor = transactions.pageInfo.endCursor;
        // TODO: rate limiting
        await sleep(1000);
    }

}
console.log("Getting all transactions in workchain 0 from the beginning/")
console.log("Most likely this process will never end, so press CTRL+C to interrupt it")
main(client)
    .then(() => {
        process.exit(0)
    })
    .catch(error => {
        console.error(error);
        process.exit(1);
    })



// This helper function is used for limiting request rate
function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)) }
```

### Subscription

[Subscription](https://github.com/everx-labs/sdk-samples/tree/master/demo/subscribe-transactions) sample subscribes to new transactions of the listed accounts and lists them as they appear.

```typescript
async function main() {
    try {
        const client = new TonClient({ network: { endpoints: [endpoint] } })

        const queryText = `
            subscription my($list: [String!]!){
                transactions(
                    filter: {account_addr: { in: $list }}
                ) {
                    id
                    account_addr
                    balance_delta
                }
            }`

        // use `client.net.unsubscribe({ handle })` to close subscription
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { handle } = await client.net.subscribe(
            {
                subscription: queryText,
                variables: { list: addressList }
            },
            responseHandler,
        );
        console.log("Subscribed to transactions of accounts:", JSON.stringify(addressList))
        console.log("Press CTRL+C to interrupt it")

    } catch (error) {
        if (error.code === 504) {
            console.error('Network is inaccessible.');
        } else {
            console.error(error);
        }
        process.exit(1);
    }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function responseHandler(params: any, responseType: number) {
    // Tip: Always wrap the logic inside responseHandler in a try-catch block
    // or you will be surprised by non-informative errors due to the context
    // in which the handler is executed
    try {
        if (responseType === 100 /* GraphQL data received */) {
            if (params?.result) {
                console.log(params.result);
            }

        } else {
            // See full list of error codes here:
            // https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_net#neterrorcode
            console.error(params, responseType);
        }
    } catch (err) {
        console.log(err);
    }
}
```

You may test out the demo application running this process on the developer network by cloning the [sdk-samples](https://github.com/everx-labs/sdk-samples) repository, creating a project in <https://dashboard.evercloud.dev>, exporting the API endpoint as an environment variable:

```
export ENDPOINT=https://devnet.evercloud.dev/<your_project_id>/graphql
```

and running the following command in the `/demo/subscribe-transactions` folder:

```shell
npm run subscribe-tr
```

{% hint style="warning" %}
Not all transactions that are successful are valid transfers and not all transactions that are aborted actually failed. Read [here](https://docs.everscale.network/arch/transactions#how-to-determine-a-successful-transaction) how to understand which transfers are successful transfers and which are not.
{% endhint %}

## Withdrawing from wallet accounts

The specific function that is used to withdraw the funds depends on the contract chosen for the wallet account. Examples provided below are applicable for the [SetcodeMultisig](https://github.com/EverSurf/multisig2) contract.

### Using CLI tool

Command line `Everdev` tool may be used to automate withdrawals from wallet account in your scripts.

{% hint style="danger" %}
If the user made a mistake in the destination address, and has no control over it, these funds will be lost forever. If the account does not exist, and the user makes mistakes deploying it after the funds are transferred, they may end up being lost as well.
{% endhint %}

So, to perform a simple transfer from a single-owner user account to any specified account, we should make sure that it is already deployed, by setting `bounce` flag to true. If the account does not exist, funds will return back.

{% code overflow="wrap" %}

```shell
everdev contract run SetcodeMultisig.abi.json sendTransaction --address <wallet_account_address> --signer wallet_signer --input dest:recipient_address,value:50000000000,bounce:true,flags:3,payload:""
```

{% endcode %}

`<wallet_account_address>` - address of the user account. Example: 0:7bf2b2ec80371601f854bff9ed0a1171714d922c8bfc86d39e67a7e3a41b2176

`wallet_signer` - name of the user account owner signer

`recipient_address` - raw address of the recipient smart contract. Example: 255a3ad9dfa8aa4f3481856aafc7d79f47d50205190bd56147138740e9b177f3

`value`: - amount of tokens to transfer in nanotokens (Example: value:10000000000 sets up a transfer of 10 tokens).

`bounce` - use true to transfer funds only to deployed accounts.

`flags` - use 3 for a simple transfer.

`payload` - use "" for simple transfer.

{% hint style="info" %}
**Note**: To transfer all funds from the account use `sendTransaction` method with flag `130` and value `0.`
{% endhint %}

{% code overflow="wrap" %}

```shell
everdev contract run SetcodeMultisig.abi.json --address <wallet_account_address> sendTransaction --signer wallet_signer --input dest:recipient_address,value:0,bounce:true,flags:130,payload:""
```

{% endcode %}

Example of regular withdrawal transaction on a single-owner multisig:

```shell
everdev contract run SetcodeMultisig.abi.json sendTransaction --signer wallet_signer --input dest:665a62042aff317ba3f32e36b712b0f4a9d35277dd76dc38c9762cc6421681cf,value:500000000000,bounce:false,flags:3,payload:""

Configuration

  Network: dev (devnet.evercloud.dev)
  Signer:  wallet_signer (public 3da1909b7a4bd11fd9a1d79ca9713a9a8645880e0a7a12f9691c68e95d56fe75)

Address:   0:95c35b94e98c1b5c7716a9129ed5bb0798c8c336465fd8d1eb0d385e3d969494

Parameters of sendTransaction:

  dest (address): "665a62042aff317ba3f32e36b712b0f4a9d35277dd76dc38c9762cc6421681cf"
  value (uint128): "500000000000"
  bounce (bool): "false"
  flags (uint8): "3"
  payload (cell): ""


Running...

Execution has finished with result:
{
    "transaction": {
        "json_version": 8,
        "id": "cbeb7f8b1aa7ac89439d9c6772b699a7c042215cef090f206ecc8b21bb230fc9",
        "boc": "te6ccgECDwEAArcAA7d5XDW5TpjBtcdxapEp7VuweYyMM2Rl/Y0esNOF49lpSUAAAOakEwMsEkhiumuyPgwNDWXdmNBHsr9g6Y6XgsntCG/AQxbMH/mAAADmo/0T8BZCW1XwAFSAICQ36AUEAQIPDE/GHimDxEADAgBvyY9CQExRYUAAAAAAAAQAAAAAAARz+2ts0g+y9Ais9VbZ65O+4BourUTTYoPq+tvoLxFJpECQJNQAnUZPYxOIAAAAAAAAAABYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAgnI1Aq0GL7DtfZycdkRDzfxJtFk47dtGidJveUmyV1aRWS0JxA5UCIBaO/paLFUAjm0/YFLGbVz5bUyQ5fEsfxqwAgHgCwYCAd0JBwEBIAgAdeAErhrcp0xg2uO4tUiU9q3YPMZGGbIy/saPWGnC8ey0pKAAABzUgmBlhshLar5JjsFmgAAAAAAAAABAAQEgCgCzSAErhrcp0xg2uO4tUiU9q3YPMZGGbIy/saPWGnC8ey0pKQAZlpiBCr/MXuj8y42txKw9KnTUnfddtw4yXYsxkIWgc9XRqUogAAYUWGAAABzUgmBlhMhLar5AAUWIASuGtynTGDa47i1SJT2rdg8xkYZsjL+xo9YacLx7LSkoDAwB4fRRR+puAACR3O0hyRMPrwVnVPX+pw1OSY/hvAY+6jc/0ST0CDjZIS4ccsC4fPFe5CZoyAH4UOealyQ5K/a8zQXPaGQm3pL0R/ZodecqXE6moZFiA4KehL5aRxo6V1W/nUAAAGHM0x8YGQltYcTHYLNgDQFjgAzLTECFX+YvdH5lxtbiVh6VOmpO+67bhxkuxZjIQtA54AAAAAAAAAAAAAAOjUpRAAQOAAA=",
        "status": 3,
        "status_name": "finalized",
        "storage": {
            "storage_fees_collected": "0x3f",
            "status_change": 0,
            "status_change_name": "unchanged"
        },
        "compute": {
            "success": true,
            "msg_state_used": false,
            "account_activated": false,
            "gas_fees": "0xc53078",
            "gas_used": 12923,
            "gas_limit": 0,
            "gas_credit": 10000,
            "mode": 0,
            "exit_code": 0,
            "vm_steps": 352,
            "vm_init_state_hash": "0000000000000000000000000000000000000000000000000000000000000000",
            "vm_final_state_hash": "0000000000000000000000000000000000000000000000000000000000000000",
            "compute_type": 1,
            "compute_type_name": "vm"
        },
        "action": {
            "success": true,
            "valid": true,
            "no_funds": false,
            "status_change": 0,
            "total_fwd_fees": "0x1e8480",
            "total_action_fees": "0x145850",
            "result_code": 0,
            "tot_actions": 2,
            "spec_actions": 0,
            "skipped_actions": 0,
            "msgs_created": 2,
            "action_list_hash": "39fdb5b66907d97a04567aab6cf5c9df700d1756a269b141f57d6df41788a4d2",
            "tot_msg_size_cells": 2,
            "tot_msg_size_bits": 1178
        },
        "credit_first": true,
        "aborted": false,
        "destroyed": false,
        "tr_type": 0,
        "tr_type_name": "ordinary",
        "lt": "0xe6a413032c1",
        "prev_trans_hash": "24862ba6bb23e0c0d0d65dd98d047b2bf60e98e9782c9ed086fc04316cc1ff98",
        "prev_trans_lt": "0xe6a3fd13f01",
        "now": 1680192863,
        "outmsg_cnt": 2,
        "orig_status": 1,
        "orig_status_name": "Active",
        "end_status": 1,
        "end_status_name": "Active",
        "in_msg": "b10b0866cb7320f9abac1ba6c5a09f7a60bb87b399142aa0a7dda28b086d9a40",
        "ext_in_msg_fee": "0x2798b8",
        "out_msgs": [
            "ff491002eaeaf22e85055d5b055383d8aaaa030bcb5ae34a65b27f15de8e2e34",
            "8f2f48998b041adbae47a3e8ee7541ee918299d316e07c7dbd221501a31b15d8"
        ],
        "account_addr": "0:95c35b94e98c1b5c7716a9129ed5bb0798c8c336465fd8d1eb0d385e3d969494",
        "workchain_id": 0,
        "total_fees": "0x10121bf",
        "balance_delta": "-0x746b5dd5ef",
        "old_hash": "3502ad062fb0ed7d9c9c764443cdfc49b45938eddb4689d26f7949b257569159",
        "new_hash": "2d09c40e5408805a3bfa5a2c55008e6d3f6052c66d5cf96d4c90e5f12c7f1ab0"
    },
    "output": {
        "transId": "0"
    },
    "out_messages": [
        null
    ]
}

```

Basic checks of the address format will be performed by the Everdev utility automatically, only addresses of a valid Everscale format will be accepted.

#### (Optional) Multi-owner accounts and Confirm transaction

Note, that if your user account has multiple custodians, the transaction has to be confirmed by the required number of signatures to be executed. This transaction ID should be communicated to other custodians, who should use it to confirm the transaction.

To withdraw tokens from a multi-owner account use the following command:

{% code overflow="wrap" %}

```bash
everdev contract run SetcodeMultisig.abi.json submitTransaction --address <wallet_account_address> --signer wallet_signer --input '{ "dest": "recipient_address", "value":10000000000, "bounce": false, "allBalance": false, "payload": "", "stateInit": null }'
```

{% endcode %}

`<wallet_account_address>` - address of the user account. Example: 0:7bf2b2ec80371601f854bff9ed0a1171714d922c8bfc86d39e67a7e3a41b2176

`wallet_signer` - name of the user account owner signer

`value`: - amount of tokens to transfer in nanotokens (Example: value:10000000000 sets up a transfer of 10 tokens).

`bounce` - use false to transfer funds to an already deployed account

`allBalance` - used to transfer all funds in the wallet. Use false for a simple transfer.

`payload` - use "" for simple transfer.

`stateInit` - use `null` for a simple transfer.

This will generate a transaction and display its `transId` that will have to be confirmed by other custodians.

To confirm a transaction, use the following command:

{% code overflow="wrap" %}

```shell
everdev contract run SetcodeMultisig.abi.json confirmTransaction --address <wallet_account_address> --signer wallet_signer2 --input transactionId:6954030467099431873
```

{% endcode %}

`<wallet_account_address>` - address of the user account. Example: 0:7bf2b2ec80371601f854bff9ed0a1171714d922c8bfc86d39e67a7e3a41b2176

`wallet_signer2` - signer of another multisig custodian (not the one who initiated the transaction).

`transactionId` – the ID of the transaction can be acquired from the custodian who created it.

#### Mitigating risks of token loss due to user error

The are two main cases regarding transfers to user accounts: a user may already have an active account to which they want to withdraw funds (set bounce to true), or they may want to withdraw funds to a completely new account, that doesn't exist at the time withdraw is requested (set bounce to false).

The status of the account provided by the user may be checked with the following Everdev command:

```shell
everdev contract info --address external_address
```

Example of existing account:

```shell
everdev contract info --address 0:665a62042aff317ba3f32e36b712b0f4a9d35277dd76dc38c9762cc6421681cf

Configuration

  Network: dev (devnet.evercloud.dev)
  Signer:  owner_keys (public 5ff6b5ba62b52b25ef347984912937bffaf2df88605e4e56cb64b9b617a28fea)

Address:   0:665a62042aff317ba3f32e36b712b0f4a9d35277dd76dc38c9762cc6421681cf
Account:   Active
Balance:   ≈ 51655 tokens (51655086754193 nano)
```

Example of account that doesn't exist yet:

```shell
everdev contract info --address 0:6238e23f6987883b3d1a86e1c39c63ae2baf7f93603d0ea5dc9b6e91ef54a1ab

Configuration

  Network: dev (devnet.evercloud.dev)
  Signer:  owner_keys (public 5ff6b5ba62b52b25ef347984912937bffaf2df88605e4e56cb64b9b617a28fea)

Address:   0:6238e23f6987883b3d1a86e1c39c63ae2baf7f93603d0ea5dc9b6e91ef54a1ab (calculated from TVC and signer public)
Code Hash: 80d6c47c4a25543c9b397b71716f3fae1e2c5d247174c52e2c19bd896442b105 (from TVC file)
Account:   Doesn't exist

```

The possible results of this command are the following:

`Doesn't exist` - account does not exist. It needs to be sponsored, then deployed, and only then will it be active.

`Uninit` - account already has some funds on it but contract code has not been deployed yet. User needs to deploy it.

`Active` - account already exists, and its code is deployed.

In the first to cases, the service might first transfer a small portion of the requested amount (\~1 EVER) and request that the user deploys their contract. Upon the user's confirmation that the account is deployed, its status may be rechecked, and if it became active, the remaining amount of requested funds may be safely transferred.

If the account is already active, a small portion of the requested amount may be transferred to the user, and the user may be asked what amount they received (note: a small amount of the transfer, usually less than 0.05 EVER, will be spent on fees, so it's best to ask for the whole number of tokens transferred). If the amounts match, the rest of the requested funds may be transferred as well.

### Using SDK

You may integrate withdrawals from wallet account into your backend using SDK as well. A sample is available in [this repository](https://github.com/everx-labs/sdk-samples/tree/master/demo/msig-wallet) and an overview of the relevant part is given below.

In this sample JS SDK is used. [Bindings](https://docs.everos.dev/ever-sdk/#community-bindings) for a large number of languages have been developed for SDK.

This example shows how to generate a withdrawal transaction from a Multisig wallet, using its `sendTransaction` method. Note, that if Multisig has multiple custodians, the transaction will have to be confirmed with the `confirmTransaction` method.

In this example tokens are withdrawn from the user account to the account specified in `dest`. In a proper implementation, the account given by user should be used instead.

```javascript
    // We send 0.5 tokens. Value is written in nanotokens
    const amount = 0.5e9
    const dest = "-1:7777777777777777777777777777777777777777777777777777777777777777"

    console.log('Sending 0.5 token to', dest)

    result = await client.processing.process_message({
        message_encode_params: {
            address: msigAddress,
            ...messageParams, // use the same params as for `encode_message`,
            call_set: {       // plus add `call_set`
                function_name: 'sendTransaction',
                input: {
                    dest: dest,
                    value: amount,
                    bounce: true,
                    flags: 64,
                    payload: ''
                }
            },
        },
        send_events: false, // do not send intermidate events
    })
    console.log('Transfer completed. Transaction hash', result.transaction?.id)
    assert.equal(result.transaction?.status, 3)
    assert.equal(result.transaction?.status_name, "finalized")

```

#### Mitigating risks of token loss due to user error

Similarly to the everdev approach, you can add the account status check prior to sending tokens.

The are two main cases regarding transfers to user accounts: a user may already have an active account to which they want to withdraw funds, or they may want to withdraw funds to a completely new account, that doesn't exist at the time withdraw is requested.

Here is an example of checking account status in SDK:

```typescript
    let balance: number
    let accType: number
    for (; ;) {
        // The idiomatic way to send a request is to specify 
        // query and variables as separate properties.
        const getInfoQuery = `
                query getBalance($address: String!) {
                    blockchain {
                    account(address: $address) {
                            info {
                            balance
                            acc_type
                        }
                    }
                }
            }
            `
        const resultOfQuery: ResultOfQuery = await client.net.query({
            query: getInfoQuery,
            variables: { address: msigAddress }
        })
        

        const nanotokens = parseInt(resultOfQuery.result.data.blockchain.account.info?.balance, 16)
        accType = resultOfQuery.result.data.blockchain.account.info?.acc_type;
        if (nanotokens > MINIMAL_BALANCE * 1e9) {
            balance = nanotokens / 1e9
            break
        }
        // TODO: rate limiting
        await sleep(1000)
    }
    console.log(`Account balance is: ${balance.toString(10)} tokens. Account type is ${accType}`)
```


# Types and Methods

This section contains documents describing TON SDK Types and Methods supported by various [modules](/ever-sdk/reference/types-and-methods/modules).

* [Module abi](/ever-sdk/reference/types-and-methods/mod_abi)
* [Module boc](/ever-sdk/reference/types-and-methods/mod_boc)
* [Module client](/ever-sdk/reference/types-and-methods/mod_client)
* [Module crypto](/ever-sdk/reference/types-and-methods/mod_crypto)
* [Module debot](/ever-sdk/reference/types-and-methods/mod_debot)
* [Module net](/ever-sdk/reference/types-and-methods/mod_net)
* [Module processing](/ever-sdk/reference/types-and-methods/mod_processing)
* [Module proofs](/ever-sdk/reference/types-and-methods/mod_proofs)
* [Module tvm](/ever-sdk/reference/types-and-methods/mod_tvm)
* [Module utils](/ever-sdk/reference/types-and-methods/mod_utils)


# Modules

## Common Types

### ResponseHandler

```ts
type ResponseHandler = (params: any, responseType: number) => void;
```

Handles additional function responses.

Where:

* `params`: *any* – Response parameters. Actual type depends on API function.
* `responseType`: *number* – Function specific response type.

## Modules

### [client](/ever-sdk/reference/types-and-methods/mod_client) – Provides information about library.

[get\_api\_reference](/ever-sdk/reference/types-and-methods/mod_client#get_api_reference) – Returns Core Library API reference

[version](/ever-sdk/reference/types-and-methods/mod_client#version) – Returns Core Library version

[config](/ever-sdk/reference/types-and-methods/mod_client#config) – Returns Core Library API reference

[build\_info](/ever-sdk/reference/types-and-methods/mod_client#build_info) – Returns detailed information about this build.

[resolve\_app\_request](/ever-sdk/reference/types-and-methods/mod_client#resolve_app_request) – Resolves application request processing result

### [crypto](/ever-sdk/reference/types-and-methods/mod_crypto) – Crypto functions.

[factorize](/ever-sdk/reference/types-and-methods/mod_crypto#factorize) – Integer factorization

[modular\_power](/ever-sdk/reference/types-and-methods/mod_crypto#modular_power) – Modular exponentiation

[ton\_crc16](/ever-sdk/reference/types-and-methods/mod_crypto#ton_crc16) – Calculates CRC16 using TON algorithm.

[generate\_random\_bytes](/ever-sdk/reference/types-and-methods/mod_crypto#generate_random_bytes) – Generates random byte array of the specified length and returns it in `base64` format

[convert\_public\_key\_to\_ton\_safe\_format](/ever-sdk/reference/types-and-methods/mod_crypto#convert_public_key_to_ton_safe_format) – Converts public key to ton safe\_format

[generate\_random\_sign\_keys](/ever-sdk/reference/types-and-methods/mod_crypto#generate_random_sign_keys) – Generates random ed25519 key pair.

[sign](/ever-sdk/reference/types-and-methods/mod_crypto#sign) – Signs a data using the provided keys.

[verify\_signature](/ever-sdk/reference/types-and-methods/mod_crypto#verify_signature) – Verifies signed data using the provided public key. Raises error if verification is failed.

[sha256](/ever-sdk/reference/types-and-methods/mod_crypto#sha256) – Calculates SHA256 hash of the specified data.

[sha512](/ever-sdk/reference/types-and-methods/mod_crypto#sha512) – Calculates SHA512 hash of the specified data.

[scrypt](/ever-sdk/reference/types-and-methods/mod_crypto#scrypt) – Perform `scrypt` encryption

[nacl\_sign\_keypair\_from\_secret\_key](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_sign_keypair_from_secret_key) – Generates a key pair for signing from the secret key

[nacl\_sign](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_sign) – Signs data using the signer's secret key.

[nacl\_sign\_open](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_sign_open) – Verifies the signature and returns the unsigned message

[nacl\_sign\_detached](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_sign_detached) – Signs the message using the secret key and returns a signature.

[nacl\_sign\_detached\_verify](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_sign_detached_verify) – Verifies the signature with public key and `unsigned` data.

[nacl\_box\_keypair](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_box_keypair) – Generates a random NaCl key pair

[nacl\_box\_keypair\_from\_secret\_key](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_box_keypair_from_secret_key) – Generates key pair from a secret key

[nacl\_box](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_box) – Public key authenticated encryption

[nacl\_box\_open](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_box_open) – Decrypt and verify the cipher text using the receivers secret key, the senders public key, and the nonce.

[nacl\_secret\_box](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_secret_box) – Encrypt and authenticate message using nonce and secret key.

[nacl\_secret\_box\_open](/ever-sdk/reference/types-and-methods/mod_crypto#nacl_secret_box_open) – Decrypts and verifies cipher text using `nonce` and secret `key`.

[mnemonic\_words](/ever-sdk/reference/types-and-methods/mod_crypto#mnemonic_words) – Prints the list of words from the specified dictionary

[mnemonic\_from\_random](/ever-sdk/reference/types-and-methods/mod_crypto#mnemonic_from_random) – Generates a random mnemonic

[mnemonic\_from\_entropy](/ever-sdk/reference/types-and-methods/mod_crypto#mnemonic_from_entropy) – Generates mnemonic from pre-generated entropy

[mnemonic\_verify](/ever-sdk/reference/types-and-methods/mod_crypto#mnemonic_verify) – Validates a mnemonic phrase

[mnemonic\_derive\_sign\_keys](/ever-sdk/reference/types-and-methods/mod_crypto#mnemonic_derive_sign_keys) – Derives a key pair for signing from the seed phrase

[hdkey\_xprv\_from\_mnemonic](/ever-sdk/reference/types-and-methods/mod_crypto#hdkey_xprv_from_mnemonic) – Generates an extended master private key that will be the root for all the derived keys

[hdkey\_derive\_from\_xprv](/ever-sdk/reference/types-and-methods/mod_crypto#hdkey_derive_from_xprv) – Returns extended private key derived from the specified extended private key and child index

[hdkey\_derive\_from\_xprv\_path](/ever-sdk/reference/types-and-methods/mod_crypto#hdkey_derive_from_xprv_path) – Derives the extended private key from the specified key and path

[hdkey\_secret\_from\_xprv](/ever-sdk/reference/types-and-methods/mod_crypto#hdkey_secret_from_xprv) – Extracts the private key from the serialized extended private key

[hdkey\_public\_from\_xprv](/ever-sdk/reference/types-and-methods/mod_crypto#hdkey_public_from_xprv) – Extracts the public key from the serialized extended private key

[chacha20](/ever-sdk/reference/types-and-methods/mod_crypto#chacha20) – Performs symmetric `chacha20` encryption.

[create\_crypto\_box](/ever-sdk/reference/types-and-methods/mod_crypto#create_crypto_box) – Creates a Crypto Box instance.

[remove\_crypto\_box](/ever-sdk/reference/types-and-methods/mod_crypto#remove_crypto_box) – Removes Crypto Box. Clears all secret data.

[get\_crypto\_box\_info](/ever-sdk/reference/types-and-methods/mod_crypto#get_crypto_box_info) – Get Crypto Box Info. Used to get `encrypted_secret` that should be used for all the cryptobox initializations except the first one.

[get\_crypto\_box\_seed\_phrase](/ever-sdk/reference/types-and-methods/mod_crypto#get_crypto_box_seed_phrase) – Get Crypto Box Seed Phrase.

[get\_signing\_box\_from\_crypto\_box](/ever-sdk/reference/types-and-methods/mod_crypto#get_signing_box_from_crypto_box) – Get handle of Signing Box derived from Crypto Box.

[get\_encryption\_box\_from\_crypto\_box](/ever-sdk/reference/types-and-methods/mod_crypto#get_encryption_box_from_crypto_box) – Gets Encryption Box from Crypto Box.

[clear\_crypto\_box\_secret\_cache](/ever-sdk/reference/types-and-methods/mod_crypto#clear_crypto_box_secret_cache) – Removes cached secrets (overwrites with zeroes) from all signing and encryption boxes, derived from crypto box.

[register\_signing\_box](/ever-sdk/reference/types-and-methods/mod_crypto#register_signing_box) – Register an application implemented signing box.

[get\_signing\_box](/ever-sdk/reference/types-and-methods/mod_crypto#get_signing_box) – Creates a default signing box implementation.

[signing\_box\_get\_public\_key](/ever-sdk/reference/types-and-methods/mod_crypto#signing_box_get_public_key) – Returns public key of signing key pair.

[signing\_box\_sign](/ever-sdk/reference/types-and-methods/mod_crypto#signing_box_sign) – Returns signed user data.

[remove\_signing\_box](/ever-sdk/reference/types-and-methods/mod_crypto#remove_signing_box) – Removes signing box from SDK.

[register\_encryption\_box](/ever-sdk/reference/types-and-methods/mod_crypto#register_encryption_box) – Register an application implemented encryption box.

[remove\_encryption\_box](/ever-sdk/reference/types-and-methods/mod_crypto#remove_encryption_box) – Removes encryption box from SDK

[encryption\_box\_get\_info](/ever-sdk/reference/types-and-methods/mod_crypto#encryption_box_get_info) – Queries info from the given encryption box

[encryption\_box\_encrypt](/ever-sdk/reference/types-and-methods/mod_crypto#encryption_box_encrypt) – Encrypts data using given encryption box Note.

[encryption\_box\_decrypt](/ever-sdk/reference/types-and-methods/mod_crypto#encryption_box_decrypt) – Decrypts data using given encryption box Note.

[create\_encryption\_box](/ever-sdk/reference/types-and-methods/mod_crypto#create_encryption_box) – Creates encryption box with specified algorithm

### [abi](/ever-sdk/reference/types-and-methods/mod_abi) – Provides message encoding and decoding according to the ABI specification.

[encode\_message\_body](/ever-sdk/reference/types-and-methods/mod_abi#encode_message_body) – Encodes message body according to ABI function call.

[attach\_signature\_to\_message\_body](/ever-sdk/reference/types-and-methods/mod_abi#attach_signature_to_message_body)

[encode\_message](/ever-sdk/reference/types-and-methods/mod_abi#encode_message) – Encodes an ABI-compatible message

[encode\_internal\_message](/ever-sdk/reference/types-and-methods/mod_abi#encode_internal_message) – Encodes an internal ABI-compatible message

[attach\_signature](/ever-sdk/reference/types-and-methods/mod_abi#attach_signature) – Combines `hex`-encoded `signature` with `base64`-encoded `unsigned_message`. Returns signed message encoded in `base64`.

[decode\_message](/ever-sdk/reference/types-and-methods/mod_abi#decode_message) – Decodes message body using provided message BOC and ABI.

[decode\_message\_body](/ever-sdk/reference/types-and-methods/mod_abi#decode_message_body) – Decodes message body using provided body BOC and ABI.

[encode\_account](/ever-sdk/reference/types-and-methods/mod_abi#encode_account) – Creates account state BOC

[decode\_account\_data](/ever-sdk/reference/types-and-methods/mod_abi#decode_account_data) – Decodes account data using provided data BOC and ABI.

[update\_initial\_data](/ever-sdk/reference/types-and-methods/mod_abi#update_initial_data) – Updates initial account data with initial values for the contract's static variables and owner's public key. This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.

[encode\_initial\_data](/ever-sdk/reference/types-and-methods/mod_abi#encode_initial_data) – Encodes initial account data with initial values for the contract's static variables and owner's public key into a data BOC that can be passed to `encode_tvc` function afterwards.

[decode\_initial\_data](/ever-sdk/reference/types-and-methods/mod_abi#decode_initial_data) – Decodes initial values of a contract's static variables and owner's public key from account initial data This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.

[decode\_boc](/ever-sdk/reference/types-and-methods/mod_abi#decode_boc) – Decodes BOC into JSON as a set of provided parameters.

[encode\_boc](/ever-sdk/reference/types-and-methods/mod_abi#encode_boc) – Encodes given parameters in JSON into a BOC using param types from ABI.

[calc\_function\_id](/ever-sdk/reference/types-and-methods/mod_abi#calc_function_id) – Calculates contract function ID by contract ABI

[get\_signature\_data](/ever-sdk/reference/types-and-methods/mod_abi#get_signature_data) – Extracts signature from message body and calculates hash to verify the signature

### [boc](/ever-sdk/reference/types-and-methods/mod_boc) – BOC manipulation module.

[decode\_tvc](/ever-sdk/reference/types-and-methods/mod_boc#decode_tvc) – Decodes tvc according to the tvc spec. Read more about tvc structure here <https://github.com/everx-labs/ever-struct/blob/main/src/scheme/mod.rs#L30>

[parse\_message](/ever-sdk/reference/types-and-methods/mod_boc#parse_message) – Parses message boc into a JSON

[parse\_transaction](/ever-sdk/reference/types-and-methods/mod_boc#parse_transaction) – Parses transaction boc into a JSON

[parse\_account](/ever-sdk/reference/types-and-methods/mod_boc#parse_account) – Parses account boc into a JSON

[parse\_block](/ever-sdk/reference/types-and-methods/mod_boc#parse_block) – Parses block boc into a JSON

[parse\_shardstate](/ever-sdk/reference/types-and-methods/mod_boc#parse_shardstate) – Parses shardstate boc into a JSON

[get\_blockchain\_config](/ever-sdk/reference/types-and-methods/mod_boc#get_blockchain_config) – Extract blockchain configuration from key block and also from zerostate.

[get\_boc\_hash](/ever-sdk/reference/types-and-methods/mod_boc#get_boc_hash) – Calculates BOC root hash

[get\_boc\_depth](/ever-sdk/reference/types-and-methods/mod_boc#get_boc_depth) – Calculates BOC depth

[get\_code\_from\_tvc](/ever-sdk/reference/types-and-methods/mod_boc#get_code_from_tvc) – Extracts code from TVC contract image

[cache\_get](/ever-sdk/reference/types-and-methods/mod_boc#cache_get) – Get BOC from cache

[cache\_set](/ever-sdk/reference/types-and-methods/mod_boc#cache_set) – Save BOC into cache or increase pin counter for existing pinned BOC

[cache\_unpin](/ever-sdk/reference/types-and-methods/mod_boc#cache_unpin) – Unpin BOCs with specified pin defined in the `cache_set`. Decrease pin reference counter for BOCs with specified pin defined in the `cache_set`. BOCs which have only 1 pin and its reference counter become 0 will be removed from cache

[encode\_boc](/ever-sdk/reference/types-and-methods/mod_boc#encode_boc) – Encodes bag of cells (BOC) with builder operations. This method provides the same functionality as Solidity TvmBuilder. Resulting BOC of this method can be passed into Solidity and C++ contracts as TvmCell type.

[get\_code\_salt](/ever-sdk/reference/types-and-methods/mod_boc#get_code_salt) – Returns the contract code's salt if it is present.

[set\_code\_salt](/ever-sdk/reference/types-and-methods/mod_boc#set_code_salt) – Sets new salt to contract code.

[decode\_state\_init](/ever-sdk/reference/types-and-methods/mod_boc#decode_state_init) – Decodes contract's initial state into code, data, libraries and special options.

[encode\_state\_init](/ever-sdk/reference/types-and-methods/mod_boc#encode_state_init) – Encodes initial contract state from code, data, libraries ans special options (see input params)

[encode\_external\_in\_message](/ever-sdk/reference/types-and-methods/mod_boc#encode_external_in_message) – Encodes a message

[get\_compiler\_version](/ever-sdk/reference/types-and-methods/mod_boc#get_compiler_version) – Returns the compiler version used to compile the code.

### [processing](/ever-sdk/reference/types-and-methods/mod_processing) – Message processing module.

[monitor\_messages](/ever-sdk/reference/types-and-methods/mod_processing#monitor_messages) – Starts monitoring for the processing results of the specified messages.

[get\_monitor\_info](/ever-sdk/reference/types-and-methods/mod_processing#get_monitor_info) – Returns summary information about current state of the specified monitoring queue.

[fetch\_next\_monitor\_results](/ever-sdk/reference/types-and-methods/mod_processing#fetch_next_monitor_results) – Fetches next resolved results from the specified monitoring queue.

[cancel\_monitor](/ever-sdk/reference/types-and-methods/mod_processing#cancel_monitor) – Cancels all background activity and releases all allocated system resources for the specified monitoring queue.

[send\_messages](/ever-sdk/reference/types-and-methods/mod_processing#send_messages) – Sends specified messages to the blockchain.

[send\_message](/ever-sdk/reference/types-and-methods/mod_processing#send_message) – Sends message to the network

[wait\_for\_transaction](/ever-sdk/reference/types-and-methods/mod_processing#wait_for_transaction) – Performs monitoring of the network for the result transaction of the external inbound message processing.

[process\_message](/ever-sdk/reference/types-and-methods/mod_processing#process_message) – Creates message, sends it to the network and monitors its processing.

### [utils](/ever-sdk/reference/types-and-methods/mod_utils) – Misc utility Functions.

[convert\_address](/ever-sdk/reference/types-and-methods/mod_utils#convert_address) – Converts address from any TON format to any TON format

[get\_address\_type](/ever-sdk/reference/types-and-methods/mod_utils#get_address_type) – Validates and returns the type of any TON address.

[calc\_storage\_fee](/ever-sdk/reference/types-and-methods/mod_utils#calc_storage_fee) – Calculates storage fee for an account over a specified time period

[compress\_zstd](/ever-sdk/reference/types-and-methods/mod_utils#compress_zstd) – Compresses data using Zstandard algorithm

[decompress\_zstd](/ever-sdk/reference/types-and-methods/mod_utils#decompress_zstd) – Decompresses data using Zstandard algorithm

### [tvm](/ever-sdk/reference/types-and-methods/mod_tvm)

[run\_executor](/ever-sdk/reference/types-and-methods/mod_tvm#run_executor) – Emulates all the phases of contract execution locally

[run\_tvm](/ever-sdk/reference/types-and-methods/mod_tvm#run_tvm) – Executes get-methods of ABI-compatible contracts

[run\_get](/ever-sdk/reference/types-and-methods/mod_tvm#run_get) – Executes a get-method of FIFT contract

### [net](/ever-sdk/reference/types-and-methods/mod_net) – Network access.

[query](/ever-sdk/reference/types-and-methods/mod_net#query) – Performs DAppServer GraphQL query.

[batch\_query](/ever-sdk/reference/types-and-methods/mod_net#batch_query) – Performs multiple queries per single fetch.

[query\_collection](/ever-sdk/reference/types-and-methods/mod_net#query_collection) – Queries collection data

[aggregate\_collection](/ever-sdk/reference/types-and-methods/mod_net#aggregate_collection) – Aggregates collection data.

[wait\_for\_collection](/ever-sdk/reference/types-and-methods/mod_net#wait_for_collection) – Returns an object that fulfills the conditions or waits for its appearance

[unsubscribe](/ever-sdk/reference/types-and-methods/mod_net#unsubscribe) – Cancels a subscription

[subscribe\_collection](/ever-sdk/reference/types-and-methods/mod_net#subscribe_collection) – Creates a collection subscription

[subscribe](/ever-sdk/reference/types-and-methods/mod_net#subscribe) – Creates a subscription

[suspend](/ever-sdk/reference/types-and-methods/mod_net#suspend) – Suspends network module to stop any network activity

[resume](/ever-sdk/reference/types-and-methods/mod_net#resume) – Resumes network module to enable network activity

[find\_last\_shard\_block](/ever-sdk/reference/types-and-methods/mod_net#find_last_shard_block) – Returns ID of the last block in a specified account shard

[fetch\_endpoints](/ever-sdk/reference/types-and-methods/mod_net#fetch_endpoints) – Requests the list of alternative endpoints from server

[set\_endpoints](/ever-sdk/reference/types-and-methods/mod_net#set_endpoints) – Sets the list of endpoints to use on reinit

[get\_endpoints](/ever-sdk/reference/types-and-methods/mod_net#get_endpoints) – Requests the list of alternative endpoints from server

[query\_counterparties](/ever-sdk/reference/types-and-methods/mod_net#query_counterparties) – Allows to query and paginate through the list of accounts that the specified account has interacted with, sorted by the time of the last internal message between accounts

[query\_transaction\_tree](/ever-sdk/reference/types-and-methods/mod_net#query_transaction_tree) – Returns a tree of transactions triggered by a specific message.

[create\_block\_iterator](/ever-sdk/reference/types-and-methods/mod_net#create_block_iterator) – Creates block iterator.

[resume\_block\_iterator](/ever-sdk/reference/types-and-methods/mod_net#resume_block_iterator) – Resumes block iterator.

[create\_transaction\_iterator](/ever-sdk/reference/types-and-methods/mod_net#create_transaction_iterator) – Creates transaction iterator.

[resume\_transaction\_iterator](/ever-sdk/reference/types-and-methods/mod_net#resume_transaction_iterator) – Resumes transaction iterator.

[iterator\_next](/ever-sdk/reference/types-and-methods/mod_net#iterator_next) – Returns next available items.

[remove\_iterator](/ever-sdk/reference/types-and-methods/mod_net#remove_iterator) – Removes an iterator

[get\_signature\_id](/ever-sdk/reference/types-and-methods/mod_net#get_signature_id) – Returns signature ID for configured network if it should be used in messages signature

### [debot](/ever-sdk/reference/types-and-methods/mod_debot) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Module for working with debot.

[init](/ever-sdk/reference/types-and-methods/mod_debot#init) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Creates and instance of DeBot.

[start](/ever-sdk/reference/types-and-methods/mod_debot#start) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Starts the DeBot.

[fetch](/ever-sdk/reference/types-and-methods/mod_debot#fetch) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Fetches DeBot metadata from blockchain.

[execute](/ever-sdk/reference/types-and-methods/mod_debot#execute) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Executes debot action.

[send](/ever-sdk/reference/types-and-methods/mod_debot#send) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Sends message to Debot.

[remove](/ever-sdk/reference/types-and-methods/mod_debot#remove) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Destroys debot handle.

### [proofs](/ever-sdk/reference/types-and-methods/mod_proofs) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Module for proving data, retrieved from TONOS API.

[proof\_block\_data](/ever-sdk/reference/types-and-methods/mod_proofs#proof_block_data) – Proves that a given block's data, which is queried from TONOS API, can be trusted.

[proof\_transaction\_data](/ever-sdk/reference/types-and-methods/mod_proofs#proof_transaction_data) – Proves that a given transaction's data, which is queried from TONOS API, can be trusted.

[proof\_message\_data](/ever-sdk/reference/types-and-methods/mod_proofs#proof_message_data) – Proves that a given message's data, which is queried from TONOS API, can be trusted.


# Module abi

## Module abi

Provides message encoding and decoding according to the ABI specification.

### Functions

[encode\_message\_body](#encode_message_body) – Encodes message body according to ABI function call.

[attach\_signature\_to\_message\_body](#attach_signature_to_message_body)

[encode\_message](#encode_message) – Encodes an ABI-compatible message

[encode\_internal\_message](#encode_internal_message) – Encodes an internal ABI-compatible message

[attach\_signature](#attach_signature) – Combines `hex`-encoded `signature` with `base64`-encoded `unsigned_message`. Returns signed message encoded in `base64`.

[decode\_message](#decode_message) – Decodes message body using provided message BOC and ABI.

[decode\_message\_body](#decode_message_body) – Decodes message body using provided body BOC and ABI.

[encode\_account](#encode_account) – Creates account state BOC

[decode\_account\_data](#decode_account_data) – Decodes account data using provided data BOC and ABI.

[update\_initial\_data](#update_initial_data) – Updates initial account data with initial values for the contract's static variables and owner's public key. This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.

[encode\_initial\_data](#encode_initial_data) – Encodes initial account data with initial values for the contract's static variables and owner's public key into a data BOC that can be passed to `encode_tvc` function afterwards.

[decode\_initial\_data](#decode_initial_data) – Decodes initial values of a contract's static variables and owner's public key from account initial data This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.

[decode\_boc](#decode_boc) – Decodes BOC into JSON as a set of provided parameters.

[encode\_boc](#encode_boc) – Encodes given parameters in JSON into a BOC using param types from ABI.

[calc\_function\_id](#calc_function_id) – Calculates contract function ID by contract ABI

[get\_signature\_data](#get_signature_data) – Extracts signature from message body and calculates hash to verify the signature

### Types

[AbiErrorCode](#abierrorcode)

[AbiContractVariant](#abicontractvariant)

[AbiJsonVariant](#abijsonvariant)

[AbiHandleVariant](#abihandlevariant)

[AbiSerializedVariant](#abiserializedvariant)

[Abi](#abi)

[AbiHandle](#abihandle)

[FunctionHeader](#functionheader) – The ABI function header.

[CallSet](#callset)

[DeploySet](#deployset)

[SignerNoneVariant](#signernonevariant) – No keys are provided.

[SignerExternalVariant](#signerexternalvariant) – Only public key is provided in unprefixed hex string format to generate unsigned message and `data_to_sign` which can be signed later.

[SignerKeysVariant](#signerkeysvariant) – Key pair is provided for signing

[SignerSigningBoxVariant](#signersigningboxvariant) – Signing Box interface is provided for signing, allows Dapps to sign messages using external APIs, such as HSM, cold wallet, etc.

[Signer](#signer)

[MessageBodyType](#messagebodytype)

[AbiParam](#abiparam)

[AbiEvent](#abievent)

[AbiData](#abidata)

[AbiFunction](#abifunction)

[AbiContract](#abicontract)

[DataLayout](#datalayout)

[ParamsOfEncodeMessageBody](#paramsofencodemessagebody)

[ResultOfEncodeMessageBody](#resultofencodemessagebody)

[ParamsOfAttachSignatureToMessageBody](#paramsofattachsignaturetomessagebody)

[ResultOfAttachSignatureToMessageBody](#resultofattachsignaturetomessagebody)

[ParamsOfEncodeMessage](#paramsofencodemessage)

[ResultOfEncodeMessage](#resultofencodemessage)

[ParamsOfEncodeInternalMessage](#paramsofencodeinternalmessage)

[ResultOfEncodeInternalMessage](#resultofencodeinternalmessage)

[ParamsOfAttachSignature](#paramsofattachsignature)

[ResultOfAttachSignature](#resultofattachsignature)

[ParamsOfDecodeMessage](#paramsofdecodemessage)

[DecodedMessageBody](#decodedmessagebody)

[ParamsOfDecodeMessageBody](#paramsofdecodemessagebody)

[ParamsOfEncodeAccount](#paramsofencodeaccount)

[ResultOfEncodeAccount](#resultofencodeaccount)

[ParamsOfDecodeAccountData](#paramsofdecodeaccountdata)

[ResultOfDecodeAccountData](#resultofdecodeaccountdata)

[ParamsOfUpdateInitialData](#paramsofupdateinitialdata)

[ResultOfUpdateInitialData](#resultofupdateinitialdata)

[ParamsOfEncodeInitialData](#paramsofencodeinitialdata)

[ResultOfEncodeInitialData](#resultofencodeinitialdata)

[ParamsOfDecodeInitialData](#paramsofdecodeinitialdata)

[ResultOfDecodeInitialData](#resultofdecodeinitialdata)

[ParamsOfDecodeBoc](#paramsofdecodeboc)

[ResultOfDecodeBoc](#resultofdecodeboc)

[ParamsOfAbiEncodeBoc](#paramsofabiencodeboc)

[ResultOfAbiEncodeBoc](#resultofabiencodeboc)

[ParamsOfCalcFunctionId](#paramsofcalcfunctionid)

[ResultOfCalcFunctionId](#resultofcalcfunctionid)

[ParamsOfGetSignatureData](#paramsofgetsignaturedata)

[ResultOfGetSignatureData](#resultofgetsignaturedata)

## Functions

### encode\_message\_body

Encodes message body according to ABI function call.

```ts
type ParamsOfEncodeMessageBody = {
    abi: Abi,
    call_set: CallSet,
    is_internal: boolean,
    signer: Signer,
    processing_try_index?: number,
    address?: string,
    signature_id?: number
}

type ResultOfEncodeMessageBody = {
    body: string,
    data_to_sign?: string
}

function encode_message_body(
    params: ParamsOfEncodeMessageBody,
): Promise<ResultOfEncodeMessageBody>;

function encode_message_body_sync(
    params: ParamsOfEncodeMessageBody,
): ResultOfEncodeMessageBody;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI.
* `call_set`: [*CallSet*](#callset) – Function call parameters.\
  Must be specified in non deploy message.\
  \
  In case of deploy message contains parameters of constructor.
* `is_internal`: *boolean* – True if internal message body must be encoded.
* `signer`: [*Signer*](#signer) – Signing parameters.
* `processing_try_index`?: *number* – Processing try index.\
  Used in message processing with retries.\
  \
  Encoder uses the provided try index to calculate message\
  expiration time.\
  \
  Expiration timeouts will grow with every retry.\
  \
  Default value is 0.
* `address`?: *string* – Destination address of the message\
  Since ABI version 2.3 destination address of external inbound message is used in message\
  body signature calculation. Should be provided when signed external inbound message body is\
  created. Otherwise can be omitted.
* `signature_id`?: *number* – Signature ID to be used in data to sign preparing when CapSignatureWithId capability is enabled

#### Result

* `body`: *string* – Message body BOC encoded with `base64`.
* `data_to_sign`?: *string* – Optional data to sign.\
  Encoded with `base64`.\
  Presents when `message` is unsigned. Can be used for external\
  message signing. Is this case you need to sing this data and\
  produce signed message using `abi.attach_signature`.

### attach\_signature\_to\_message\_body

```ts
type ParamsOfAttachSignatureToMessageBody = {
    abi: Abi,
    public_key: string,
    message: string,
    signature: string
}

type ResultOfAttachSignatureToMessageBody = {
    body: string
}

function attach_signature_to_message_body(
    params: ParamsOfAttachSignatureToMessageBody,
): Promise<ResultOfAttachSignatureToMessageBody>;

function attach_signature_to_message_body_sync(
    params: ParamsOfAttachSignatureToMessageBody,
): ResultOfAttachSignatureToMessageBody;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI
* `public_key`: *string* – Public key.\
  Must be encoded with `hex`.
* `message`: *string* – Unsigned message body BOC.\
  Must be encoded with `base64`.
* `signature`: *string* – Signature.\
  Must be encoded with `hex`.

#### Result

* `body`: *string*

### encode\_message

Encodes an ABI-compatible message

Allows to encode deploy and function call messages, both signed and unsigned.

Use cases include messages of any possible type:

* deploy with initial function call (i.e. `constructor` or any other function that is used for some kind of initialization);
* deploy without initial function call;
* signed/unsigned + data for signing.

`Signer` defines how the message should or shouldn't be signed:

`Signer::None` creates an unsigned message. This may be needed in case of some public methods, that do not require authorization by pubkey.

`Signer::External` takes public key and returns `data_to_sign` for later signing. Use `attach_signature` method with the result signature to get the signed message.

`Signer::Keys` creates a signed message with provided key pair.

\[SOON] `Signer::SigningBox` Allows using a special interface to implement signing without private key disclosure to SDK. For instance, in case of using a cold wallet or HSM, when application calls some API to sign data.

There is an optional public key can be provided in deploy set in order to substitute one in TVM file.

Public key resolving priority:

1. Public key from deploy set.
2. Public key, specified in TVM file.
3. Public key, provided by signer.

```ts
type ParamsOfEncodeMessage = {
    abi: Abi,
    address?: string,
    deploy_set?: DeploySet,
    call_set?: CallSet,
    signer: Signer,
    processing_try_index?: number,
    signature_id?: number
}

type ResultOfEncodeMessage = {
    message: string,
    data_to_sign?: string,
    address: string,
    message_id: string
}

function encode_message(
    params: ParamsOfEncodeMessage,
): Promise<ResultOfEncodeMessage>;

function encode_message_sync(
    params: ParamsOfEncodeMessage,
): ResultOfEncodeMessage;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI.
* `address`?: *string* – Target address the message will be sent to.\
  Must be specified in case of non-deploy message.
* `deploy_set`?: [*DeploySet*](#deployset) – Deploy parameters.\
  Must be specified in case of deploy message.
* `call_set`?: [*CallSet*](#callset) – Function call parameters.\
  Must be specified in case of non-deploy message.\
  \
  In case of deploy message it is optional and contains parameters\
  of the functions that will to be called upon deploy transaction.
* `signer`: [*Signer*](#signer) – Signing parameters.
* `processing_try_index`?: *number* – Processing try index.\
  Used in message processing with retries (if contract's ABI includes "expire" header).\
  \
  Encoder uses the provided try index to calculate message\
  expiration time. The 1st message expiration time is specified in\
  Client config.\
  \
  Expiration timeouts will grow with every retry.\
  Retry grow factor is set in Client config:\
  <.....add config parameter with default value here>\
  \
  Default value is 0.
* `signature_id`?: *number* – Signature ID to be used in data to sign preparing when CapSignatureWithId capability is enabled

#### Result

* `message`: *string* – Message BOC encoded with `base64`.
* `data_to_sign`?: *string* – Optional data to be signed encoded in `base64`.\
  Returned in case of `Signer::External`. Can be used for external\
  message signing. Is this case you need to use this data to create signature and\
  then produce signed message using `abi.attach_signature`.
* `address`: *string* – Destination address.
* `message_id`: *string* – Message id.

### encode\_internal\_message

Encodes an internal ABI-compatible message

Allows to encode deploy and function call messages.

Use cases include messages of any possible type:

* deploy with initial function call (i.e. `constructor` or any other function that is used for some kind of initialization);
* deploy without initial function call;
* simple function call

There is an optional public key can be provided in deploy set in order to substitute one in TVM file.

Public key resolving priority:

1. Public key from deploy set.
2. Public key, specified in TVM file.

```ts
type ParamsOfEncodeInternalMessage = {
    abi?: Abi,
    address?: string,
    src_address?: string,
    deploy_set?: DeploySet,
    call_set?: CallSet,
    value: string,
    bounce?: boolean,
    enable_ihr?: boolean
}

type ResultOfEncodeInternalMessage = {
    message: string,
    address: string,
    message_id: string
}

function encode_internal_message(
    params: ParamsOfEncodeInternalMessage,
): Promise<ResultOfEncodeInternalMessage>;

function encode_internal_message_sync(
    params: ParamsOfEncodeInternalMessage,
): ResultOfEncodeInternalMessage;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`?: [*Abi*](#abi) – Contract ABI.\
  Can be None if both deploy\_set and call\_set are None.
* `address`?: *string* – Target address the message will be sent to.\
  Must be specified in case of non-deploy message.
* `src_address`?: *string* – Source address of the message.
* `deploy_set`?: [*DeploySet*](#deployset) – Deploy parameters.\
  Must be specified in case of deploy message.
* `call_set`?: [*CallSet*](#callset) – Function call parameters.\
  Must be specified in case of non-deploy message.\
  \
  In case of deploy message it is optional and contains parameters\
  of the functions that will to be called upon deploy transaction.
* `value`: *string* – Value in nanotokens to be sent with message.
* `bounce`?: *boolean* – Flag of bounceable message.\
  Default is true.
* `enable_ihr`?: *boolean* – Enable Instant Hypercube Routing for the message.\
  Default is false.

#### Result

* `message`: *string* – Message BOC encoded with `base64`.
* `address`: *string* – Destination address.
* `message_id`: *string* – Message id.

### attach\_signature

Combines `hex`-encoded `signature` with `base64`-encoded `unsigned_message`. Returns signed message encoded in `base64`.

```ts
type ParamsOfAttachSignature = {
    abi: Abi,
    public_key: string,
    message: string,
    signature: string
}

type ResultOfAttachSignature = {
    message: string,
    message_id: string
}

function attach_signature(
    params: ParamsOfAttachSignature,
): Promise<ResultOfAttachSignature>;

function attach_signature_sync(
    params: ParamsOfAttachSignature,
): ResultOfAttachSignature;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI
* `public_key`: *string* – Public key encoded in `hex`.
* `message`: *string* – Unsigned message BOC encoded in `base64`.
* `signature`: *string* – Signature encoded in `hex`.

#### Result

* `message`: *string* – Signed message BOC
* `message_id`: *string* – Message ID

### decode\_message

Decodes message body using provided message BOC and ABI.

```ts
type ParamsOfDecodeMessage = {
    abi: Abi,
    message: string,
    allow_partial?: boolean,
    function_name?: string,
    data_layout?: DataLayout
}

type DecodedMessageBody = {
    body_type: MessageBodyType,
    name: string,
    value?: any,
    header?: FunctionHeader
}

function decode_message(
    params: ParamsOfDecodeMessage,
): Promise<DecodedMessageBody>;

function decode_message_sync(
    params: ParamsOfDecodeMessage,
): DecodedMessageBody;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – contract ABI
* `message`: *string* – Message BOC
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)
* `function_name`?: *string* – Function name or function id if is known in advance
* `data_layout`?: [*DataLayout*](#datalayout)

#### Result

* `body_type`: [*MessageBodyType*](#messagebodytype) – Type of the message body content.
* `name`: *string* – Function or event name.
* `value`?: *any* – Parameters or result value.
* `header`?: [*FunctionHeader*](#functionheader) – Function header.

### decode\_message\_body

Decodes message body using provided body BOC and ABI.

```ts
type ParamsOfDecodeMessageBody = {
    abi: Abi,
    body: string,
    is_internal: boolean,
    allow_partial?: boolean,
    function_name?: string,
    data_layout?: DataLayout
}

type DecodedMessageBody = {
    body_type: MessageBodyType,
    name: string,
    value?: any,
    header?: FunctionHeader
}

function decode_message_body(
    params: ParamsOfDecodeMessageBody,
): Promise<DecodedMessageBody>;

function decode_message_body_sync(
    params: ParamsOfDecodeMessageBody,
): DecodedMessageBody;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI used to decode.
* `body`: *string* – Message body BOC encoded in `base64`.
* `is_internal`: *boolean* – True if the body belongs to the internal message.
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)
* `function_name`?: *string* – Function name or function id if is known in advance
* `data_layout`?: [*DataLayout*](#datalayout)

#### Result

* `body_type`: [*MessageBodyType*](#messagebodytype) – Type of the message body content.
* `name`: *string* – Function or event name.
* `value`?: *any* – Parameters or result value.
* `header`?: [*FunctionHeader*](#functionheader) – Function header.

### encode\_account

Creates account state BOC

```ts
type ParamsOfEncodeAccount = {
    state_init: string,
    balance?: bigint,
    last_trans_lt?: bigint,
    last_paid?: number,
    boc_cache?: BocCacheType
}

type ResultOfEncodeAccount = {
    account: string,
    id: string
}

function encode_account(
    params: ParamsOfEncodeAccount,
): Promise<ResultOfEncodeAccount>;

function encode_account_sync(
    params: ParamsOfEncodeAccount,
): ResultOfEncodeAccount;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `state_init`: *string* – Account state init.
* `balance`?: *bigint* – Initial balance.
* `last_trans_lt`?: *bigint* – Initial value for the `last_trans_lt`.
* `last_paid`?: *number* – Initial value for the `last_paid`.
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided

#### Result

* `account`: *string* – Account BOC encoded in `base64`.
* `id`: *string* – Account ID encoded in `hex`.

### decode\_account\_data

Decodes account data using provided data BOC and ABI.

Note: this feature requires ABI 2.1 or higher.

```ts
type ParamsOfDecodeAccountData = {
    abi: Abi,
    data: string,
    allow_partial?: boolean
}

type ResultOfDecodeAccountData = {
    data: any
}

function decode_account_data(
    params: ParamsOfDecodeAccountData,
): Promise<ResultOfDecodeAccountData>;

function decode_account_data_sync(
    params: ParamsOfDecodeAccountData,
): ResultOfDecodeAccountData;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI
* `data`: *string* – Data BOC or BOC handle
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)

#### Result

* `data`: *any* – Decoded data as a JSON structure.

### update\_initial\_data

Updates initial account data with initial values for the contract's static variables and owner's public key. This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.

Doesn't support ABI version >= 2.4. Use `encode_initial_data` instead

```ts
type ParamsOfUpdateInitialData = {
    abi: Abi,
    data: string,
    initial_data?: any,
    initial_pubkey?: string,
    boc_cache?: BocCacheType
}

type ResultOfUpdateInitialData = {
    data: string
}

function update_initial_data(
    params: ParamsOfUpdateInitialData,
): Promise<ResultOfUpdateInitialData>;

function update_initial_data_sync(
    params: ParamsOfUpdateInitialData,
): ResultOfUpdateInitialData;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI
* `data`: *string* – Data BOC or BOC handle
* `initial_data`?: *any* – List of initial values for contract's static variables.\
  `abi` parameter should be provided to set initial data
* `initial_pubkey`?: *string* – Initial account owner's public key to set into account data
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

#### Result

* `data`: *string* – Updated data BOC or BOC handle

### encode\_initial\_data

Encodes initial account data with initial values for the contract's static variables and owner's public key into a data BOC that can be passed to `encode_tvc` function afterwards.

This function is analogue of `tvm.buildDataInit` function in Solidity.

```ts
type ParamsOfEncodeInitialData = {
    abi: Abi,
    initial_data?: any,
    initial_pubkey?: string,
    boc_cache?: BocCacheType
}

type ResultOfEncodeInitialData = {
    data: string
}

function encode_initial_data(
    params: ParamsOfEncodeInitialData,
): Promise<ResultOfEncodeInitialData>;

function encode_initial_data_sync(
    params: ParamsOfEncodeInitialData,
): ResultOfEncodeInitialData;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI
* `initial_data`?: *any* – List of initial values for contract's static variables.\
  `abi` parameter should be provided to set initial data
* `initial_pubkey`?: *string* – Initial account owner's public key to set into account data
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

#### Result

* `data`: *string* – Updated data BOC or BOC handle

### decode\_initial\_data

Decodes initial values of a contract's static variables and owner's public key from account initial data This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.

Doesn't support ABI version >= 2.4. Use `decode_account_data` instead

```ts
type ParamsOfDecodeInitialData = {
    abi: Abi,
    data: string,
    allow_partial?: boolean
}

type ResultOfDecodeInitialData = {
    initial_data: any,
    initial_pubkey: string
}

function decode_initial_data(
    params: ParamsOfDecodeInitialData,
): Promise<ResultOfDecodeInitialData>;

function decode_initial_data_sync(
    params: ParamsOfDecodeInitialData,
): ResultOfDecodeInitialData;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI.\
  Initial data is decoded if this parameter is provided
* `data`: *string* – Data BOC or BOC handle
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)

#### Result

* `initial_data`: *any* – List of initial values of contract's public variables.\
  Initial data is decoded if `abi` input parameter is provided
* `initial_pubkey`: *string* – Initial account owner's public key

### decode\_boc

Decodes BOC into JSON as a set of provided parameters.

Solidity functions use ABI types for [builder encoding](https://github.com/everx-labs/TVM-Solidity-Compiler/blob/master/API.md#tvmbuilderstore). The simplest way to decode such a BOC is to use ABI decoding. ABI has it own rules for fields layout in cells so manually encoded BOC can not be described in terms of ABI rules.

To solve this problem we introduce a new ABI type `Ref(<ParamType>)` which allows to store `ParamType` ABI parameter in cell reference and, thus, decode manually encoded BOCs. This type is available only in `decode_boc` function and will not be available in ABI messages encoding until it is included into some ABI revision.

Such BOC descriptions covers most users needs. If someone wants to decode some BOC which can not be described by these rules (i.e. BOC with TLB containing constructors of flags defining some parsing conditions) then they can decode the fields up to fork condition, check the parsed data manually, expand the parsing schema and then decode the whole BOC with the full schema.

```ts
type ParamsOfDecodeBoc = {
    params: AbiParam[],
    boc: string,
    allow_partial: boolean
}

type ResultOfDecodeBoc = {
    data: any
}

function decode_boc(
    params: ParamsOfDecodeBoc,
): Promise<ResultOfDecodeBoc>;

function decode_boc_sync(
    params: ParamsOfDecodeBoc,
): ResultOfDecodeBoc;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `params`: [*AbiParam*](#abiparam)*\[]* – Parameters to decode from BOC
* `boc`: *string* – Data BOC or BOC handle
* `allow_partial`: *boolean*

#### Result

* `data`: *any* – Decoded data as a JSON structure.

### encode\_boc

Encodes given parameters in JSON into a BOC using param types from ABI.

```ts
type ParamsOfAbiEncodeBoc = {
    params: AbiParam[],
    data: any,
    boc_cache?: BocCacheType
}

type ResultOfAbiEncodeBoc = {
    boc: string
}

function encode_boc(
    params: ParamsOfAbiEncodeBoc,
): Promise<ResultOfAbiEncodeBoc>;

function encode_boc_sync(
    params: ParamsOfAbiEncodeBoc,
): ResultOfAbiEncodeBoc;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `params`: [*AbiParam*](#abiparam)*\[]* – Parameters to encode into BOC
* `data`: *any* – Parameters and values as a JSON structure
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided

#### Result

* `boc`: *string* – BOC encoded as base64

### calc\_function\_id

Calculates contract function ID by contract ABI

```ts
type ParamsOfCalcFunctionId = {
    abi: Abi,
    function_name: string,
    output?: boolean
}

type ResultOfCalcFunctionId = {
    function_id: number
}

function calc_function_id(
    params: ParamsOfCalcFunctionId,
): Promise<ResultOfCalcFunctionId>;

function calc_function_id_sync(
    params: ParamsOfCalcFunctionId,
): ResultOfCalcFunctionId;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI.
* `function_name`: *string* – Contract function name
* `output`?: *boolean* – If set to `true` output function ID will be returned which is used in contract response. Default is `false`

#### Result

* `function_id`: *number* – Contract function ID

### get\_signature\_data

Extracts signature from message body and calculates hash to verify the signature

```ts
type ParamsOfGetSignatureData = {
    abi: Abi,
    message: string,
    signature_id?: number
}

type ResultOfGetSignatureData = {
    signature: string,
    unsigned: string
}

function get_signature_data(
    params: ParamsOfGetSignatureData,
): Promise<ResultOfGetSignatureData>;

function get_signature_data_sync(
    params: ParamsOfGetSignatureData,
): ResultOfGetSignatureData;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`: [*Abi*](#abi) – Contract ABI used to decode.
* `message`: *string* – Message BOC encoded in `base64`.
* `signature_id`?: *number* – Signature ID to be used in unsigned data preparing when CapSignatureWithId capability is enabled

#### Result

* `signature`: *string* – Signature from the message in `hex`.
* `unsigned`: *string* – Data to verify the signature in `base64`.

## Types

### AbiErrorCode

```ts
enum AbiErrorCode {
    RequiredAddressMissingForEncodeMessage = 301,
    RequiredCallSetMissingForEncodeMessage = 302,
    InvalidJson = 303,
    InvalidMessage = 304,
    EncodeDeployMessageFailed = 305,
    EncodeRunMessageFailed = 306,
    AttachSignatureFailed = 307,
    InvalidTvcImage = 308,
    RequiredPublicKeyMissingForFunctionHeader = 309,
    InvalidSigner = 310,
    InvalidAbi = 311,
    InvalidFunctionId = 312,
    InvalidData = 313,
    EncodeInitialDataFailed = 314,
    InvalidFunctionName = 315,
    PubKeyNotSupported = 316
}
```

One of the following value:

* `RequiredAddressMissingForEncodeMessage = 301`
* `RequiredCallSetMissingForEncodeMessage = 302`
* `InvalidJson = 303`
* `InvalidMessage = 304`
* `EncodeDeployMessageFailed = 305`
* `EncodeRunMessageFailed = 306`
* `AttachSignatureFailed = 307`
* `InvalidTvcImage = 308`
* `RequiredPublicKeyMissingForFunctionHeader = 309`
* `InvalidSigner = 310`
* `InvalidAbi = 311`
* `InvalidFunctionId = 312`
* `InvalidData = 313`
* `EncodeInitialDataFailed = 314`
* `InvalidFunctionName = 315`
* `PubKeyNotSupported = 316`

### AbiContractVariant

```ts
type AbiContractVariant = {
    value: AbiContract
}
```

* `value`: [*AbiContract*](#abicontract)

### AbiJsonVariant

```ts
type AbiJsonVariant = {
    value: string
}
```

* `value`: *string*

### AbiHandleVariant

```ts
type AbiHandleVariant = {
    value: AbiHandle
}
```

* `value`: [*AbiHandle*](#abihandle)

### AbiSerializedVariant

```ts
type AbiSerializedVariant = {
    value: AbiContract
}
```

* `value`: [*AbiContract*](#abicontract)

### Abi

```ts
type Abi = ({
    type: 'Contract'
} & AbiContractVariant) | ({
    type: 'Json'
} & AbiJsonVariant) | ({
    type: 'Handle'
} & AbiHandleVariant) | ({
    type: 'Serialized'
} & AbiSerializedVariant)
```

Depends on value of the `type` field.

When *type* is *'Contract'*

* `value`: [*AbiContract*](#abicontract)

When *type* is *'Json'*

* `value`: *string*

When *type* is *'Handle'*

* `value`: [*AbiHandle*](#abihandle)

When *type* is *'Serialized'*

* `value`: [*AbiContract*](#abicontract)

Variant constructors:

```ts
function abiContract(value: AbiContract): Abi;
function abiJson(value: string): Abi;
function abiHandle(value: AbiHandle): Abi;
function abiSerialized(value: AbiContract): Abi;
```

### AbiHandle

```ts
type AbiHandle = number
```

### FunctionHeader

The ABI function header.

Includes several hidden function parameters that contract uses for security, message delivery monitoring and replay protection reasons.

The actual set of header fields depends on the contract's ABI. If a contract's ABI does not include some headers, then they are not filled.

```ts
type FunctionHeader = {
    expire?: number,
    time?: bigint,
    pubkey?: string
}
```

* `expire`?: *number* – Message expiration timestamp (UNIX time) in seconds.\
  If not specified - calculated automatically from message\_expiration\_timeout(),\
  try\_index and message\_expiration\_timeout\_grow\_factor() (if ABI includes `expire` header).
* `time`?: *bigint* – Message creation time in milliseconds.\
  If not specified, `now` is used (if ABI includes `time` header).
* `pubkey`?: *string* – Public key is used by the contract to check the signature.\
  Encoded in `hex`. If not specified, method fails with exception (if ABI includes `pubkey` header).

### CallSet

```ts
type CallSet = {
    function_name: string,
    header?: FunctionHeader,
    input?: any
}
```

* `function_name`: *string* – Function name that is being called. Or function id encoded as string in hex (starting with 0x).
* `header`?: [*FunctionHeader*](#functionheader) – Function header.\
  If an application omits some header parameters required by the\
  contract's ABI, the library will set the default values for\
  them.
* `input`?: *any* – Function input parameters according to ABI.

### DeploySet

```ts
type DeploySet = {
    tvc?: string,
    code?: string,
    state_init?: string,
    workchain_id?: number,
    initial_data?: any,
    initial_pubkey?: string
}
```

* `tvc`?: *string* – Content of TVC file encoded in `base64`. For compatibility reason this field can contain an encoded `StateInit`.
* `code`?: *string* – Contract code BOC encoded with base64.
* `state_init`?: *string* – State init BOC encoded with base64.
* `workchain_id`?: *number* – Target workchain for destination address.\
  Default is `0`.
* `initial_data`?: *any* – List of initial values for contract's public variables.
* `initial_pubkey`?: *string* – Optional public key that can be provided in deploy set in order to substitute one in TVM file or provided by Signer.\
  Public key resolving priority:\
  1\. Public key from deploy set.\
  2\. Public key, specified in TVM file.\
  3\. Public key, provided by Signer.\
  \
  Applicable only for contracts with ABI version < 2.4. Contract initial public key should be\
  explicitly provided inside `initial_data` since ABI 2.4

### SignerNoneVariant

No keys are provided.

Creates an unsigned message.

```ts
type SignerNoneVariant = {

}
```

### SignerExternalVariant

Only public key is provided in unprefixed hex string format to generate unsigned message and `data_to_sign` which can be signed later.

```ts
type SignerExternalVariant = {
    public_key: string
}
```

* `public_key`: *string*

### SignerKeysVariant

Key pair is provided for signing

```ts
type SignerKeysVariant = {
    keys: KeyPair
}
```

* `keys`: [*KeyPair*](/ever-sdk/reference/types-and-methods/mod_crypto#keypair)

### SignerSigningBoxVariant

Signing Box interface is provided for signing, allows Dapps to sign messages using external APIs, such as HSM, cold wallet, etc.

```ts
type SignerSigningBoxVariant = {
    handle: SigningBoxHandle
}
```

* `handle`: [*SigningBoxHandle*](/ever-sdk/reference/types-and-methods/mod_crypto#signingboxhandle)

### Signer

```ts
type Signer = ({
    type: 'None'
} & SignerNoneVariant) | ({
    type: 'External'
} & SignerExternalVariant) | ({
    type: 'Keys'
} & SignerKeysVariant) | ({
    type: 'SigningBox'
} & SignerSigningBoxVariant)
```

Depends on value of the `type` field.

When *type* is *'None'*

No keys are provided.

Creates an unsigned message.

When *type* is *'External'*

Only public key is provided in unprefixed hex string format to generate unsigned message and `data_to_sign` which can be signed later.

* `public_key`: *string*

When *type* is *'Keys'*

Key pair is provided for signing

* `keys`: [*KeyPair*](/ever-sdk/reference/types-and-methods/mod_crypto#keypair)

When *type* is *'SigningBox'*

Signing Box interface is provided for signing, allows Dapps to sign messages using external APIs, such as HSM, cold wallet, etc.

* `handle`: [*SigningBoxHandle*](/ever-sdk/reference/types-and-methods/mod_crypto#signingboxhandle)

Variant constructors:

```ts
function signerNone(): Signer;
function signerExternal(public_key: string): Signer;
function signerKeys(keys: KeyPair): Signer;
function signerSigningBox(handle: SigningBoxHandle): Signer;
```

### MessageBodyType

```ts
enum MessageBodyType {
    Input = "Input",
    Output = "Output",
    InternalOutput = "InternalOutput",
    Event = "Event"
}
```

One of the following value:

* `Input = "Input"` – Message contains the input of the ABI function.
* `Output = "Output"` – Message contains the output of the ABI function.
* `InternalOutput = "InternalOutput"` – Message contains the input of the imported ABI function.\
  Occurs when contract sends an internal message to other\
  contract.
* `Event = "Event"` – Message contains the input of the ABI event.

### AbiParam

```ts
type AbiParam = {
    name: string,
    type: string,
    components?: AbiParam[],
    init?: boolean
}
```

* `name`: *string*
* `type`: *string*
* `components`?: [*AbiParam*](#abiparam)*\[]*
* `init`?: *boolean*

### AbiEvent

```ts
type AbiEvent = {
    name: string,
    inputs: AbiParam[],
    id?: string | null
}
```

* `name`: *string*
* `inputs`: [*AbiParam*](#abiparam)*\[]*
* `id`?: *string?*

### AbiData

```ts
type AbiData = {
    key: number,
    name: string,
    type: string,
    components?: AbiParam[]
}
```

* `key`: *number*
* `name`: *string*
* `type`: *string*
* `components`?: [*AbiParam*](#abiparam)*\[]*

### AbiFunction

```ts
type AbiFunction = {
    name: string,
    inputs: AbiParam[],
    outputs: AbiParam[],
    id?: string | null
}
```

* `name`: *string*
* `inputs`: [*AbiParam*](#abiparam)*\[]*
* `outputs`: [*AbiParam*](#abiparam)*\[]*
* `id`?: *string?*

### AbiContract

```ts
type AbiContract = {
    'ABI version'?: number,
    abi_version?: number,
    version?: string | null,
    header?: string[],
    functions?: AbiFunction[],
    events?: AbiEvent[],
    data?: AbiData[],
    fields?: AbiParam[]
}
```

* `ABI version`?: *number*
* `abi_version`?: *number*
* `version`?: *string?*
* `header`?: *string\[]*
* `functions`?: [*AbiFunction*](#abifunction)*\[]*
* `events`?: [*AbiEvent*](#abievent)*\[]*
* `data`?: [*AbiData*](#abidata)*\[]*
* `fields`?: [*AbiParam*](#abiparam)*\[]*

### DataLayout

```ts
enum DataLayout {
    Input = "Input",
    Output = "Output"
}
```

One of the following value:

* `Input = "Input"` – Decode message body as function input parameters.
* `Output = "Output"` – Decode message body as function output.

### ParamsOfEncodeMessageBody

```ts
type ParamsOfEncodeMessageBody = {
    abi: Abi,
    call_set: CallSet,
    is_internal: boolean,
    signer: Signer,
    processing_try_index?: number,
    address?: string,
    signature_id?: number
}
```

* `abi`: [*Abi*](#abi) – Contract ABI.
* `call_set`: [*CallSet*](#callset) – Function call parameters.\
  Must be specified in non deploy message.\
  \
  In case of deploy message contains parameters of constructor.
* `is_internal`: *boolean* – True if internal message body must be encoded.
* `signer`: [*Signer*](#signer) – Signing parameters.
* `processing_try_index`?: *number* – Processing try index.\
  Used in message processing with retries.\
  \
  Encoder uses the provided try index to calculate message\
  expiration time.\
  \
  Expiration timeouts will grow with every retry.\
  \
  Default value is 0.
* `address`?: *string* – Destination address of the message\
  Since ABI version 2.3 destination address of external inbound message is used in message\
  body signature calculation. Should be provided when signed external inbound message body is\
  created. Otherwise can be omitted.
* `signature_id`?: *number* – Signature ID to be used in data to sign preparing when CapSignatureWithId capability is enabled

### ResultOfEncodeMessageBody

```ts
type ResultOfEncodeMessageBody = {
    body: string,
    data_to_sign?: string
}
```

* `body`: *string* – Message body BOC encoded with `base64`.
* `data_to_sign`?: *string* – Optional data to sign.\
  Encoded with `base64`.\
  Presents when `message` is unsigned. Can be used for external\
  message signing. Is this case you need to sing this data and\
  produce signed message using `abi.attach_signature`.

### ParamsOfAttachSignatureToMessageBody

```ts
type ParamsOfAttachSignatureToMessageBody = {
    abi: Abi,
    public_key: string,
    message: string,
    signature: string
}
```

* `abi`: [*Abi*](#abi) – Contract ABI
* `public_key`: *string* – Public key.\
  Must be encoded with `hex`.
* `message`: *string* – Unsigned message body BOC.\
  Must be encoded with `base64`.
* `signature`: *string* – Signature.\
  Must be encoded with `hex`.

### ResultOfAttachSignatureToMessageBody

```ts
type ResultOfAttachSignatureToMessageBody = {
    body: string
}
```

* `body`: *string*

### ParamsOfEncodeMessage

```ts
type ParamsOfEncodeMessage = {
    abi: Abi,
    address?: string,
    deploy_set?: DeploySet,
    call_set?: CallSet,
    signer: Signer,
    processing_try_index?: number,
    signature_id?: number
}
```

* `abi`: [*Abi*](#abi) – Contract ABI.
* `address`?: *string* – Target address the message will be sent to.\
  Must be specified in case of non-deploy message.
* `deploy_set`?: [*DeploySet*](#deployset) – Deploy parameters.\
  Must be specified in case of deploy message.
* `call_set`?: [*CallSet*](#callset) – Function call parameters.\
  Must be specified in case of non-deploy message.\
  \
  In case of deploy message it is optional and contains parameters\
  of the functions that will to be called upon deploy transaction.
* `signer`: [*Signer*](#signer) – Signing parameters.
* `processing_try_index`?: *number* – Processing try index.\
  Used in message processing with retries (if contract's ABI includes "expire" header).\
  \
  Encoder uses the provided try index to calculate message\
  expiration time. The 1st message expiration time is specified in\
  Client config.\
  \
  Expiration timeouts will grow with every retry.\
  Retry grow factor is set in Client config:\
  <.....add config parameter with default value here>\
  \
  Default value is 0.
* `signature_id`?: *number* – Signature ID to be used in data to sign preparing when CapSignatureWithId capability is enabled

### ResultOfEncodeMessage

```ts
type ResultOfEncodeMessage = {
    message: string,
    data_to_sign?: string,
    address: string,
    message_id: string
}
```

* `message`: *string* – Message BOC encoded with `base64`.
* `data_to_sign`?: *string* – Optional data to be signed encoded in `base64`.\
  Returned in case of `Signer::External`. Can be used for external\
  message signing. Is this case you need to use this data to create signature and\
  then produce signed message using `abi.attach_signature`.
* `address`: *string* – Destination address.
* `message_id`: *string* – Message id.

### ParamsOfEncodeInternalMessage

```ts
type ParamsOfEncodeInternalMessage = {
    abi?: Abi,
    address?: string,
    src_address?: string,
    deploy_set?: DeploySet,
    call_set?: CallSet,
    value: string,
    bounce?: boolean,
    enable_ihr?: boolean
}
```

* `abi`?: [*Abi*](#abi) – Contract ABI.\
  Can be None if both deploy\_set and call\_set are None.
* `address`?: *string* – Target address the message will be sent to.\
  Must be specified in case of non-deploy message.
* `src_address`?: *string* – Source address of the message.
* `deploy_set`?: [*DeploySet*](#deployset) – Deploy parameters.\
  Must be specified in case of deploy message.
* `call_set`?: [*CallSet*](#callset) – Function call parameters.\
  Must be specified in case of non-deploy message.\
  \
  In case of deploy message it is optional and contains parameters\
  of the functions that will to be called upon deploy transaction.
* `value`: *string* – Value in nanotokens to be sent with message.
* `bounce`?: *boolean* – Flag of bounceable message.\
  Default is true.
* `enable_ihr`?: *boolean* – Enable Instant Hypercube Routing for the message.\
  Default is false.

### ResultOfEncodeInternalMessage

```ts
type ResultOfEncodeInternalMessage = {
    message: string,
    address: string,
    message_id: string
}
```

* `message`: *string* – Message BOC encoded with `base64`.
* `address`: *string* – Destination address.
* `message_id`: *string* – Message id.

### ParamsOfAttachSignature

```ts
type ParamsOfAttachSignature = {
    abi: Abi,
    public_key: string,
    message: string,
    signature: string
}
```

* `abi`: [*Abi*](#abi) – Contract ABI
* `public_key`: *string* – Public key encoded in `hex`.
* `message`: *string* – Unsigned message BOC encoded in `base64`.
* `signature`: *string* – Signature encoded in `hex`.

### ResultOfAttachSignature

```ts
type ResultOfAttachSignature = {
    message: string,
    message_id: string
}
```

* `message`: *string* – Signed message BOC
* `message_id`: *string* – Message ID

### ParamsOfDecodeMessage

```ts
type ParamsOfDecodeMessage = {
    abi: Abi,
    message: string,
    allow_partial?: boolean,
    function_name?: string,
    data_layout?: DataLayout
}
```

* `abi`: [*Abi*](#abi) – contract ABI
* `message`: *string* – Message BOC
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)
* `function_name`?: *string* – Function name or function id if is known in advance
* `data_layout`?: [*DataLayout*](#datalayout)

### DecodedMessageBody

```ts
type DecodedMessageBody = {
    body_type: MessageBodyType,
    name: string,
    value?: any,
    header?: FunctionHeader
}
```

* `body_type`: [*MessageBodyType*](#messagebodytype) – Type of the message body content.
* `name`: *string* – Function or event name.
* `value`?: *any* – Parameters or result value.
* `header`?: [*FunctionHeader*](#functionheader) – Function header.

### ParamsOfDecodeMessageBody

```ts
type ParamsOfDecodeMessageBody = {
    abi: Abi,
    body: string,
    is_internal: boolean,
    allow_partial?: boolean,
    function_name?: string,
    data_layout?: DataLayout
}
```

* `abi`: [*Abi*](#abi) – Contract ABI used to decode.
* `body`: *string* – Message body BOC encoded in `base64`.
* `is_internal`: *boolean* – True if the body belongs to the internal message.
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)
* `function_name`?: *string* – Function name or function id if is known in advance
* `data_layout`?: [*DataLayout*](#datalayout)

### ParamsOfEncodeAccount

```ts
type ParamsOfEncodeAccount = {
    state_init: string,
    balance?: bigint,
    last_trans_lt?: bigint,
    last_paid?: number,
    boc_cache?: BocCacheType
}
```

* `state_init`: *string* – Account state init.
* `balance`?: *bigint* – Initial balance.
* `last_trans_lt`?: *bigint* – Initial value for the `last_trans_lt`.
* `last_paid`?: *number* – Initial value for the `last_paid`.
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided

### ResultOfEncodeAccount

```ts
type ResultOfEncodeAccount = {
    account: string,
    id: string
}
```

* `account`: *string* – Account BOC encoded in `base64`.
* `id`: *string* – Account ID encoded in `hex`.

### ParamsOfDecodeAccountData

```ts
type ParamsOfDecodeAccountData = {
    abi: Abi,
    data: string,
    allow_partial?: boolean
}
```

* `abi`: [*Abi*](#abi) – Contract ABI
* `data`: *string* – Data BOC or BOC handle
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)

### ResultOfDecodeAccountData

```ts
type ResultOfDecodeAccountData = {
    data: any
}
```

* `data`: *any* – Decoded data as a JSON structure.

### ParamsOfUpdateInitialData

```ts
type ParamsOfUpdateInitialData = {
    abi: Abi,
    data: string,
    initial_data?: any,
    initial_pubkey?: string,
    boc_cache?: BocCacheType
}
```

* `abi`: [*Abi*](#abi) – Contract ABI
* `data`: *string* – Data BOC or BOC handle
* `initial_data`?: *any* – List of initial values for contract's static variables.\
  `abi` parameter should be provided to set initial data
* `initial_pubkey`?: *string* – Initial account owner's public key to set into account data
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

### ResultOfUpdateInitialData

```ts
type ResultOfUpdateInitialData = {
    data: string
}
```

* `data`: *string* – Updated data BOC or BOC handle

### ParamsOfEncodeInitialData

```ts
type ParamsOfEncodeInitialData = {
    abi: Abi,
    initial_data?: any,
    initial_pubkey?: string,
    boc_cache?: BocCacheType
}
```

* `abi`: [*Abi*](#abi) – Contract ABI
* `initial_data`?: *any* – List of initial values for contract's static variables.\
  `abi` parameter should be provided to set initial data
* `initial_pubkey`?: *string* – Initial account owner's public key to set into account data
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

### ResultOfEncodeInitialData

```ts
type ResultOfEncodeInitialData = {
    data: string
}
```

* `data`: *string* – Updated data BOC or BOC handle

### ParamsOfDecodeInitialData

```ts
type ParamsOfDecodeInitialData = {
    abi: Abi,
    data: string,
    allow_partial?: boolean
}
```

* `abi`: [*Abi*](#abi) – Contract ABI.\
  Initial data is decoded if this parameter is provided
* `data`: *string* – Data BOC or BOC handle
* `allow_partial`?: *boolean* – Flag allowing partial BOC decoding when ABI doesn't describe the full body BOC. Controls decoder behaviour when after decoding all described in ABI params there are some data left in BOC: `true` - return decoded values `false` - return error of incomplete BOC deserialization (default)

### ResultOfDecodeInitialData

```ts
type ResultOfDecodeInitialData = {
    initial_data: any,
    initial_pubkey: string
}
```

* `initial_data`: *any* – List of initial values of contract's public variables.\
  Initial data is decoded if `abi` input parameter is provided
* `initial_pubkey`: *string* – Initial account owner's public key

### ParamsOfDecodeBoc

```ts
type ParamsOfDecodeBoc = {
    params: AbiParam[],
    boc: string,
    allow_partial: boolean
}
```

* `params`: [*AbiParam*](#abiparam)*\[]* – Parameters to decode from BOC
* `boc`: *string* – Data BOC or BOC handle
* `allow_partial`: *boolean*

### ResultOfDecodeBoc

```ts
type ResultOfDecodeBoc = {
    data: any
}
```

* `data`: *any* – Decoded data as a JSON structure.

### ParamsOfAbiEncodeBoc

```ts
type ParamsOfAbiEncodeBoc = {
    params: AbiParam[],
    data: any,
    boc_cache?: BocCacheType
}
```

* `params`: [*AbiParam*](#abiparam)*\[]* – Parameters to encode into BOC
* `data`: *any* – Parameters and values as a JSON structure
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided

### ResultOfAbiEncodeBoc

```ts
type ResultOfAbiEncodeBoc = {
    boc: string
}
```

* `boc`: *string* – BOC encoded as base64

### ParamsOfCalcFunctionId

```ts
type ParamsOfCalcFunctionId = {
    abi: Abi,
    function_name: string,
    output?: boolean
}
```

* `abi`: [*Abi*](#abi) – Contract ABI.
* `function_name`: *string* – Contract function name
* `output`?: *boolean* – If set to `true` output function ID will be returned which is used in contract response. Default is `false`

### ResultOfCalcFunctionId

```ts
type ResultOfCalcFunctionId = {
    function_id: number
}
```

* `function_id`: *number* – Contract function ID

### ParamsOfGetSignatureData

```ts
type ParamsOfGetSignatureData = {
    abi: Abi,
    message: string,
    signature_id?: number
}
```

* `abi`: [*Abi*](#abi) – Contract ABI used to decode.
* `message`: *string* – Message BOC encoded in `base64`.
* `signature_id`?: *number* – Signature ID to be used in unsigned data preparing when CapSignatureWithId capability is enabled

### ResultOfGetSignatureData

```ts
type ResultOfGetSignatureData = {
    signature: string,
    unsigned: string
}
```

* `signature`: *string* – Signature from the message in `hex`.
* `unsigned`: *string* – Data to verify the signature in `base64`.


# Module boc

## Module boc

BOC manipulation module.

### Functions

[decode\_tvc](#decode_tvc) – Decodes tvc according to the tvc spec. Read more about tvc structure here <https://github.com/everx-labs/ever-struct/blob/main/src/scheme/mod.rs#L30>

[parse\_message](#parse_message) – Parses message boc into a JSON

[parse\_transaction](#parse_transaction) – Parses transaction boc into a JSON

[parse\_account](#parse_account) – Parses account boc into a JSON

[parse\_block](#parse_block) – Parses block boc into a JSON

[parse\_shardstate](#parse_shardstate) – Parses shardstate boc into a JSON

[get\_blockchain\_config](#get_blockchain_config) – Extract blockchain configuration from key block and also from zerostate.

[get\_boc\_hash](#get_boc_hash) – Calculates BOC root hash

[get\_boc\_depth](#get_boc_depth) – Calculates BOC depth

[get\_code\_from\_tvc](#get_code_from_tvc) – Extracts code from TVC contract image

[cache\_get](#cache_get) – Get BOC from cache

[cache\_set](#cache_set) – Save BOC into cache or increase pin counter for existing pinned BOC

[cache\_unpin](#cache_unpin) – Unpin BOCs with specified pin defined in the `cache_set`. Decrease pin reference counter for BOCs with specified pin defined in the `cache_set`. BOCs which have only 1 pin and its reference counter become 0 will be removed from cache

[encode\_boc](#encode_boc) – Encodes bag of cells (BOC) with builder operations. This method provides the same functionality as Solidity TvmBuilder. Resulting BOC of this method can be passed into Solidity and C++ contracts as TvmCell type.

[get\_code\_salt](#get_code_salt) – Returns the contract code's salt if it is present.

[set\_code\_salt](#set_code_salt) – Sets new salt to contract code.

[decode\_state\_init](#decode_state_init) – Decodes contract's initial state into code, data, libraries and special options.

[encode\_state\_init](#encode_state_init) – Encodes initial contract state from code, data, libraries ans special options (see input params)

[encode\_external\_in\_message](#encode_external_in_message) – Encodes a message

[get\_compiler\_version](#get_compiler_version) – Returns the compiler version used to compile the code.

### Types

[BocCacheTypePinnedVariant](#boccachetypepinnedvariant) – Pin the BOC with `pin` name.

[BocCacheTypeUnpinnedVariant](#boccachetypeunpinnedvariant) – BOC is placed into a common BOC pool with limited size regulated by LRU (least recently used) cache lifecycle.

[BocCacheType](#boccachetype)

[BuilderOpIntegerVariant](#builderopintegervariant) – Append integer to cell data.

[BuilderOpBitStringVariant](#builderopbitstringvariant) – Append bit string to cell data.

[BuilderOpCellVariant](#builderopcellvariant) – Append ref to nested cells.

[BuilderOpCellBocVariant](#builderopcellbocvariant) – Append ref to nested cell.

[BuilderOpAddressVariant](#builderopaddressvariant) – Address.

[BuilderOp](#builderop) – Cell builder operation.

[TvcV1Variant](#tvcv1variant)

[Tvc](#tvc)

[TvcV1](#tvcv1)

[BocErrorCode](#bocerrorcode)

[ParamsOfDecodeTvc](#paramsofdecodetvc)

[ResultOfDecodeTvc](#resultofdecodetvc)

[ParamsOfParse](#paramsofparse)

[ResultOfParse](#resultofparse)

[ParamsOfParseShardstate](#paramsofparseshardstate)

[ParamsOfGetBlockchainConfig](#paramsofgetblockchainconfig)

[ResultOfGetBlockchainConfig](#resultofgetblockchainconfig)

[ParamsOfGetBocHash](#paramsofgetbochash)

[ResultOfGetBocHash](#resultofgetbochash)

[ParamsOfGetBocDepth](#paramsofgetbocdepth)

[ResultOfGetBocDepth](#resultofgetbocdepth)

[ParamsOfGetCodeFromTvc](#paramsofgetcodefromtvc)

[ResultOfGetCodeFromTvc](#resultofgetcodefromtvc)

[ParamsOfBocCacheGet](#paramsofboccacheget)

[ResultOfBocCacheGet](#resultofboccacheget)

[ParamsOfBocCacheSet](#paramsofboccacheset)

[ResultOfBocCacheSet](#resultofboccacheset)

[ParamsOfBocCacheUnpin](#paramsofboccacheunpin)

[ParamsOfEncodeBoc](#paramsofencodeboc)

[ResultOfEncodeBoc](#resultofencodeboc)

[ParamsOfGetCodeSalt](#paramsofgetcodesalt)

[ResultOfGetCodeSalt](#resultofgetcodesalt)

[ParamsOfSetCodeSalt](#paramsofsetcodesalt)

[ResultOfSetCodeSalt](#resultofsetcodesalt)

[ParamsOfDecodeStateInit](#paramsofdecodestateinit)

[ResultOfDecodeStateInit](#resultofdecodestateinit)

[ParamsOfEncodeStateInit](#paramsofencodestateinit)

[ResultOfEncodeStateInit](#resultofencodestateinit)

[ParamsOfEncodeExternalInMessage](#paramsofencodeexternalinmessage)

[ResultOfEncodeExternalInMessage](#resultofencodeexternalinmessage)

[ParamsOfGetCompilerVersion](#paramsofgetcompilerversion)

[ResultOfGetCompilerVersion](#resultofgetcompilerversion)

## Functions

### decode\_tvc

Decodes tvc according to the tvc spec. Read more about tvc structure here <https://github.com/everx-labs/ever-struct/blob/main/src/scheme/mod.rs#L30>

```ts
type ParamsOfDecodeTvc = {
    tvc: string
}

type ResultOfDecodeTvc = {
    tvc: Tvc
}

function decode_tvc(
    params: ParamsOfDecodeTvc,
): Promise<ResultOfDecodeTvc>;

function decode_tvc_sync(
    params: ParamsOfDecodeTvc,
): ResultOfDecodeTvc;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `tvc`: *string* – Contract TVC BOC encoded as base64 or BOC handle

#### Result

* `tvc`: [*Tvc*](#tvc) – Decoded TVC

### parse\_message

Parses message boc into a JSON

JSON structure is compatible with GraphQL API message object

```ts
type ParamsOfParse = {
    boc: string
}

type ResultOfParse = {
    parsed: any
}

function parse_message(
    params: ParamsOfParse,
): Promise<ResultOfParse>;

function parse_message_sync(
    params: ParamsOfParse,
): ResultOfParse;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64

#### Result

* `parsed`: *any* – JSON containing parsed BOC

### parse\_transaction

Parses transaction boc into a JSON

JSON structure is compatible with GraphQL API transaction object

```ts
type ParamsOfParse = {
    boc: string
}

type ResultOfParse = {
    parsed: any
}

function parse_transaction(
    params: ParamsOfParse,
): Promise<ResultOfParse>;

function parse_transaction_sync(
    params: ParamsOfParse,
): ResultOfParse;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64

#### Result

* `parsed`: *any* – JSON containing parsed BOC

### parse\_account

Parses account boc into a JSON

JSON structure is compatible with GraphQL API account object

```ts
type ParamsOfParse = {
    boc: string
}

type ResultOfParse = {
    parsed: any
}

function parse_account(
    params: ParamsOfParse,
): Promise<ResultOfParse>;

function parse_account_sync(
    params: ParamsOfParse,
): ResultOfParse;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64

#### Result

* `parsed`: *any* – JSON containing parsed BOC

### parse\_block

Parses block boc into a JSON

JSON structure is compatible with GraphQL API block object

```ts
type ParamsOfParse = {
    boc: string
}

type ResultOfParse = {
    parsed: any
}

function parse_block(
    params: ParamsOfParse,
): Promise<ResultOfParse>;

function parse_block_sync(
    params: ParamsOfParse,
): ResultOfParse;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64

#### Result

* `parsed`: *any* – JSON containing parsed BOC

### parse\_shardstate

Parses shardstate boc into a JSON

JSON structure is compatible with GraphQL API shardstate object

```ts
type ParamsOfParseShardstate = {
    boc: string,
    id: string,
    workchain_id: number
}

type ResultOfParse = {
    parsed: any
}

function parse_shardstate(
    params: ParamsOfParseShardstate,
): Promise<ResultOfParse>;

function parse_shardstate_sync(
    params: ParamsOfParseShardstate,
): ResultOfParse;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64
* `id`: *string* – Shardstate identifier
* `workchain_id`: *number* – Workchain shardstate belongs to

#### Result

* `parsed`: *any* – JSON containing parsed BOC

### get\_blockchain\_config

Extract blockchain configuration from key block and also from zerostate.

```ts
type ParamsOfGetBlockchainConfig = {
    block_boc: string
}

type ResultOfGetBlockchainConfig = {
    config_boc: string
}

function get_blockchain_config(
    params: ParamsOfGetBlockchainConfig,
): Promise<ResultOfGetBlockchainConfig>;

function get_blockchain_config_sync(
    params: ParamsOfGetBlockchainConfig,
): ResultOfGetBlockchainConfig;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `block_boc`: *string* – Key block BOC or zerostate BOC encoded as base64

#### Result

* `config_boc`: *string* – Blockchain config BOC encoded as base64

### get\_boc\_hash

Calculates BOC root hash

```ts
type ParamsOfGetBocHash = {
    boc: string
}

type ResultOfGetBocHash = {
    hash: string
}

function get_boc_hash(
    params: ParamsOfGetBocHash,
): Promise<ResultOfGetBocHash>;

function get_boc_hash_sync(
    params: ParamsOfGetBocHash,
): ResultOfGetBocHash;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64 or BOC handle

#### Result

* `hash`: *string* – BOC root hash encoded with hex

### get\_boc\_depth

Calculates BOC depth

```ts
type ParamsOfGetBocDepth = {
    boc: string
}

type ResultOfGetBocDepth = {
    depth: number
}

function get_boc_depth(
    params: ParamsOfGetBocDepth,
): Promise<ResultOfGetBocDepth>;

function get_boc_depth_sync(
    params: ParamsOfGetBocDepth,
): ResultOfGetBocDepth;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64 or BOC handle

#### Result

* `depth`: *number* – BOC root cell depth

### get\_code\_from\_tvc

Extracts code from TVC contract image

```ts
type ParamsOfGetCodeFromTvc = {
    tvc: string
}

type ResultOfGetCodeFromTvc = {
    code: string
}

function get_code_from_tvc(
    params: ParamsOfGetCodeFromTvc,
): Promise<ResultOfGetCodeFromTvc>;

function get_code_from_tvc_sync(
    params: ParamsOfGetCodeFromTvc,
): ResultOfGetCodeFromTvc;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `tvc`: *string* – Contract TVC image or image BOC handle

#### Result

* `code`: *string* – Contract code encoded as base64

### cache\_get

Get BOC from cache

```ts
type ParamsOfBocCacheGet = {
    boc_ref: string
}

type ResultOfBocCacheGet = {
    boc?: string
}

function cache_get(
    params: ParamsOfBocCacheGet,
): Promise<ResultOfBocCacheGet>;

function cache_get_sync(
    params: ParamsOfBocCacheGet,
): ResultOfBocCacheGet;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc_ref`: *string* – Reference to the cached BOC

#### Result

* `boc`?: *string* – BOC encoded as base64.

### cache\_set

Save BOC into cache or increase pin counter for existing pinned BOC

```ts
type ParamsOfBocCacheSet = {
    boc: string,
    cache_type: BocCacheType
}

type ResultOfBocCacheSet = {
    boc_ref: string
}

function cache_set(
    params: ParamsOfBocCacheSet,
): Promise<ResultOfBocCacheSet>;

function cache_set_sync(
    params: ParamsOfBocCacheSet,
): ResultOfBocCacheSet;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `boc`: *string* – BOC encoded as base64 or BOC reference
* `cache_type`: [*BocCacheType*](#boccachetype) – Cache type

#### Result

* `boc_ref`: *string* – Reference to the cached BOC

### cache\_unpin

Unpin BOCs with specified pin defined in the `cache_set`. Decrease pin reference counter for BOCs with specified pin defined in the `cache_set`. BOCs which have only 1 pin and its reference counter become 0 will be removed from cache

```ts
type ParamsOfBocCacheUnpin = {
    pin: string,
    boc_ref?: string
}

function cache_unpin(
    params: ParamsOfBocCacheUnpin,
): Promise<void>;

function cache_unpin_sync(
    params: ParamsOfBocCacheUnpin,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `pin`: *string* – Pinned name
* `boc_ref`?: *string* – Reference to the cached BOC.\
  If it is provided then only referenced BOC is unpinned

### encode\_boc

Encodes bag of cells (BOC) with builder operations. This method provides the same functionality as Solidity TvmBuilder. Resulting BOC of this method can be passed into Solidity and C++ contracts as TvmCell type.

```ts
type ParamsOfEncodeBoc = {
    builder: BuilderOp[],
    boc_cache?: BocCacheType
}

type ResultOfEncodeBoc = {
    boc: string
}

function encode_boc(
    params: ParamsOfEncodeBoc,
): Promise<ResultOfEncodeBoc>;

function encode_boc_sync(
    params: ParamsOfEncodeBoc,
): ResultOfEncodeBoc;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `builder`: [*BuilderOp*](#builderop)*\[]* – Cell builder operations.
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

#### Result

* `boc`: *string* – Encoded cell BOC or BOC cache key.

### get\_code\_salt

Returns the contract code's salt if it is present.

```ts
type ParamsOfGetCodeSalt = {
    code: string,
    boc_cache?: BocCacheType
}

type ResultOfGetCodeSalt = {
    salt?: string
}

function get_code_salt(
    params: ParamsOfGetCodeSalt,
): Promise<ResultOfGetCodeSalt>;

function get_code_salt_sync(
    params: ParamsOfGetCodeSalt,
): ResultOfGetCodeSalt;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `code`: *string* – Contract code BOC encoded as base64 or code BOC handle
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

#### Result

* `salt`?: *string* – Contract code salt if present.\
  BOC encoded as base64 or BOC handle

### set\_code\_salt

Sets new salt to contract code.

Returns the new contract code with salt.

```ts
type ParamsOfSetCodeSalt = {
    code: string,
    salt: string,
    boc_cache?: BocCacheType
}

type ResultOfSetCodeSalt = {
    code: string
}

function set_code_salt(
    params: ParamsOfSetCodeSalt,
): Promise<ResultOfSetCodeSalt>;

function set_code_salt_sync(
    params: ParamsOfSetCodeSalt,
): ResultOfSetCodeSalt;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `code`: *string* – Contract code BOC encoded as base64 or code BOC handle
* `salt`: *string* – Code salt to set.\
  BOC encoded as base64 or BOC handle
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

#### Result

* `code`: *string* – Contract code with salt set.\
  BOC encoded as base64 or BOC handle

### decode\_state\_init

Decodes contract's initial state into code, data, libraries and special options.

```ts
type ParamsOfDecodeStateInit = {
    state_init: string,
    boc_cache?: BocCacheType
}

type ResultOfDecodeStateInit = {
    code?: string,
    code_hash?: string,
    code_depth?: number,
    data?: string,
    data_hash?: string,
    data_depth?: number,
    library?: string,
    tick?: boolean,
    tock?: boolean,
    split_depth?: number,
    compiler_version?: string
}

function decode_state_init(
    params: ParamsOfDecodeStateInit,
): Promise<ResultOfDecodeStateInit>;

function decode_state_init_sync(
    params: ParamsOfDecodeStateInit,
): ResultOfDecodeStateInit;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `state_init`: *string* – Contract StateInit image BOC encoded as base64 or BOC handle
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

#### Result

* `code`?: *string* – Contract code BOC encoded as base64 or BOC handle
* `code_hash`?: *string* – Contract code hash
* `code_depth`?: *number* – Contract code depth
* `data`?: *string* – Contract data BOC encoded as base64 or BOC handle
* `data_hash`?: *string* – Contract data hash
* `data_depth`?: *number* – Contract data depth
* `library`?: *string* – Contract library BOC encoded as base64 or BOC handle
* `tick`?: *boolean* – `special.tick` field.\
  Specifies the contract ability to handle tick transactions
* `tock`?: *boolean* – `special.tock` field.\
  Specifies the contract ability to handle tock transactions
* `split_depth`?: *number* – Is present and non-zero only in instances of large smart contracts
* `compiler_version`?: *string* – Compiler version, for example 'sol 0.49.0'

### encode\_state\_init

Encodes initial contract state from code, data, libraries ans special options (see input params)

```ts
type ParamsOfEncodeStateInit = {
    code?: string,
    data?: string,
    library?: string,
    tick?: boolean,
    tock?: boolean,
    split_depth?: number,
    boc_cache?: BocCacheType
}

type ResultOfEncodeStateInit = {
    state_init: string
}

function encode_state_init(
    params: ParamsOfEncodeStateInit,
): Promise<ResultOfEncodeStateInit>;

function encode_state_init_sync(
    params: ParamsOfEncodeStateInit,
): ResultOfEncodeStateInit;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `code`?: *string* – Contract code BOC encoded as base64 or BOC handle
* `data`?: *string* – Contract data BOC encoded as base64 or BOC handle
* `library`?: *string* – Contract library BOC encoded as base64 or BOC handle
* `tick`?: *boolean* – `special.tick` field.\
  Specifies the contract ability to handle tick transactions
* `tock`?: *boolean* – `special.tock` field.\
  Specifies the contract ability to handle tock transactions
* `split_depth`?: *number* – Is present and non-zero only in instances of large smart contracts
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

#### Result

* `state_init`: *string* – Contract StateInit image BOC encoded as base64 or BOC handle of boc\_cache parameter was specified

### encode\_external\_in\_message

Encodes a message

Allows to encode any external inbound message.

```ts
type ParamsOfEncodeExternalInMessage = {
    src?: string,
    dst: string,
    init?: string,
    body?: string,
    boc_cache?: BocCacheType
}

type ResultOfEncodeExternalInMessage = {
    message: string,
    message_id: string
}

function encode_external_in_message(
    params: ParamsOfEncodeExternalInMessage,
): Promise<ResultOfEncodeExternalInMessage>;

function encode_external_in_message_sync(
    params: ParamsOfEncodeExternalInMessage,
): ResultOfEncodeExternalInMessage;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `src`?: *string* – Source address.
* `dst`: *string* – Destination address.
* `init`?: *string* – Bag of cells with state init (used in deploy messages).
* `body`?: *string* – Bag of cells with the message body encoded as base64.
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided

#### Result

* `message`: *string* – Message BOC encoded with `base64`.
* `message_id`: *string* – Message id.

### get\_compiler\_version

Returns the compiler version used to compile the code.

```ts
type ParamsOfGetCompilerVersion = {
    code: string
}

type ResultOfGetCompilerVersion = {
    version?: string
}

function get_compiler_version(
    params: ParamsOfGetCompilerVersion,
): Promise<ResultOfGetCompilerVersion>;

function get_compiler_version_sync(
    params: ParamsOfGetCompilerVersion,
): ResultOfGetCompilerVersion;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `code`: *string* – Contract code BOC encoded as base64 or code BOC handle

#### Result

* `version`?: *string* – Compiler version, for example 'sol 0.49.0'

## Types

### BocCacheTypePinnedVariant

Pin the BOC with `pin` name.

Such BOC will not be removed from cache until it is unpinned BOCs can have several pins and each of the pins has reference counter indicating how many times the BOC was pinned with the pin. BOC is removed from cache after all references for all pins are unpinned with `cache_unpin` function calls.

```ts
type BocCacheTypePinnedVariant = {
    pin: string
}
```

* `pin`: *string*

### BocCacheTypeUnpinnedVariant

BOC is placed into a common BOC pool with limited size regulated by LRU (least recently used) cache lifecycle.

BOC resides there until it is replaced with other BOCs if it is not used

```ts
type BocCacheTypeUnpinnedVariant = {

}
```

### BocCacheType

```ts
type BocCacheType = ({
    type: 'Pinned'
} & BocCacheTypePinnedVariant) | ({
    type: 'Unpinned'
} & BocCacheTypeUnpinnedVariant)
```

Depends on value of the `type` field.

When *type* is *'Pinned'*

Pin the BOC with `pin` name.

Such BOC will not be removed from cache until it is unpinned BOCs can have several pins and each of the pins has reference counter indicating how many times the BOC was pinned with the pin. BOC is removed from cache after all references for all pins are unpinned with `cache_unpin` function calls.

* `pin`: *string*

When *type* is *'Unpinned'*

BOC is placed into a common BOC pool with limited size regulated by LRU (least recently used) cache lifecycle.

BOC resides there until it is replaced with other BOCs if it is not used

Variant constructors:

```ts
function bocCacheTypePinned(pin: string): BocCacheType;
function bocCacheTypeUnpinned(): BocCacheType;
```

### BuilderOpIntegerVariant

Append integer to cell data.

```ts
type BuilderOpIntegerVariant = {
    size: number,
    value: any
}
```

* `size`: *number* – Bit size of the value.
* `value`: *any* – Value: - `Number` containing integer number.\
  e.g. `123`, `-123`. - Decimal string. e.g. `"123"`, `"-123"`.\
  \- `0x` prefixed hexadecimal string.\
  e.g `0x123`, `0X123`, `-0x123`.

### BuilderOpBitStringVariant

Append bit string to cell data.

```ts
type BuilderOpBitStringVariant = {
    value: string
}
```

* `value`: *string* – Bit string content using bitstring notation. See `TON VM specification` 1.0.\
  Contains hexadecimal string representation:\
  \- Can end with `_` tag.\
  \- Can be prefixed with `x` or `X`.\
  \- Can be prefixed with `x{` or `X{` and ended with `}`.\
  \
  Contains binary string represented as a sequence\
  of `0` and `1` prefixed with `n` or `N`.\
  \
  Examples:\
  `1AB`, `x1ab`, `X1AB`, `x{1abc}`, `X{1ABC}`\
  `2D9_`, `x2D9_`, `X2D9_`, `x{2D9_}`, `X{2D9_}`\
  `n00101101100`, `N00101101100`

### BuilderOpCellVariant

Append ref to nested cells.

```ts
type BuilderOpCellVariant = {
    builder: BuilderOp[]
}
```

* `builder`: [*BuilderOp*](#builderop)*\[]* – Nested cell builder.

### BuilderOpCellBocVariant

Append ref to nested cell.

```ts
type BuilderOpCellBocVariant = {
    boc: string
}
```

* `boc`: *string* – Nested cell BOC encoded with `base64` or BOC cache key.

### BuilderOpAddressVariant

Address.

```ts
type BuilderOpAddressVariant = {
    address: string
}
```

* `address`: *string* – Address in a common `workchain:account` or base64 format.

### BuilderOp

Cell builder operation.

```ts
type BuilderOp = ({
    type: 'Integer'
} & BuilderOpIntegerVariant) | ({
    type: 'BitString'
} & BuilderOpBitStringVariant) | ({
    type: 'Cell'
} & BuilderOpCellVariant) | ({
    type: 'CellBoc'
} & BuilderOpCellBocVariant) | ({
    type: 'Address'
} & BuilderOpAddressVariant)
```

Depends on value of the `type` field.

When *type* is *'Integer'*

Append integer to cell data.

* `size`: *number* – Bit size of the value.
* `value`: *any* – Value: - `Number` containing integer number.\
  e.g. `123`, `-123`. - Decimal string. e.g. `"123"`, `"-123"`.\
  \- `0x` prefixed hexadecimal string.\
  e.g `0x123`, `0X123`, `-0x123`.

When *type* is *'BitString'*

Append bit string to cell data.

* `value`: *string* – Bit string content using bitstring notation. See `TON VM specification` 1.0.\
  Contains hexadecimal string representation:\
  \- Can end with `_` tag.\
  \- Can be prefixed with `x` or `X`.\
  \- Can be prefixed with `x{` or `X{` and ended with `}`.\
  \
  Contains binary string represented as a sequence\
  of `0` and `1` prefixed with `n` or `N`.\
  \
  Examples:\
  `1AB`, `x1ab`, `X1AB`, `x{1abc}`, `X{1ABC}`\
  `2D9_`, `x2D9_`, `X2D9_`, `x{2D9_}`, `X{2D9_}`\
  `n00101101100`, `N00101101100`

When *type* is *'Cell'*

Append ref to nested cells.

* `builder`: [*BuilderOp*](#builderop)*\[]* – Nested cell builder.

When *type* is *'CellBoc'*

Append ref to nested cell.

* `boc`: *string* – Nested cell BOC encoded with `base64` or BOC cache key.

When *type* is *'Address'*

Address.

* `address`: *string* – Address in a common `workchain:account` or base64 format.

Variant constructors:

```ts
function builderOpInteger(size: number, value: any): BuilderOp;
function builderOpBitString(value: string): BuilderOp;
function builderOpCell(builder: BuilderOp[]): BuilderOp;
function builderOpCellBoc(boc: string): BuilderOp;
function builderOpAddress(address: string): BuilderOp;
```

### TvcV1Variant

```ts
type TvcV1Variant = {
    value: TvcV1
}
```

* `value`: [*TvcV1*](#tvcv1)

### Tvc

```ts
type Tvc = ({
    type: 'V1'
} & TvcV1Variant)
```

Depends on value of the `type` field.

When *type* is *'V1'*

* `value`: [*TvcV1*](#tvcv1)

Variant constructors:

```ts
function tvcV1(value: TvcV1): Tvc;
```

### TvcV1

```ts
type TvcV1 = {
    code?: string,
    description?: string
}
```

* `code`?: *string*
* `description`?: *string*

### BocErrorCode

```ts
enum BocErrorCode {
    InvalidBoc = 201,
    SerializationError = 202,
    InappropriateBlock = 203,
    MissingSourceBoc = 204,
    InsufficientCacheSize = 205,
    BocRefNotFound = 206,
    InvalidBocRef = 207
}
```

One of the following value:

* `InvalidBoc = 201`
* `SerializationError = 202`
* `InappropriateBlock = 203`
* `MissingSourceBoc = 204`
* `InsufficientCacheSize = 205`
* `BocRefNotFound = 206`
* `InvalidBocRef = 207`

### ParamsOfDecodeTvc

```ts
type ParamsOfDecodeTvc = {
    tvc: string
}
```

* `tvc`: *string* – Contract TVC BOC encoded as base64 or BOC handle

### ResultOfDecodeTvc

```ts
type ResultOfDecodeTvc = {
    tvc: Tvc
}
```

* `tvc`: [*Tvc*](#tvc) – Decoded TVC

### ParamsOfParse

```ts
type ParamsOfParse = {
    boc: string
}
```

* `boc`: *string* – BOC encoded as base64

### ResultOfParse

```ts
type ResultOfParse = {
    parsed: any
}
```

* `parsed`: *any* – JSON containing parsed BOC

### ParamsOfParseShardstate

```ts
type ParamsOfParseShardstate = {
    boc: string,
    id: string,
    workchain_id: number
}
```

* `boc`: *string* – BOC encoded as base64
* `id`: *string* – Shardstate identifier
* `workchain_id`: *number* – Workchain shardstate belongs to

### ParamsOfGetBlockchainConfig

```ts
type ParamsOfGetBlockchainConfig = {
    block_boc: string
}
```

* `block_boc`: *string* – Key block BOC or zerostate BOC encoded as base64

### ResultOfGetBlockchainConfig

```ts
type ResultOfGetBlockchainConfig = {
    config_boc: string
}
```

* `config_boc`: *string* – Blockchain config BOC encoded as base64

### ParamsOfGetBocHash

```ts
type ParamsOfGetBocHash = {
    boc: string
}
```

* `boc`: *string* – BOC encoded as base64 or BOC handle

### ResultOfGetBocHash

```ts
type ResultOfGetBocHash = {
    hash: string
}
```

* `hash`: *string* – BOC root hash encoded with hex

### ParamsOfGetBocDepth

```ts
type ParamsOfGetBocDepth = {
    boc: string
}
```

* `boc`: *string* – BOC encoded as base64 or BOC handle

### ResultOfGetBocDepth

```ts
type ResultOfGetBocDepth = {
    depth: number
}
```

* `depth`: *number* – BOC root cell depth

### ParamsOfGetCodeFromTvc

```ts
type ParamsOfGetCodeFromTvc = {
    tvc: string
}
```

* `tvc`: *string* – Contract TVC image or image BOC handle

### ResultOfGetCodeFromTvc

```ts
type ResultOfGetCodeFromTvc = {
    code: string
}
```

* `code`: *string* – Contract code encoded as base64

### ParamsOfBocCacheGet

```ts
type ParamsOfBocCacheGet = {
    boc_ref: string
}
```

* `boc_ref`: *string* – Reference to the cached BOC

### ResultOfBocCacheGet

```ts
type ResultOfBocCacheGet = {
    boc?: string
}
```

* `boc`?: *string* – BOC encoded as base64.

### ParamsOfBocCacheSet

```ts
type ParamsOfBocCacheSet = {
    boc: string,
    cache_type: BocCacheType
}
```

* `boc`: *string* – BOC encoded as base64 or BOC reference
* `cache_type`: [*BocCacheType*](#boccachetype) – Cache type

### ResultOfBocCacheSet

```ts
type ResultOfBocCacheSet = {
    boc_ref: string
}
```

* `boc_ref`: *string* – Reference to the cached BOC

### ParamsOfBocCacheUnpin

```ts
type ParamsOfBocCacheUnpin = {
    pin: string,
    boc_ref?: string
}
```

* `pin`: *string* – Pinned name
* `boc_ref`?: *string* – Reference to the cached BOC.\
  If it is provided then only referenced BOC is unpinned

### ParamsOfEncodeBoc

```ts
type ParamsOfEncodeBoc = {
    builder: BuilderOp[],
    boc_cache?: BocCacheType
}
```

* `builder`: [*BuilderOp*](#builderop)*\[]* – Cell builder operations.
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

### ResultOfEncodeBoc

```ts
type ResultOfEncodeBoc = {
    boc: string
}
```

* `boc`: *string* – Encoded cell BOC or BOC cache key.

### ParamsOfGetCodeSalt

```ts
type ParamsOfGetCodeSalt = {
    code: string,
    boc_cache?: BocCacheType
}
```

* `code`: *string* – Contract code BOC encoded as base64 or code BOC handle
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

### ResultOfGetCodeSalt

```ts
type ResultOfGetCodeSalt = {
    salt?: string
}
```

* `salt`?: *string* – Contract code salt if present.\
  BOC encoded as base64 or BOC handle

### ParamsOfSetCodeSalt

```ts
type ParamsOfSetCodeSalt = {
    code: string,
    salt: string,
    boc_cache?: BocCacheType
}
```

* `code`: *string* – Contract code BOC encoded as base64 or code BOC handle
* `salt`: *string* – Code salt to set.\
  BOC encoded as base64 or BOC handle
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

### ResultOfSetCodeSalt

```ts
type ResultOfSetCodeSalt = {
    code: string
}
```

* `code`: *string* – Contract code with salt set.\
  BOC encoded as base64 or BOC handle

### ParamsOfDecodeStateInit

```ts
type ParamsOfDecodeStateInit = {
    state_init: string,
    boc_cache?: BocCacheType
}
```

* `state_init`: *string* – Contract StateInit image BOC encoded as base64 or BOC handle
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

### ResultOfDecodeStateInit

```ts
type ResultOfDecodeStateInit = {
    code?: string,
    code_hash?: string,
    code_depth?: number,
    data?: string,
    data_hash?: string,
    data_depth?: number,
    library?: string,
    tick?: boolean,
    tock?: boolean,
    split_depth?: number,
    compiler_version?: string
}
```

* `code`?: *string* – Contract code BOC encoded as base64 or BOC handle
* `code_hash`?: *string* – Contract code hash
* `code_depth`?: *number* – Contract code depth
* `data`?: *string* – Contract data BOC encoded as base64 or BOC handle
* `data_hash`?: *string* – Contract data hash
* `data_depth`?: *number* – Contract data depth
* `library`?: *string* – Contract library BOC encoded as base64 or BOC handle
* `tick`?: *boolean* – `special.tick` field.\
  Specifies the contract ability to handle tick transactions
* `tock`?: *boolean* – `special.tock` field.\
  Specifies the contract ability to handle tock transactions
* `split_depth`?: *number* – Is present and non-zero only in instances of large smart contracts
* `compiler_version`?: *string* – Compiler version, for example 'sol 0.49.0'

### ParamsOfEncodeStateInit

```ts
type ParamsOfEncodeStateInit = {
    code?: string,
    data?: string,
    library?: string,
    tick?: boolean,
    tock?: boolean,
    split_depth?: number,
    boc_cache?: BocCacheType
}
```

* `code`?: *string* – Contract code BOC encoded as base64 or BOC handle
* `data`?: *string* – Contract data BOC encoded as base64 or BOC handle
* `library`?: *string* – Contract library BOC encoded as base64 or BOC handle
* `tick`?: *boolean* – `special.tick` field.\
  Specifies the contract ability to handle tick transactions
* `tock`?: *boolean* – `special.tock` field.\
  Specifies the contract ability to handle tock transactions
* `split_depth`?: *number* – Is present and non-zero only in instances of large smart contracts
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result. The BOC itself returned if no cache type provided.

### ResultOfEncodeStateInit

```ts
type ResultOfEncodeStateInit = {
    state_init: string
}
```

* `state_init`: *string* – Contract StateInit image BOC encoded as base64 or BOC handle of boc\_cache parameter was specified

### ParamsOfEncodeExternalInMessage

```ts
type ParamsOfEncodeExternalInMessage = {
    src?: string,
    dst: string,
    init?: string,
    body?: string,
    boc_cache?: BocCacheType
}
```

* `src`?: *string* – Source address.
* `dst`: *string* – Destination address.
* `init`?: *string* – Bag of cells with state init (used in deploy messages).
* `body`?: *string* – Bag of cells with the message body encoded as base64.
* `boc_cache`?: [*BocCacheType*](#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided

### ResultOfEncodeExternalInMessage

```ts
type ResultOfEncodeExternalInMessage = {
    message: string,
    message_id: string
}
```

* `message`: *string* – Message BOC encoded with `base64`.
* `message_id`: *string* – Message id.

### ParamsOfGetCompilerVersion

```ts
type ParamsOfGetCompilerVersion = {
    code: string
}
```

* `code`: *string* – Contract code BOC encoded as base64 or code BOC handle

### ResultOfGetCompilerVersion

```ts
type ResultOfGetCompilerVersion = {
    version?: string
}
```

* `version`?: *string* – Compiler version, for example 'sol 0.49.0'


# Module client

## Module client

Provides information about library.

### Functions

[get\_api\_reference](#get_api_reference) – Returns Core Library API reference

[version](#version) – Returns Core Library version

[config](#config) – Returns Core Library API reference

[build\_info](#build_info) – Returns detailed information about this build.

[resolve\_app\_request](#resolve_app_request) – Resolves application request processing result

### Types

[ClientErrorCode](#clienterrorcode)

[ClientError](#clienterror)

[ClientConfig](#clientconfig)

[NetworkConfig](#networkconfig)

[BindingConfig](#bindingconfig)

[NetworkQueriesProtocol](#networkqueriesprotocol) – Network protocol used to perform GraphQL queries.

[CryptoConfig](#cryptoconfig) – Crypto config.

[AbiConfig](#abiconfig)

[BocConfig](#bocconfig)

[ProofsConfig](#proofsconfig)

[BuildInfoDependency](#buildinfodependency)

[ParamsOfAppRequest](#paramsofapprequest)

[AppRequestResultErrorVariant](#apprequestresulterrorvariant) – Error occurred during request processing

[AppRequestResultOkVariant](#apprequestresultokvariant) – Request processed successfully

[AppRequestResult](#apprequestresult)

[ResultOfGetApiReference](#resultofgetapireference)

[ResultOfVersion](#resultofversion)

[ResultOfBuildInfo](#resultofbuildinfo)

[ParamsOfResolveAppRequest](#paramsofresolveapprequest)

## Functions

### get\_api\_reference

Returns Core Library API reference

```ts
type ResultOfGetApiReference = {
    api: any
}

function get_api_reference(): Promise<ResultOfGetApiReference>;

function get_api_reference_sync(): ResultOfGetApiReference;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `api`: *API*

### version

Returns Core Library version

```ts
type ResultOfVersion = {
    version: string
}

function version(): Promise<ResultOfVersion>;

function version_sync(): ResultOfVersion;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `version`: *string* – Core Library version

### config

Returns Core Library API reference

```ts
type ClientConfig = {
    binding?: BindingConfig,
    network?: NetworkConfig,
    crypto?: CryptoConfig,
    abi?: AbiConfig,
    boc?: BocConfig,
    proofs?: ProofsConfig,
    local_storage_path?: string
}

function config(): Promise<ClientConfig>;

function config_sync(): ClientConfig;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `binding`?: [*BindingConfig*](#bindingconfig)
* `network`?: [*NetworkConfig*](#networkconfig)
* `crypto`?: [*CryptoConfig*](#cryptoconfig)
* `abi`?: [*AbiConfig*](#abiconfig)
* `boc`?: [*BocConfig*](#bocconfig)
* `proofs`?: [*ProofsConfig*](#proofsconfig)
* `local_storage_path`?: *string* – For file based storage is a folder name where SDK will store its data. For browser based is a browser async storage key prefix. Default (recommended) value is "\~/.tonclient" for native environments and ".tonclient" for web-browser.

### build\_info

Returns detailed information about this build.

```ts
type ResultOfBuildInfo = {
    build_number: number,
    dependencies: BuildInfoDependency[]
}

function build_info(): Promise<ResultOfBuildInfo>;

function build_info_sync(): ResultOfBuildInfo;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `build_number`: *number* – Build number assigned to this build by the CI.
* `dependencies`: [*BuildInfoDependency*](#buildinfodependency)*\[]* – Fingerprint of the most important dependencies.

### resolve\_app\_request

Resolves application request processing result

```ts
type ParamsOfResolveAppRequest = {
    app_request_id: number,
    result: AppRequestResult
}

function resolve_app_request(
    params: ParamsOfResolveAppRequest,
): Promise<void>;

function resolve_app_request_sync(
    params: ParamsOfResolveAppRequest,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `app_request_id`: *number* – Request ID received from SDK
* `result`: [*AppRequestResult*](#apprequestresult) – Result of request processing

## Types

### ClientErrorCode

```ts
enum ClientErrorCode {
    NotImplemented = 1,
    InvalidHex = 2,
    InvalidBase64 = 3,
    InvalidAddress = 4,
    CallbackParamsCantBeConvertedToJson = 5,
    WebsocketConnectError = 6,
    WebsocketReceiveError = 7,
    WebsocketSendError = 8,
    HttpClientCreateError = 9,
    HttpRequestCreateError = 10,
    HttpRequestSendError = 11,
    HttpRequestParseError = 12,
    CallbackNotRegistered = 13,
    NetModuleNotInit = 14,
    InvalidConfig = 15,
    CannotCreateRuntime = 16,
    InvalidContextHandle = 17,
    CannotSerializeResult = 18,
    CannotSerializeError = 19,
    CannotConvertJsValueToJson = 20,
    CannotReceiveSpawnedResult = 21,
    SetTimerError = 22,
    InvalidParams = 23,
    ContractsAddressConversionFailed = 24,
    UnknownFunction = 25,
    AppRequestError = 26,
    NoSuchRequest = 27,
    CanNotSendRequestResult = 28,
    CanNotReceiveRequestResult = 29,
    CanNotParseRequestResult = 30,
    UnexpectedCallbackResponse = 31,
    CanNotParseNumber = 32,
    InternalError = 33,
    InvalidHandle = 34,
    LocalStorageError = 35,
    InvalidData = 36
}
```

One of the following value:

* `NotImplemented = 1`
* `InvalidHex = 2`
* `InvalidBase64 = 3`
* `InvalidAddress = 4`
* `CallbackParamsCantBeConvertedToJson = 5`
* `WebsocketConnectError = 6`
* `WebsocketReceiveError = 7`
* `WebsocketSendError = 8`
* `HttpClientCreateError = 9`
* `HttpRequestCreateError = 10`
* `HttpRequestSendError = 11`
* `HttpRequestParseError = 12`
* `CallbackNotRegistered = 13`
* `NetModuleNotInit = 14`
* `InvalidConfig = 15`
* `CannotCreateRuntime = 16`
* `InvalidContextHandle = 17`
* `CannotSerializeResult = 18`
* `CannotSerializeError = 19`
* `CannotConvertJsValueToJson = 20`
* `CannotReceiveSpawnedResult = 21`
* `SetTimerError = 22`
* `InvalidParams = 23`
* `ContractsAddressConversionFailed = 24`
* `UnknownFunction = 25`
* `AppRequestError = 26`
* `NoSuchRequest = 27`
* `CanNotSendRequestResult = 28`
* `CanNotReceiveRequestResult = 29`
* `CanNotParseRequestResult = 30`
* `UnexpectedCallbackResponse = 31`
* `CanNotParseNumber = 32`
* `InternalError = 33`
* `InvalidHandle = 34`
* `LocalStorageError = 35`
* `InvalidData = 36`

### ClientError

```ts
type ClientError = {
    code: number,
    message: string,
    data: any
}
```

* `code`: *number*
* `message`: *string*
* `data`: *any*

### ClientConfig

```ts
type ClientConfig = {
    binding?: BindingConfig,
    network?: NetworkConfig,
    crypto?: CryptoConfig,
    abi?: AbiConfig,
    boc?: BocConfig,
    proofs?: ProofsConfig,
    local_storage_path?: string
}
```

* `binding`?: [*BindingConfig*](#bindingconfig)
* `network`?: [*NetworkConfig*](#networkconfig)
* `crypto`?: [*CryptoConfig*](#cryptoconfig)
* `abi`?: [*AbiConfig*](#abiconfig)
* `boc`?: [*BocConfig*](#bocconfig)
* `proofs`?: [*ProofsConfig*](#proofsconfig)
* `local_storage_path`?: *string* – For file based storage is a folder name where SDK will store its data. For browser based is a browser async storage key prefix. Default (recommended) value is "\~/.tonclient" for native environments and ".tonclient" for web-browser.

### NetworkConfig

```ts
type NetworkConfig = {
    server_address?: string,
    endpoints?: string[],
    network_retries_count?: number,
    max_reconnect_timeout?: number,
    reconnect_timeout?: number,
    message_retries_count?: number,
    message_processing_timeout?: number,
    wait_for_timeout?: number,
    out_of_sync_threshold?: number,
    sending_endpoint_count?: number,
    latency_detection_interval?: number,
    max_latency?: number,
    query_timeout?: number,
    queries_protocol?: NetworkQueriesProtocol,
    first_remp_status_timeout?: number,
    next_remp_status_timeout?: number,
    signature_id?: number,
    access_key?: string
}
```

* `server_address`?: *string* – **This field is deprecated, but left for backward-compatibility.** Evernode endpoint.
* `endpoints`?: *string\[]* – List of Evernode endpoints.\
  Any correct URL format can be specified, including IP addresses. This parameter is prevailing over `server_address`.\
  Check the full list of [supported network endpoints](https://docs.evercloud.dev/products/evercloud/networks-endpoints).
* `network_retries_count`?: *number* – Deprecated.\
  You must use `network.max_reconnect_timeout` that allows to specify maximum network resolving timeout.
* `max_reconnect_timeout`?: *number* – Maximum time for sequential reconnections.\
  Must be specified in milliseconds. Default is 120000 (2 min).
* `reconnect_timeout`?: *number* – Deprecated
* `message_retries_count`?: *number* – The number of automatic message processing retries that SDK performs in case of `Message Expired (507)` error - but only for those messages which local emulation was successful or failed with replay protection error.\
  Default is 5.
* `message_processing_timeout`?: *number* – Timeout that is used to process message delivery for the contracts which ABI does not include "expire" header. If the message is not delivered within the specified timeout the appropriate error occurs.\
  Must be specified in milliseconds. Default is 40000 (40 sec).
* `wait_for_timeout`?: *number* – Maximum timeout that is used for query response.\
  Must be specified in milliseconds. Default is 40000 (40 sec).
* `out_of_sync_threshold`?: *number* – **DEPRECATED**: This parameter was deprecated.
* `sending_endpoint_count`?: *number* – Maximum number of randomly chosen endpoints the library uses to broadcast a message.\
  Default is 1.
* `latency_detection_interval`?: *number* – Frequency of sync latency detection.\
  Library periodically checks the current endpoint for blockchain data synchronization latency.\
  If the latency (time-lag) is less then `NetworkConfig.max_latency`\
  then library selects another endpoint.\
  \
  Must be specified in milliseconds. Default is 60000 (1 min).
* `max_latency`?: *number* – Maximum value for the endpoint's blockchain data synchronization latency (time-lag). Library periodically checks the current endpoint for blockchain data synchronization latency. If the latency (time-lag) is less then `NetworkConfig.max_latency` then library selects another endpoint.\
  Must be specified in milliseconds. Default is 60000 (1 min).
* `query_timeout`?: *number* – Default timeout for http requests.\
  Is is used when no timeout specified for the request to limit the answer waiting time. If no answer received during the timeout requests ends with\
  error.\
  \
  Must be specified in milliseconds. Default is 60000 (1 min).
* `queries_protocol`?: [*NetworkQueriesProtocol*](#networkqueriesprotocol) – Queries protocol.\
  `HTTP` or `WS`.\
  Default is `HTTP`.
* `first_remp_status_timeout`?: *number* – UNSTABLE.\
  First REMP status awaiting timeout. If no status received during the timeout than fallback transaction scenario is activated.\
  \
  Must be specified in milliseconds. Default is 1 (1 ms) in order to start fallback scenario\
  together with REMP statuses processing while REMP is not properly tuned yet.
* `next_remp_status_timeout`?: *number* – UNSTABLE.\
  Subsequent REMP status awaiting timeout. If no status received during the timeout than fallback transaction scenario is activated.\
  \
  Must be specified in milliseconds. Default is 5000 (5 sec).
* `signature_id`?: *number* – Network signature ID which is used by VM in signature verifying instructions if capability `CapSignatureWithId` is enabled in blockchain configuration parameters.\
  This parameter should be set to `global_id` field from any blockchain block if network can\
  not be reachable at the moment of message encoding and the message is aimed to be sent into\
  network with `CapSignatureWithId` enabled. Otherwise signature ID is detected automatically\
  inside message encoding functions
* `access_key`?: *string* – Access key to GraphQL API (Project secret)

### BindingConfig

```ts
type BindingConfig = {
    library?: string,
    version?: string
}
```

* `library`?: *string*
* `version`?: *string*

### NetworkQueriesProtocol

Network protocol used to perform GraphQL queries.

```ts
enum NetworkQueriesProtocol {
    HTTP = "HTTP",
    WS = "WS"
}
```

One of the following value:

* `HTTP = "HTTP"` – Each GraphQL query uses separate HTTP request.
* `WS = "WS"` – All GraphQL queries will be served using single web socket connection. SDK is tested to reliably handle 5000 parallel network requests (sending and processing messages, quering and awaiting blockchain data)

### CryptoConfig

Crypto config.

```ts
type CryptoConfig = {
    mnemonic_dictionary?: MnemonicDictionary,
    mnemonic_word_count?: number,
    hdkey_derivation_path?: string
}
```

* `mnemonic_dictionary`?: [*MnemonicDictionary*](/ever-sdk/reference/types-and-methods/mod_crypto#mnemonicdictionary) – Mnemonic dictionary that will be used by default in crypto functions. If not specified, `English` dictionary will be used.
* `mnemonic_word_count`?: *number* – Mnemonic word count that will be used by default in crypto functions. If not specified the default value will be 12.
* `hdkey_derivation_path`?: *string* – Derivation path that will be used by default in crypto functions. If not specified `m/44'/396'/0'/0/0` will be used.

### AbiConfig

```ts
type AbiConfig = {
    workchain?: number,
    message_expiration_timeout?: number,
    message_expiration_timeout_grow_factor?: number
}
```

* `workchain`?: *number* – Workchain id that is used by default in DeploySet
* `message_expiration_timeout`?: *number* – Message lifetime for contracts which ABI includes "expire" header.\
  Must be specified in milliseconds. Default is 40000 (40 sec).
* `message_expiration_timeout_grow_factor`?: *number* – Factor that increases the expiration timeout for each retry\
  Default is 1.5

### BocConfig

```ts
type BocConfig = {
    cache_max_size?: number
}
```

* `cache_max_size`?: *number* – Maximum BOC cache size in kilobytes.\
  Default is 10 MB

### ProofsConfig

```ts
type ProofsConfig = {
    cache_in_local_storage?: boolean
}
```

* `cache_in_local_storage`?: *boolean* – Cache proofs in the local storage.\
  Default is `true`. If this value is set to `true`, downloaded proofs and master-chain BOCs are saved into the\
  persistent local storage (e.g. file system for native environments or browser's IndexedDB\
  for the web); otherwise all the data is cached only in memory in current client's context\
  and will be lost after destruction of the client.

### BuildInfoDependency

```ts
type BuildInfoDependency = {
    name: string,
    git_commit: string
}
```

* `name`: *string* – Dependency name.\
  Usually it is a crate name.
* `git_commit`: *string* – Git commit hash of the related repository.

### ParamsOfAppRequest

```ts
type ParamsOfAppRequest = {
    app_request_id: number,
    request_data: any
}
```

* `app_request_id`: *number* – Request ID.\
  Should be used in `resolve_app_request` call
* `request_data`: *any* – Request describing data

### AppRequestResultErrorVariant

Error occurred during request processing

```ts
type AppRequestResultErrorVariant = {
    text: string
}
```

* `text`: *string* – Error description

### AppRequestResultOkVariant

Request processed successfully

```ts
type AppRequestResultOkVariant = {
    result: any
}
```

* `result`: *any* – Request processing result

### AppRequestResult

```ts
type AppRequestResult = ({
    type: 'Error'
} & AppRequestResultErrorVariant) | ({
    type: 'Ok'
} & AppRequestResultOkVariant)
```

Depends on value of the `type` field.

When *type* is *'Error'*

Error occurred during request processing

* `text`: *string* – Error description

When *type* is *'Ok'*

Request processed successfully

* `result`: *any* – Request processing result

Variant constructors:

```ts
function appRequestResultError(text: string): AppRequestResult;
function appRequestResultOk(result: any): AppRequestResult;
```

### ResultOfGetApiReference

```ts
type ResultOfGetApiReference = {
    api: any
}
```

* `api`: *API*

### ResultOfVersion

```ts
type ResultOfVersion = {
    version: string
}
```

* `version`: *string* – Core Library version

### ResultOfBuildInfo

```ts
type ResultOfBuildInfo = {
    build_number: number,
    dependencies: BuildInfoDependency[]
}
```

* `build_number`: *number* – Build number assigned to this build by the CI.
* `dependencies`: [*BuildInfoDependency*](#buildinfodependency)*\[]* – Fingerprint of the most important dependencies.

### ParamsOfResolveAppRequest

```ts
type ParamsOfResolveAppRequest = {
    app_request_id: number,
    result: AppRequestResult
}
```

* `app_request_id`: *number* – Request ID received from SDK
* `result`: [*AppRequestResult*](#apprequestresult) – Result of request processing


# Module crypto

## Module crypto

Crypto functions.

### Functions

[factorize](#factorize) – Integer factorization

[modular\_power](#modular_power) – Modular exponentiation

[ton\_crc16](#ton_crc16) – Calculates CRC16 using TON algorithm.

[generate\_random\_bytes](#generate_random_bytes) – Generates random byte array of the specified length and returns it in `base64` format

[convert\_public\_key\_to\_ton\_safe\_format](#convert_public_key_to_ton_safe_format) – Converts public key to ton safe\_format

[generate\_random\_sign\_keys](#generate_random_sign_keys) – Generates random ed25519 key pair.

[sign](#sign) – Signs a data using the provided keys.

[verify\_signature](#verify_signature) – Verifies signed data using the provided public key. Raises error if verification is failed.

[sha256](#sha256) – Calculates SHA256 hash of the specified data.

[sha512](#sha512) – Calculates SHA512 hash of the specified data.

[scrypt](#scrypt) – Perform `scrypt` encryption

[nacl\_sign\_keypair\_from\_secret\_key](#nacl_sign_keypair_from_secret_key) – Generates a key pair for signing from the secret key

[nacl\_sign](#nacl_sign) – Signs data using the signer's secret key.

[nacl\_sign\_open](#nacl_sign_open) – Verifies the signature and returns the unsigned message

[nacl\_sign\_detached](#nacl_sign_detached) – Signs the message using the secret key and returns a signature.

[nacl\_sign\_detached\_verify](#nacl_sign_detached_verify) – Verifies the signature with public key and `unsigned` data.

[nacl\_box\_keypair](#nacl_box_keypair) – Generates a random NaCl key pair

[nacl\_box\_keypair\_from\_secret\_key](#nacl_box_keypair_from_secret_key) – Generates key pair from a secret key

[nacl\_box](#nacl_box) – Public key authenticated encryption

[nacl\_box\_open](#nacl_box_open) – Decrypt and verify the cipher text using the receivers secret key, the senders public key, and the nonce.

[nacl\_secret\_box](#nacl_secret_box) – Encrypt and authenticate message using nonce and secret key.

[nacl\_secret\_box\_open](#nacl_secret_box_open) – Decrypts and verifies cipher text using `nonce` and secret `key`.

[mnemonic\_words](#mnemonic_words) – Prints the list of words from the specified dictionary

[mnemonic\_from\_random](#mnemonic_from_random) – Generates a random mnemonic

[mnemonic\_from\_entropy](#mnemonic_from_entropy) – Generates mnemonic from pre-generated entropy

[mnemonic\_verify](#mnemonic_verify) – Validates a mnemonic phrase

[mnemonic\_derive\_sign\_keys](#mnemonic_derive_sign_keys) – Derives a key pair for signing from the seed phrase

[hdkey\_xprv\_from\_mnemonic](#hdkey_xprv_from_mnemonic) – Generates an extended master private key that will be the root for all the derived keys

[hdkey\_derive\_from\_xprv](#hdkey_derive_from_xprv) – Returns extended private key derived from the specified extended private key and child index

[hdkey\_derive\_from\_xprv\_path](#hdkey_derive_from_xprv_path) – Derives the extended private key from the specified key and path

[hdkey\_secret\_from\_xprv](#hdkey_secret_from_xprv) – Extracts the private key from the serialized extended private key

[hdkey\_public\_from\_xprv](#hdkey_public_from_xprv) – Extracts the public key from the serialized extended private key

[chacha20](#chacha20) – Performs symmetric `chacha20` encryption.

[create\_crypto\_box](#create_crypto_box) – Creates a Crypto Box instance.

[remove\_crypto\_box](#remove_crypto_box) – Removes Crypto Box. Clears all secret data.

[get\_crypto\_box\_info](#get_crypto_box_info) – Get Crypto Box Info. Used to get `encrypted_secret` that should be used for all the cryptobox initializations except the first one.

[get\_crypto\_box\_seed\_phrase](#get_crypto_box_seed_phrase) – Get Crypto Box Seed Phrase.

[get\_signing\_box\_from\_crypto\_box](#get_signing_box_from_crypto_box) – Get handle of Signing Box derived from Crypto Box.

[get\_encryption\_box\_from\_crypto\_box](#get_encryption_box_from_crypto_box) – Gets Encryption Box from Crypto Box.

[clear\_crypto\_box\_secret\_cache](#clear_crypto_box_secret_cache) – Removes cached secrets (overwrites with zeroes) from all signing and encryption boxes, derived from crypto box.

[register\_signing\_box](#register_signing_box) – Register an application implemented signing box.

[get\_signing\_box](#get_signing_box) – Creates a default signing box implementation.

[signing\_box\_get\_public\_key](#signing_box_get_public_key) – Returns public key of signing key pair.

[signing\_box\_sign](#signing_box_sign) – Returns signed user data.

[remove\_signing\_box](#remove_signing_box) – Removes signing box from SDK.

[register\_encryption\_box](#register_encryption_box) – Register an application implemented encryption box.

[remove\_encryption\_box](#remove_encryption_box) – Removes encryption box from SDK

[encryption\_box\_get\_info](#encryption_box_get_info) – Queries info from the given encryption box

[encryption\_box\_encrypt](#encryption_box_encrypt) – Encrypts data using given encryption box Note.

[encryption\_box\_decrypt](#encryption_box_decrypt) – Decrypts data using given encryption box Note.

[create\_encryption\_box](#create_encryption_box) – Creates encryption box with specified algorithm

### Types

[CryptoErrorCode](#cryptoerrorcode)

[SigningBoxHandle](#signingboxhandle)

[EncryptionBoxHandle](#encryptionboxhandle)

[EncryptionBoxInfo](#encryptionboxinfo) – Encryption box information.

[EncryptionAlgorithmAESVariant](#encryptionalgorithmaesvariant)

[EncryptionAlgorithmChaCha20Variant](#encryptionalgorithmchacha20variant)

[EncryptionAlgorithmNaclBoxVariant](#encryptionalgorithmnaclboxvariant)

[EncryptionAlgorithmNaclSecretBoxVariant](#encryptionalgorithmnaclsecretboxvariant)

[EncryptionAlgorithm](#encryptionalgorithm)

[CipherMode](#ciphermode)

[AesParamsEB](#aesparamseb)

[AesInfo](#aesinfo)

[ChaCha20ParamsEB](#chacha20paramseb)

[NaclBoxParamsEB](#naclboxparamseb)

[NaclSecretBoxParamsEB](#naclsecretboxparamseb)

[CryptoBoxSecretRandomSeedPhraseVariant](#cryptoboxsecretrandomseedphrasevariant) – Creates Crypto Box from a random seed phrase. This option can be used if a developer doesn't want the seed phrase to leave the core library's memory, where it is stored encrypted.

[CryptoBoxSecretPredefinedSeedPhraseVariant](#cryptoboxsecretpredefinedseedphrasevariant) – Restores crypto box instance from an existing seed phrase. This type should be used when Crypto Box is initialized from a seed phrase, entered by a user.

[CryptoBoxSecretEncryptedSecretVariant](#cryptoboxsecretencryptedsecretvariant) – Use this type for wallet reinitializations, when you already have `encrypted_secret` on hands. To get `encrypted_secret`, use `get_crypto_box_info` function after you initialized your crypto box for the first time.

[CryptoBoxSecret](#cryptoboxsecret) – Crypto Box Secret.

[CryptoBoxHandle](#cryptoboxhandle)

[BoxEncryptionAlgorithmChaCha20Variant](#boxencryptionalgorithmchacha20variant)

[BoxEncryptionAlgorithmNaclBoxVariant](#boxencryptionalgorithmnaclboxvariant)

[BoxEncryptionAlgorithmNaclSecretBoxVariant](#boxencryptionalgorithmnaclsecretboxvariant)

[BoxEncryptionAlgorithm](#boxencryptionalgorithm)

[ChaCha20ParamsCB](#chacha20paramscb)

[NaclBoxParamsCB](#naclboxparamscb)

[NaclSecretBoxParamsCB](#naclsecretboxparamscb)

[MnemonicDictionary](#mnemonicdictionary)

[ParamsOfFactorize](#paramsoffactorize)

[ResultOfFactorize](#resultoffactorize)

[ParamsOfModularPower](#paramsofmodularpower)

[ResultOfModularPower](#resultofmodularpower)

[ParamsOfTonCrc16](#paramsoftoncrc16)

[ResultOfTonCrc16](#resultoftoncrc16)

[ParamsOfGenerateRandomBytes](#paramsofgeneraterandombytes)

[ResultOfGenerateRandomBytes](#resultofgeneraterandombytes)

[ParamsOfConvertPublicKeyToTonSafeFormat](#paramsofconvertpublickeytotonsafeformat)

[ResultOfConvertPublicKeyToTonSafeFormat](#resultofconvertpublickeytotonsafeformat)

[KeyPair](#keypair)

[ParamsOfSign](#paramsofsign)

[ResultOfSign](#resultofsign)

[ParamsOfVerifySignature](#paramsofverifysignature)

[ResultOfVerifySignature](#resultofverifysignature)

[ParamsOfHash](#paramsofhash)

[ResultOfHash](#resultofhash)

[ParamsOfScrypt](#paramsofscrypt)

[ResultOfScrypt](#resultofscrypt)

[ParamsOfNaclSignKeyPairFromSecret](#paramsofnaclsignkeypairfromsecret)

[ParamsOfNaclSign](#paramsofnaclsign)

[ResultOfNaclSign](#resultofnaclsign)

[ParamsOfNaclSignOpen](#paramsofnaclsignopen)

[ResultOfNaclSignOpen](#resultofnaclsignopen)

[ResultOfNaclSignDetached](#resultofnaclsigndetached)

[ParamsOfNaclSignDetachedVerify](#paramsofnaclsigndetachedverify)

[ResultOfNaclSignDetachedVerify](#resultofnaclsigndetachedverify)

[ParamsOfNaclBoxKeyPairFromSecret](#paramsofnaclboxkeypairfromsecret)

[ParamsOfNaclBox](#paramsofnaclbox)

[ResultOfNaclBox](#resultofnaclbox)

[ParamsOfNaclBoxOpen](#paramsofnaclboxopen)

[ResultOfNaclBoxOpen](#resultofnaclboxopen)

[ParamsOfNaclSecretBox](#paramsofnaclsecretbox)

[ParamsOfNaclSecretBoxOpen](#paramsofnaclsecretboxopen)

[ParamsOfMnemonicWords](#paramsofmnemonicwords)

[ResultOfMnemonicWords](#resultofmnemonicwords)

[ParamsOfMnemonicFromRandom](#paramsofmnemonicfromrandom)

[ResultOfMnemonicFromRandom](#resultofmnemonicfromrandom)

[ParamsOfMnemonicFromEntropy](#paramsofmnemonicfromentropy)

[ResultOfMnemonicFromEntropy](#resultofmnemonicfromentropy)

[ParamsOfMnemonicVerify](#paramsofmnemonicverify)

[ResultOfMnemonicVerify](#resultofmnemonicverify)

[ParamsOfMnemonicDeriveSignKeys](#paramsofmnemonicderivesignkeys)

[ParamsOfHDKeyXPrvFromMnemonic](#paramsofhdkeyxprvfrommnemonic)

[ResultOfHDKeyXPrvFromMnemonic](#resultofhdkeyxprvfrommnemonic)

[ParamsOfHDKeyDeriveFromXPrv](#paramsofhdkeyderivefromxprv)

[ResultOfHDKeyDeriveFromXPrv](#resultofhdkeyderivefromxprv)

[ParamsOfHDKeyDeriveFromXPrvPath](#paramsofhdkeyderivefromxprvpath)

[ResultOfHDKeyDeriveFromXPrvPath](#resultofhdkeyderivefromxprvpath)

[ParamsOfHDKeySecretFromXPrv](#paramsofhdkeysecretfromxprv)

[ResultOfHDKeySecretFromXPrv](#resultofhdkeysecretfromxprv)

[ParamsOfHDKeyPublicFromXPrv](#paramsofhdkeypublicfromxprv)

[ResultOfHDKeyPublicFromXPrv](#resultofhdkeypublicfromxprv)

[ParamsOfChaCha20](#paramsofchacha20)

[ResultOfChaCha20](#resultofchacha20)

[ParamsOfCreateCryptoBox](#paramsofcreatecryptobox)

[RegisteredCryptoBox](#registeredcryptobox)

[ParamsOfAppPasswordProviderGetPasswordVariant](#paramsofapppasswordprovidergetpasswordvariant)

[ParamsOfAppPasswordProvider](#paramsofapppasswordprovider) – Interface that provides a callback that returns an encrypted password, used for cryptobox secret encryption

[ResultOfAppPasswordProviderGetPasswordVariant](#resultofapppasswordprovidergetpasswordvariant)

[ResultOfAppPasswordProvider](#resultofapppasswordprovider)

[ResultOfGetCryptoBoxInfo](#resultofgetcryptoboxinfo)

[ResultOfGetCryptoBoxSeedPhrase](#resultofgetcryptoboxseedphrase)

[ParamsOfGetSigningBoxFromCryptoBox](#paramsofgetsigningboxfromcryptobox)

[RegisteredSigningBox](#registeredsigningbox)

[ParamsOfGetEncryptionBoxFromCryptoBox](#paramsofgetencryptionboxfromcryptobox)

[RegisteredEncryptionBox](#registeredencryptionbox)

[ParamsOfAppSigningBoxGetPublicKeyVariant](#paramsofappsigningboxgetpublickeyvariant) – Get signing box public key

[ParamsOfAppSigningBoxSignVariant](#paramsofappsigningboxsignvariant) – Sign data

[ParamsOfAppSigningBox](#paramsofappsigningbox) – Signing box callbacks.

[ResultOfAppSigningBoxGetPublicKeyVariant](#resultofappsigningboxgetpublickeyvariant) – Result of getting public key

[ResultOfAppSigningBoxSignVariant](#resultofappsigningboxsignvariant) – Result of signing data

[ResultOfAppSigningBox](#resultofappsigningbox) – Returning values from signing box callbacks.

[ResultOfSigningBoxGetPublicKey](#resultofsigningboxgetpublickey)

[ParamsOfSigningBoxSign](#paramsofsigningboxsign)

[ResultOfSigningBoxSign](#resultofsigningboxsign)

[ParamsOfAppEncryptionBoxGetInfoVariant](#paramsofappencryptionboxgetinfovariant) – Get encryption box info

[ParamsOfAppEncryptionBoxEncryptVariant](#paramsofappencryptionboxencryptvariant) – Encrypt data

[ParamsOfAppEncryptionBoxDecryptVariant](#paramsofappencryptionboxdecryptvariant) – Decrypt data

[ParamsOfAppEncryptionBox](#paramsofappencryptionbox) – Interface for data encryption/decryption

[ResultOfAppEncryptionBoxGetInfoVariant](#resultofappencryptionboxgetinfovariant) – Result of getting encryption box info

[ResultOfAppEncryptionBoxEncryptVariant](#resultofappencryptionboxencryptvariant) – Result of encrypting data

[ResultOfAppEncryptionBoxDecryptVariant](#resultofappencryptionboxdecryptvariant) – Result of decrypting data

[ResultOfAppEncryptionBox](#resultofappencryptionbox) – Returning values from signing box callbacks.

[ParamsOfEncryptionBoxGetInfo](#paramsofencryptionboxgetinfo)

[ResultOfEncryptionBoxGetInfo](#resultofencryptionboxgetinfo)

[ParamsOfEncryptionBoxEncrypt](#paramsofencryptionboxencrypt)

[ResultOfEncryptionBoxEncrypt](#resultofencryptionboxencrypt)

[ParamsOfEncryptionBoxDecrypt](#paramsofencryptionboxdecrypt)

[ResultOfEncryptionBoxDecrypt](#resultofencryptionboxdecrypt)

[ParamsOfCreateEncryptionBox](#paramsofcreateencryptionbox)

[AppPasswordProvider](#apppasswordprovider) – Interface that provides a callback that returns an encrypted password, used for cryptobox secret encryption

[AppSigningBox](#appsigningbox) – Signing box callbacks.

[AppEncryptionBox](#appencryptionbox) – Interface for data encryption/decryption

## Functions

### factorize

Integer factorization

Performs prime factorization – decomposition of a composite number into a product of smaller prime integers (factors). See \[<https://en.wikipedia.org/wiki/Integer\\_factorization>]

```ts
type ParamsOfFactorize = {
    composite: string
}

type ResultOfFactorize = {
    factors: string[]
}

function factorize(
    params: ParamsOfFactorize,
): Promise<ResultOfFactorize>;

function factorize_sync(
    params: ParamsOfFactorize,
): ResultOfFactorize;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `composite`: *string* – Hexadecimal representation of u64 composite number.

#### Result

* `factors`: *string\[]* – Two factors of composite or empty if composite can't be factorized.

### modular\_power

Modular exponentiation

Performs modular exponentiation for big integers (`base`^`exponent` mod `modulus`). See \[<https://en.wikipedia.org/wiki/Modular\\_exponentiation>]

```ts
type ParamsOfModularPower = {
    base: string,
    exponent: string,
    modulus: string
}

type ResultOfModularPower = {
    modular_power: string
}

function modular_power(
    params: ParamsOfModularPower,
): Promise<ResultOfModularPower>;

function modular_power_sync(
    params: ParamsOfModularPower,
): ResultOfModularPower;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `base`: *string* – `base` argument of calculation.
* `exponent`: *string* – `exponent` argument of calculation.
* `modulus`: *string* – `modulus` argument of calculation.

#### Result

* `modular_power`: *string* – Result of modular exponentiation

### ton\_crc16

Calculates CRC16 using TON algorithm.

```ts
type ParamsOfTonCrc16 = {
    data: string
}

type ResultOfTonCrc16 = {
    crc: number
}

function ton_crc16(
    params: ParamsOfTonCrc16,
): Promise<ResultOfTonCrc16>;

function ton_crc16_sync(
    params: ParamsOfTonCrc16,
): ResultOfTonCrc16;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `data`: *string* – Input data for CRC calculation.\
  Encoded with `base64`.

#### Result

* `crc`: *number* – Calculated CRC for input data.

### generate\_random\_bytes

Generates random byte array of the specified length and returns it in `base64` format

```ts
type ParamsOfGenerateRandomBytes = {
    length: number
}

type ResultOfGenerateRandomBytes = {
    bytes: string
}

function generate_random_bytes(
    params: ParamsOfGenerateRandomBytes,
): Promise<ResultOfGenerateRandomBytes>;

function generate_random_bytes_sync(
    params: ParamsOfGenerateRandomBytes,
): ResultOfGenerateRandomBytes;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `length`: *number* – Size of random byte array.

#### Result

* `bytes`: *string* – Generated bytes encoded in `base64`.

### convert\_public\_key\_to\_ton\_safe\_format

Converts public key to ton safe\_format

```ts
type ParamsOfConvertPublicKeyToTonSafeFormat = {
    public_key: string
}

type ResultOfConvertPublicKeyToTonSafeFormat = {
    ton_public_key: string
}

function convert_public_key_to_ton_safe_format(
    params: ParamsOfConvertPublicKeyToTonSafeFormat,
): Promise<ResultOfConvertPublicKeyToTonSafeFormat>;

function convert_public_key_to_ton_safe_format_sync(
    params: ParamsOfConvertPublicKeyToTonSafeFormat,
): ResultOfConvertPublicKeyToTonSafeFormat;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `public_key`: *string* – Public key - 64 symbols hex string

#### Result

* `ton_public_key`: *string* – Public key represented in TON safe format.

### generate\_random\_sign\_keys

Generates random ed25519 key pair.

```ts
type KeyPair = {
    public: string,
    secret: string
}

function generate_random_sign_keys(): Promise<KeyPair>;

function generate_random_sign_keys_sync(): KeyPair;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `public`: *string* – Public key - 64 symbols hex string
* `secret`: *string* – Private key - u64 symbols hex string

### sign

Signs a data using the provided keys.

```ts
type ParamsOfSign = {
    unsigned: string,
    keys: KeyPair
}

type ResultOfSign = {
    signed: string,
    signature: string
}

function sign(
    params: ParamsOfSign,
): Promise<ResultOfSign>;

function sign_sync(
    params: ParamsOfSign,
): ResultOfSign;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `unsigned`: *string* – Data that must be signed encoded in `base64`.
* `keys`: [*KeyPair*](#keypair) – Sign keys.

#### Result

* `signed`: *string* – Signed data combined with signature encoded in `base64`.
* `signature`: *string* – Signature encoded in `hex`.

### verify\_signature

Verifies signed data using the provided public key. Raises error if verification is failed.

```ts
type ParamsOfVerifySignature = {
    signed: string,
    public: string
}

type ResultOfVerifySignature = {
    unsigned: string
}

function verify_signature(
    params: ParamsOfVerifySignature,
): Promise<ResultOfVerifySignature>;

function verify_signature_sync(
    params: ParamsOfVerifySignature,
): ResultOfVerifySignature;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `signed`: *string* – Signed data that must be verified encoded in `base64`.
* `public`: *string* – Signer's public key - 64 symbols hex string

#### Result

* `unsigned`: *string* – Unsigned data encoded in `base64`.

### sha256

Calculates SHA256 hash of the specified data.

```ts
type ParamsOfHash = {
    data: string
}

type ResultOfHash = {
    hash: string
}

function sha256(
    params: ParamsOfHash,
): Promise<ResultOfHash>;

function sha256_sync(
    params: ParamsOfHash,
): ResultOfHash;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `data`: *string* – Input data for hash calculation.\
  Encoded with `base64`.

#### Result

* `hash`: *string* – Hash of input `data`.\
  Encoded with 'hex'.

### sha512

Calculates SHA512 hash of the specified data.

```ts
type ParamsOfHash = {
    data: string
}

type ResultOfHash = {
    hash: string
}

function sha512(
    params: ParamsOfHash,
): Promise<ResultOfHash>;

function sha512_sync(
    params: ParamsOfHash,
): ResultOfHash;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `data`: *string* – Input data for hash calculation.\
  Encoded with `base64`.

#### Result

* `hash`: *string* – Hash of input `data`.\
  Encoded with 'hex'.

### scrypt

Perform `scrypt` encryption

Derives key from `password` and `key` using `scrypt` algorithm. See \[<https://en.wikipedia.org/wiki/Scrypt>].

## Arguments

* `log_n` - The log2 of the Scrypt parameter `N`
* `r` - The Scrypt parameter `r`
* `p` - The Scrypt parameter `p`

## Conditions

* `log_n` must be less than `64`
* `r` must be greater than `0` and less than or equal to `4294967295`
* `p` must be greater than `0` and less than `4294967295`

## Recommended values sufficient for most use-cases

* `log_n = 15` (`n = 32768`)
* `r = 8`
* `p = 1`

```ts
type ParamsOfScrypt = {
    password: string,
    salt: string,
    log_n: number,
    r: number,
    p: number,
    dk_len: number
}

type ResultOfScrypt = {
    key: string
}

function scrypt(
    params: ParamsOfScrypt,
): Promise<ResultOfScrypt>;

function scrypt_sync(
    params: ParamsOfScrypt,
): ResultOfScrypt;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `password`: *string* – The password bytes to be hashed. Must be encoded with `base64`.
* `salt`: *string* – Salt bytes that modify the hash to protect against Rainbow table attacks. Must be encoded with `base64`.
* `log_n`: *number* – CPU/memory cost parameter
* `r`: *number* – The block size parameter, which fine-tunes sequential memory read size and performance.
* `p`: *number* – Parallelization parameter.
* `dk_len`: *number* – Intended output length in octets of the derived key.

#### Result

* `key`: *string* – Derived key.\
  Encoded with `hex`.

### nacl\_sign\_keypair\_from\_secret\_key

Generates a key pair for signing from the secret key

**NOTE:** In the result the secret key is actually the concatenation of secret and public keys (128 symbols hex string) by design of [NaCL](http://nacl.cr.yp.to/sign.html). See also [the stackexchange question](https://crypto.stackexchange.com/questions/54353/).

```ts
type ParamsOfNaclSignKeyPairFromSecret = {
    secret: string
}

type KeyPair = {
    public: string,
    secret: string
}

function nacl_sign_keypair_from_secret_key(
    params: ParamsOfNaclSignKeyPairFromSecret,
): Promise<KeyPair>;

function nacl_sign_keypair_from_secret_key_sync(
    params: ParamsOfNaclSignKeyPairFromSecret,
): KeyPair;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `secret`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

#### Result

* `public`: *string* – Public key - 64 symbols hex string
* `secret`: *string* – Private key - u64 symbols hex string

### nacl\_sign

Signs data using the signer's secret key.

```ts
type ParamsOfNaclSign = {
    unsigned: string,
    secret: string
}

type ResultOfNaclSign = {
    signed: string
}

function nacl_sign(
    params: ParamsOfNaclSign,
): Promise<ResultOfNaclSign>;

function nacl_sign_sync(
    params: ParamsOfNaclSign,
): ResultOfNaclSign;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `unsigned`: *string* – Data that must be signed encoded in `base64`.
* `secret`: *string* – Signer's secret key - unprefixed 0-padded to 128 symbols hex string (concatenation of 64 symbols secret and 64 symbols public keys). See `nacl_sign_keypair_from_secret_key`.

#### Result

* `signed`: *string* – Signed data, encoded in `base64`.

### nacl\_sign\_open

Verifies the signature and returns the unsigned message

Verifies the signature in `signed` using the signer's public key `public` and returns the message `unsigned`.

If the signature fails verification, crypto\_sign\_open raises an exception.

```ts
type ParamsOfNaclSignOpen = {
    signed: string,
    public: string
}

type ResultOfNaclSignOpen = {
    unsigned: string
}

function nacl_sign_open(
    params: ParamsOfNaclSignOpen,
): Promise<ResultOfNaclSignOpen>;

function nacl_sign_open_sync(
    params: ParamsOfNaclSignOpen,
): ResultOfNaclSignOpen;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `signed`: *string* – Signed data that must be unsigned.\
  Encoded with `base64`.
* `public`: *string* – Signer's public key - unprefixed 0-padded to 64 symbols hex string

#### Result

* `unsigned`: *string* – Unsigned data, encoded in `base64`.

### nacl\_sign\_detached

Signs the message using the secret key and returns a signature.

Signs the message `unsigned` using the secret key `secret` and returns a signature `signature`.

```ts
type ParamsOfNaclSign = {
    unsigned: string,
    secret: string
}

type ResultOfNaclSignDetached = {
    signature: string
}

function nacl_sign_detached(
    params: ParamsOfNaclSign,
): Promise<ResultOfNaclSignDetached>;

function nacl_sign_detached_sync(
    params: ParamsOfNaclSign,
): ResultOfNaclSignDetached;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `unsigned`: *string* – Data that must be signed encoded in `base64`.
* `secret`: *string* – Signer's secret key - unprefixed 0-padded to 128 symbols hex string (concatenation of 64 symbols secret and 64 symbols public keys). See `nacl_sign_keypair_from_secret_key`.

#### Result

* `signature`: *string* – Signature encoded in `hex`.

### nacl\_sign\_detached\_verify

Verifies the signature with public key and `unsigned` data.

```ts
type ParamsOfNaclSignDetachedVerify = {
    unsigned: string,
    signature: string,
    public: string
}

type ResultOfNaclSignDetachedVerify = {
    succeeded: boolean
}

function nacl_sign_detached_verify(
    params: ParamsOfNaclSignDetachedVerify,
): Promise<ResultOfNaclSignDetachedVerify>;

function nacl_sign_detached_verify_sync(
    params: ParamsOfNaclSignDetachedVerify,
): ResultOfNaclSignDetachedVerify;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `unsigned`: *string* – Unsigned data that must be verified.\
  Encoded with `base64`.
* `signature`: *string* – Signature that must be verified.\
  Encoded with `hex`.
* `public`: *string* – Signer's public key - unprefixed 0-padded to 64 symbols hex string.

#### Result

* `succeeded`: *boolean* – `true` if verification succeeded or `false` if it failed

### nacl\_box\_keypair

Generates a random NaCl key pair

```ts
type KeyPair = {
    public: string,
    secret: string
}

function nacl_box_keypair(): Promise<KeyPair>;

function nacl_box_keypair_sync(): KeyPair;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `public`: *string* – Public key - 64 symbols hex string
* `secret`: *string* – Private key - u64 symbols hex string

### nacl\_box\_keypair\_from\_secret\_key

Generates key pair from a secret key

```ts
type ParamsOfNaclBoxKeyPairFromSecret = {
    secret: string
}

type KeyPair = {
    public: string,
    secret: string
}

function nacl_box_keypair_from_secret_key(
    params: ParamsOfNaclBoxKeyPairFromSecret,
): Promise<KeyPair>;

function nacl_box_keypair_from_secret_key_sync(
    params: ParamsOfNaclBoxKeyPairFromSecret,
): KeyPair;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `secret`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

#### Result

* `public`: *string* – Public key - 64 symbols hex string
* `secret`: *string* – Private key - u64 symbols hex string

### nacl\_box

Public key authenticated encryption

Encrypt and authenticate a message using the senders secret key, the receivers public key, and a nonce.

```ts
type ParamsOfNaclBox = {
    decrypted: string,
    nonce: string,
    their_public: string,
    secret: string
}

type ResultOfNaclBox = {
    encrypted: string
}

function nacl_box(
    params: ParamsOfNaclBox,
): Promise<ResultOfNaclBox>;

function nacl_box_sync(
    params: ParamsOfNaclBox,
): ResultOfNaclBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `decrypted`: *string* – Data that must be encrypted encoded in `base64`.
* `nonce`: *string* – Nonce, encoded in `hex`
* `their_public`: *string* – Receiver's public key - unprefixed 0-padded to 64 symbols hex string
* `secret`: *string* – Sender's private key - unprefixed 0-padded to 64 symbols hex string

#### Result

* `encrypted`: *string* – Encrypted data encoded in `base64`.

### nacl\_box\_open

Decrypt and verify the cipher text using the receivers secret key, the senders public key, and the nonce.

```ts
type ParamsOfNaclBoxOpen = {
    encrypted: string,
    nonce: string,
    their_public: string,
    secret: string
}

type ResultOfNaclBoxOpen = {
    decrypted: string
}

function nacl_box_open(
    params: ParamsOfNaclBoxOpen,
): Promise<ResultOfNaclBoxOpen>;

function nacl_box_open_sync(
    params: ParamsOfNaclBoxOpen,
): ResultOfNaclBoxOpen;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `encrypted`: *string* – Data that must be decrypted.\
  Encoded with `base64`.
* `nonce`: *string* – Nonce
* `their_public`: *string* – Sender's public key - unprefixed 0-padded to 64 symbols hex string
* `secret`: *string* – Receiver's private key - unprefixed 0-padded to 64 symbols hex string

#### Result

* `decrypted`: *string* – Decrypted data encoded in `base64`.

### nacl\_secret\_box

Encrypt and authenticate message using nonce and secret key.

```ts
type ParamsOfNaclSecretBox = {
    decrypted: string,
    nonce: string,
    key: string
}

type ResultOfNaclBox = {
    encrypted: string
}

function nacl_secret_box(
    params: ParamsOfNaclSecretBox,
): Promise<ResultOfNaclBox>;

function nacl_secret_box_sync(
    params: ParamsOfNaclSecretBox,
): ResultOfNaclBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `decrypted`: *string* – Data that must be encrypted.\
  Encoded with `base64`.
* `nonce`: *string* – Nonce in `hex`
* `key`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

#### Result

* `encrypted`: *string* – Encrypted data encoded in `base64`.

### nacl\_secret\_box\_open

Decrypts and verifies cipher text using `nonce` and secret `key`.

```ts
type ParamsOfNaclSecretBoxOpen = {
    encrypted: string,
    nonce: string,
    key: string
}

type ResultOfNaclBoxOpen = {
    decrypted: string
}

function nacl_secret_box_open(
    params: ParamsOfNaclSecretBoxOpen,
): Promise<ResultOfNaclBoxOpen>;

function nacl_secret_box_open_sync(
    params: ParamsOfNaclSecretBoxOpen,
): ResultOfNaclBoxOpen;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `encrypted`: *string* – Data that must be decrypted.\
  Encoded with `base64`.
* `nonce`: *string* – Nonce in `hex`
* `key`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

#### Result

* `decrypted`: *string* – Decrypted data encoded in `base64`.

### mnemonic\_words

Prints the list of words from the specified dictionary

```ts
type ParamsOfMnemonicWords = {
    dictionary?: MnemonicDictionary
}

type ResultOfMnemonicWords = {
    words: string
}

function mnemonic_words(
    params: ParamsOfMnemonicWords,
): Promise<ResultOfMnemonicWords>;

function mnemonic_words_sync(
    params: ParamsOfMnemonicWords,
): ResultOfMnemonicWords;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier

#### Result

* `words`: *string* – The list of mnemonic words

### mnemonic\_from\_random

Generates a random mnemonic

Generates a random mnemonic from the specified dictionary and word count

```ts
type ParamsOfMnemonicFromRandom = {
    dictionary?: MnemonicDictionary,
    word_count?: number
}

type ResultOfMnemonicFromRandom = {
    phrase: string
}

function mnemonic_from_random(
    params: ParamsOfMnemonicFromRandom,
): Promise<ResultOfMnemonicFromRandom>;

function mnemonic_from_random_sync(
    params: ParamsOfMnemonicFromRandom,
): ResultOfMnemonicFromRandom;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Mnemonic word count

#### Result

* `phrase`: *string* – String of mnemonic words

### mnemonic\_from\_entropy

Generates mnemonic from pre-generated entropy

```ts
type ParamsOfMnemonicFromEntropy = {
    entropy: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}

type ResultOfMnemonicFromEntropy = {
    phrase: string
}

function mnemonic_from_entropy(
    params: ParamsOfMnemonicFromEntropy,
): Promise<ResultOfMnemonicFromEntropy>;

function mnemonic_from_entropy_sync(
    params: ParamsOfMnemonicFromEntropy,
): ResultOfMnemonicFromEntropy;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `entropy`: *string* – Entropy bytes.\
  Hex encoded.
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Mnemonic word count

#### Result

* `phrase`: *string* – Phrase

### mnemonic\_verify

Validates a mnemonic phrase

The phrase supplied will be checked for word length and validated according to the checksum specified in BIP0039.

```ts
type ParamsOfMnemonicVerify = {
    phrase: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}

type ResultOfMnemonicVerify = {
    valid: boolean
}

function mnemonic_verify(
    params: ParamsOfMnemonicVerify,
): Promise<ResultOfMnemonicVerify>;

function mnemonic_verify_sync(
    params: ParamsOfMnemonicVerify,
): ResultOfMnemonicVerify;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `phrase`: *string* – Phrase
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Word count

#### Result

* `valid`: *boolean* – Flag indicating if the mnemonic is valid or not

### mnemonic\_derive\_sign\_keys

Derives a key pair for signing from the seed phrase

Validates the seed phrase, generates master key and then derives the key pair from the master key and the specified path

```ts
type ParamsOfMnemonicDeriveSignKeys = {
    phrase: string,
    path?: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}

type KeyPair = {
    public: string,
    secret: string
}

function mnemonic_derive_sign_keys(
    params: ParamsOfMnemonicDeriveSignKeys,
): Promise<KeyPair>;

function mnemonic_derive_sign_keys_sync(
    params: ParamsOfMnemonicDeriveSignKeys,
): KeyPair;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `phrase`: *string* – Phrase
* `path`?: *string* – Derivation path, for instance "m/44'/396'/0'/0/0"
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Word count

#### Result

* `public`: *string* – Public key - 64 symbols hex string
* `secret`: *string* – Private key - u64 symbols hex string

### hdkey\_xprv\_from\_mnemonic

Generates an extended master private key that will be the root for all the derived keys

```ts
type ParamsOfHDKeyXPrvFromMnemonic = {
    phrase: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}

type ResultOfHDKeyXPrvFromMnemonic = {
    xprv: string
}

function hdkey_xprv_from_mnemonic(
    params: ParamsOfHDKeyXPrvFromMnemonic,
): Promise<ResultOfHDKeyXPrvFromMnemonic>;

function hdkey_xprv_from_mnemonic_sync(
    params: ParamsOfHDKeyXPrvFromMnemonic,
): ResultOfHDKeyXPrvFromMnemonic;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `phrase`: *string* – String with seed phrase
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Mnemonic word count

#### Result

* `xprv`: *string* – Serialized extended master private key

### hdkey\_derive\_from\_xprv

Returns extended private key derived from the specified extended private key and child index

```ts
type ParamsOfHDKeyDeriveFromXPrv = {
    xprv: string,
    child_index: number,
    hardened: boolean
}

type ResultOfHDKeyDeriveFromXPrv = {
    xprv: string
}

function hdkey_derive_from_xprv(
    params: ParamsOfHDKeyDeriveFromXPrv,
): Promise<ResultOfHDKeyDeriveFromXPrv>;

function hdkey_derive_from_xprv_sync(
    params: ParamsOfHDKeyDeriveFromXPrv,
): ResultOfHDKeyDeriveFromXPrv;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `xprv`: *string* – Serialized extended private key
* `child_index`: *number* – Child index (see BIP-0032)
* `hardened`: *boolean* – Indicates the derivation of hardened/not-hardened key (see BIP-0032)

#### Result

* `xprv`: *string* – Serialized extended private key

### hdkey\_derive\_from\_xprv\_path

Derives the extended private key from the specified key and path

```ts
type ParamsOfHDKeyDeriveFromXPrvPath = {
    xprv: string,
    path: string
}

type ResultOfHDKeyDeriveFromXPrvPath = {
    xprv: string
}

function hdkey_derive_from_xprv_path(
    params: ParamsOfHDKeyDeriveFromXPrvPath,
): Promise<ResultOfHDKeyDeriveFromXPrvPath>;

function hdkey_derive_from_xprv_path_sync(
    params: ParamsOfHDKeyDeriveFromXPrvPath,
): ResultOfHDKeyDeriveFromXPrvPath;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `xprv`: *string* – Serialized extended private key
* `path`: *string* – Derivation path, for instance "m/44'/396'/0'/0/0"

#### Result

* `xprv`: *string* – Derived serialized extended private key

### hdkey\_secret\_from\_xprv

Extracts the private key from the serialized extended private key

```ts
type ParamsOfHDKeySecretFromXPrv = {
    xprv: string
}

type ResultOfHDKeySecretFromXPrv = {
    secret: string
}

function hdkey_secret_from_xprv(
    params: ParamsOfHDKeySecretFromXPrv,
): Promise<ResultOfHDKeySecretFromXPrv>;

function hdkey_secret_from_xprv_sync(
    params: ParamsOfHDKeySecretFromXPrv,
): ResultOfHDKeySecretFromXPrv;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `xprv`: *string* – Serialized extended private key

#### Result

* `secret`: *string* – Private key - 64 symbols hex string

### hdkey\_public\_from\_xprv

Extracts the public key from the serialized extended private key

```ts
type ParamsOfHDKeyPublicFromXPrv = {
    xprv: string
}

type ResultOfHDKeyPublicFromXPrv = {
    public: string
}

function hdkey_public_from_xprv(
    params: ParamsOfHDKeyPublicFromXPrv,
): Promise<ResultOfHDKeyPublicFromXPrv>;

function hdkey_public_from_xprv_sync(
    params: ParamsOfHDKeyPublicFromXPrv,
): ResultOfHDKeyPublicFromXPrv;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `xprv`: *string* – Serialized extended private key

#### Result

* `public`: *string* – Public key - 64 symbols hex string

### chacha20

Performs symmetric `chacha20` encryption.

```ts
type ParamsOfChaCha20 = {
    data: string,
    key: string,
    nonce: string
}

type ResultOfChaCha20 = {
    data: string
}

function chacha20(
    params: ParamsOfChaCha20,
): Promise<ResultOfChaCha20>;

function chacha20_sync(
    params: ParamsOfChaCha20,
): ResultOfChaCha20;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `data`: *string* – Source data to be encrypted or decrypted.\
  Must be encoded with `base64`.
* `key`: *string* – 256-bit key.\
  Must be encoded with `hex`.
* `nonce`: *string* – 96-bit nonce.\
  Must be encoded with `hex`.

#### Result

* `data`: *string* – Encrypted/decrypted data.\
  Encoded with `base64`.

### create\_crypto\_box

Creates a Crypto Box instance.

Crypto Box is a root crypto object, that encapsulates some secret (seed phrase usually) in encrypted form and acts as a factory for all crypto primitives used in SDK: keys for signing and encryption, derived from this secret.

Crypto Box encrypts original Seed Phrase with salt and password that is retrieved from `password_provider` callback, implemented on Application side.

When used, decrypted secret shows up in core library's memory for a very short period of time and then is immediately overwritten with zeroes.

```ts
type ParamsOfCreateCryptoBox = {
    secret_encryption_salt: string,
    secret: CryptoBoxSecret
}

type RegisteredCryptoBox = {
    handle: CryptoBoxHandle
}

function create_crypto_box(
    params: ParamsOfCreateCryptoBox,
    obj: AppPasswordProvider,
): Promise<RegisteredCryptoBox>;

function create_crypto_box_sync(
    params: ParamsOfCreateCryptoBox,
): RegisteredCryptoBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `secret_encryption_salt`: *string* – Salt used for secret encryption. For example, a mobile device can use device ID as salt.
* `secret`: [*CryptoBoxSecret*](#cryptoboxsecret) – Cryptobox secret
* `obj`: [AppPasswordProvider](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/mod_AppPasswordProvider.md#apppasswordprovider) – Interface that provides a callback that returns an encrypted password, used for cryptobox secret encryption

#### Result

* `handle`: [*CryptoBoxHandle*](#cryptoboxhandle)

### remove\_crypto\_box

Removes Crypto Box. Clears all secret data.

```ts
type RegisteredCryptoBox = {
    handle: CryptoBoxHandle
}

function remove_crypto_box(
    params: RegisteredCryptoBox,
): Promise<void>;

function remove_crypto_box_sync(
    params: RegisteredCryptoBox,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: [*CryptoBoxHandle*](#cryptoboxhandle)

### get\_crypto\_box\_info

Get Crypto Box Info. Used to get `encrypted_secret` that should be used for all the cryptobox initializations except the first one.

```ts
type RegisteredCryptoBox = {
    handle: CryptoBoxHandle
}

type ResultOfGetCryptoBoxInfo = {
    encrypted_secret: string
}

function get_crypto_box_info(
    params: RegisteredCryptoBox,
): Promise<ResultOfGetCryptoBoxInfo>;

function get_crypto_box_info_sync(
    params: RegisteredCryptoBox,
): ResultOfGetCryptoBoxInfo;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: [*CryptoBoxHandle*](#cryptoboxhandle)

#### Result

* `encrypted_secret`: *string* – Secret (seed phrase) encrypted with salt and password.

### get\_crypto\_box\_seed\_phrase

Get Crypto Box Seed Phrase.

Attention! Store this data in your application for a very short period of time and overwrite it with zeroes ASAP.

```ts
type RegisteredCryptoBox = {
    handle: CryptoBoxHandle
}

type ResultOfGetCryptoBoxSeedPhrase = {
    phrase: string,
    dictionary: MnemonicDictionary,
    wordcount: number
}

function get_crypto_box_seed_phrase(
    params: RegisteredCryptoBox,
): Promise<ResultOfGetCryptoBoxSeedPhrase>;

function get_crypto_box_seed_phrase_sync(
    params: RegisteredCryptoBox,
): ResultOfGetCryptoBoxSeedPhrase;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: [*CryptoBoxHandle*](#cryptoboxhandle)

#### Result

* `phrase`: *string*
* `dictionary`: [*MnemonicDictionary*](#mnemonicdictionary)
* `wordcount`: *number*

### get\_signing\_box\_from\_crypto\_box

Get handle of Signing Box derived from Crypto Box.

```ts
type ParamsOfGetSigningBoxFromCryptoBox = {
    handle: number,
    hdpath?: string,
    secret_lifetime?: number
}

type RegisteredSigningBox = {
    handle: SigningBoxHandle
}

function get_signing_box_from_crypto_box(
    params: ParamsOfGetSigningBoxFromCryptoBox,
): Promise<RegisteredSigningBox>;

function get_signing_box_from_crypto_box_sync(
    params: ParamsOfGetSigningBoxFromCryptoBox,
): RegisteredSigningBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: *number* – Crypto Box Handle.
* `hdpath`?: *string* – HD key derivation path.\
  By default, Everscale HD path is used.
* `secret_lifetime`?: *number* – Store derived secret for this lifetime (in ms). The timer starts after each signing box operation. Secrets will be deleted immediately after each signing box operation, if this value is not set.

#### Result

* `handle`: [*SigningBoxHandle*](#signingboxhandle) – Handle of the signing box.

### get\_encryption\_box\_from\_crypto\_box

Gets Encryption Box from Crypto Box.

Derives encryption keypair from cryptobox secret and hdpath and stores it in cache for `secret_lifetime` or until explicitly cleared by `clear_crypto_box_secret_cache` method. If `secret_lifetime` is not specified - overwrites encryption secret with zeroes immediately after encryption operation.

```ts
type ParamsOfGetEncryptionBoxFromCryptoBox = {
    handle: number,
    hdpath?: string,
    algorithm: BoxEncryptionAlgorithm,
    secret_lifetime?: number
}

type RegisteredEncryptionBox = {
    handle: EncryptionBoxHandle
}

function get_encryption_box_from_crypto_box(
    params: ParamsOfGetEncryptionBoxFromCryptoBox,
): Promise<RegisteredEncryptionBox>;

function get_encryption_box_from_crypto_box_sync(
    params: ParamsOfGetEncryptionBoxFromCryptoBox,
): RegisteredEncryptionBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: *number* – Crypto Box Handle.
* `hdpath`?: *string* – HD key derivation path.\
  By default, Everscale HD path is used.
* `algorithm`: [*BoxEncryptionAlgorithm*](#boxencryptionalgorithm) – Encryption algorithm.
* `secret_lifetime`?: *number* – Store derived secret for encryption algorithm for this lifetime (in ms). The timer starts after each encryption box operation. Secrets will be deleted (overwritten with zeroes) after each encryption operation, if this value is not set.

#### Result

* `handle`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Handle of the encryption box.

### clear\_crypto\_box\_secret\_cache

Removes cached secrets (overwrites with zeroes) from all signing and encryption boxes, derived from crypto box.

```ts
type RegisteredCryptoBox = {
    handle: CryptoBoxHandle
}

function clear_crypto_box_secret_cache(
    params: RegisteredCryptoBox,
): Promise<void>;

function clear_crypto_box_secret_cache_sync(
    params: RegisteredCryptoBox,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: [*CryptoBoxHandle*](#cryptoboxhandle)

### register\_signing\_box

Register an application implemented signing box.

```ts
type RegisteredSigningBox = {
    handle: SigningBoxHandle
}

function register_signing_box(
    obj: AppSigningBox,
): Promise<RegisteredSigningBox>;

function register_signing_box_sync(): RegisteredSigningBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `obj`: [AppSigningBox](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/mod_AppSigningBox.md#appsigningbox) – Signing box callbacks.

#### Result

* `handle`: [*SigningBoxHandle*](#signingboxhandle) – Handle of the signing box.

### get\_signing\_box

Creates a default signing box implementation.

```ts
type KeyPair = {
    public: string,
    secret: string
}

type RegisteredSigningBox = {
    handle: SigningBoxHandle
}

function get_signing_box(
    params: KeyPair,
): Promise<RegisteredSigningBox>;

function get_signing_box_sync(
    params: KeyPair,
): RegisteredSigningBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `public`: *string* – Public key - 64 symbols hex string
* `secret`: *string* – Private key - u64 symbols hex string

#### Result

* `handle`: [*SigningBoxHandle*](#signingboxhandle) – Handle of the signing box.

### signing\_box\_get\_public\_key

Returns public key of signing key pair.

```ts
type RegisteredSigningBox = {
    handle: SigningBoxHandle
}

type ResultOfSigningBoxGetPublicKey = {
    pubkey: string
}

function signing_box_get_public_key(
    params: RegisteredSigningBox,
): Promise<ResultOfSigningBoxGetPublicKey>;

function signing_box_get_public_key_sync(
    params: RegisteredSigningBox,
): ResultOfSigningBoxGetPublicKey;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: [*SigningBoxHandle*](#signingboxhandle) – Handle of the signing box.

#### Result

* `pubkey`: *string* – Public key of signing box.\
  Encoded with hex

### signing\_box\_sign

Returns signed user data.

```ts
type ParamsOfSigningBoxSign = {
    signing_box: SigningBoxHandle,
    unsigned: string
}

type ResultOfSigningBoxSign = {
    signature: string
}

function signing_box_sign(
    params: ParamsOfSigningBoxSign,
): Promise<ResultOfSigningBoxSign>;

function signing_box_sign_sync(
    params: ParamsOfSigningBoxSign,
): ResultOfSigningBoxSign;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `signing_box`: [*SigningBoxHandle*](#signingboxhandle) – Signing Box handle.
* `unsigned`: *string* – Unsigned user data.\
  Must be encoded with `base64`.

#### Result

* `signature`: *string* – Data signature.\
  Encoded with `hex`.

### remove\_signing\_box

Removes signing box from SDK.

```ts
type RegisteredSigningBox = {
    handle: SigningBoxHandle
}

function remove_signing_box(
    params: RegisteredSigningBox,
): Promise<void>;

function remove_signing_box_sync(
    params: RegisteredSigningBox,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: [*SigningBoxHandle*](#signingboxhandle) – Handle of the signing box.

### register\_encryption\_box

Register an application implemented encryption box.

```ts
type RegisteredEncryptionBox = {
    handle: EncryptionBoxHandle
}

function register_encryption_box(
    obj: AppEncryptionBox,
): Promise<RegisteredEncryptionBox>;

function register_encryption_box_sync(): RegisteredEncryptionBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `obj`: [AppEncryptionBox](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/mod_AppEncryptionBox.md#appencryptionbox) – Interface for data encryption/decryption

#### Result

* `handle`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Handle of the encryption box.

### remove\_encryption\_box

Removes encryption box from SDK

```ts
type RegisteredEncryptionBox = {
    handle: EncryptionBoxHandle
}

function remove_encryption_box(
    params: RegisteredEncryptionBox,
): Promise<void>;

function remove_encryption_box_sync(
    params: RegisteredEncryptionBox,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Handle of the encryption box.

### encryption\_box\_get\_info

Queries info from the given encryption box

```ts
type ParamsOfEncryptionBoxGetInfo = {
    encryption_box: EncryptionBoxHandle
}

type ResultOfEncryptionBoxGetInfo = {
    info: EncryptionBoxInfo
}

function encryption_box_get_info(
    params: ParamsOfEncryptionBoxGetInfo,
): Promise<ResultOfEncryptionBoxGetInfo>;

function encryption_box_get_info_sync(
    params: ParamsOfEncryptionBoxGetInfo,
): ResultOfEncryptionBoxGetInfo;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `encryption_box`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Encryption box handle

#### Result

* `info`: [*EncryptionBoxInfo*](#encryptionboxinfo) – Encryption box information

### encryption\_box\_encrypt

Encrypts data using given encryption box Note.

Block cipher algorithms pad data to cipher block size so encrypted data can be longer then original data. Client should store the original data size after encryption and use it after decryption to retrieve the original data from decrypted data.

```ts
type ParamsOfEncryptionBoxEncrypt = {
    encryption_box: EncryptionBoxHandle,
    data: string
}

type ResultOfEncryptionBoxEncrypt = {
    data: string
}

function encryption_box_encrypt(
    params: ParamsOfEncryptionBoxEncrypt,
): Promise<ResultOfEncryptionBoxEncrypt>;

function encryption_box_encrypt_sync(
    params: ParamsOfEncryptionBoxEncrypt,
): ResultOfEncryptionBoxEncrypt;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `encryption_box`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Encryption box handle
* `data`: *string* – Data to be encrypted, encoded in Base64

#### Result

* `data`: *string* – Encrypted data, encoded in Base64.\
  Padded to cipher block size

### encryption\_box\_decrypt

Decrypts data using given encryption box Note.

Block cipher algorithms pad data to cipher block size so encrypted data can be longer then original data. Client should store the original data size after encryption and use it after decryption to retrieve the original data from decrypted data.

```ts
type ParamsOfEncryptionBoxDecrypt = {
    encryption_box: EncryptionBoxHandle,
    data: string
}

type ResultOfEncryptionBoxDecrypt = {
    data: string
}

function encryption_box_decrypt(
    params: ParamsOfEncryptionBoxDecrypt,
): Promise<ResultOfEncryptionBoxDecrypt>;

function encryption_box_decrypt_sync(
    params: ParamsOfEncryptionBoxDecrypt,
): ResultOfEncryptionBoxDecrypt;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `encryption_box`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Encryption box handle
* `data`: *string* – Data to be decrypted, encoded in Base64

#### Result

* `data`: *string* – Decrypted data, encoded in Base64.

### create\_encryption\_box

Creates encryption box with specified algorithm

```ts
type ParamsOfCreateEncryptionBox = {
    algorithm: EncryptionAlgorithm
}

type RegisteredEncryptionBox = {
    handle: EncryptionBoxHandle
}

function create_encryption_box(
    params: ParamsOfCreateEncryptionBox,
): Promise<RegisteredEncryptionBox>;

function create_encryption_box_sync(
    params: ParamsOfCreateEncryptionBox,
): RegisteredEncryptionBox;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `algorithm`: [*EncryptionAlgorithm*](#encryptionalgorithm) – Encryption algorithm specifier including cipher parameters (key, IV, etc)

#### Result

* `handle`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Handle of the encryption box.

## Types

### CryptoErrorCode

```ts
enum CryptoErrorCode {
    InvalidPublicKey = 100,
    InvalidSecretKey = 101,
    InvalidKey = 102,
    InvalidFactorizeChallenge = 106,
    InvalidBigInt = 107,
    ScryptFailed = 108,
    InvalidKeySize = 109,
    NaclSecretBoxFailed = 110,
    NaclBoxFailed = 111,
    NaclSignFailed = 112,
    Bip39InvalidEntropy = 113,
    Bip39InvalidPhrase = 114,
    Bip32InvalidKey = 115,
    Bip32InvalidDerivePath = 116,
    Bip39InvalidDictionary = 117,
    Bip39InvalidWordCount = 118,
    MnemonicGenerationFailed = 119,
    MnemonicFromEntropyFailed = 120,
    SigningBoxNotRegistered = 121,
    InvalidSignature = 122,
    EncryptionBoxNotRegistered = 123,
    InvalidIvSize = 124,
    UnsupportedCipherMode = 125,
    CannotCreateCipher = 126,
    EncryptDataError = 127,
    DecryptDataError = 128,
    IvRequired = 129,
    CryptoBoxNotRegistered = 130,
    InvalidCryptoBoxType = 131,
    CryptoBoxSecretSerializationError = 132,
    CryptoBoxSecretDeserializationError = 133,
    InvalidNonceSize = 134
}
```

One of the following value:

* `InvalidPublicKey = 100`
* `InvalidSecretKey = 101`
* `InvalidKey = 102`
* `InvalidFactorizeChallenge = 106`
* `InvalidBigInt = 107`
* `ScryptFailed = 108`
* `InvalidKeySize = 109`
* `NaclSecretBoxFailed = 110`
* `NaclBoxFailed = 111`
* `NaclSignFailed = 112`
* `Bip39InvalidEntropy = 113`
* `Bip39InvalidPhrase = 114`
* `Bip32InvalidKey = 115`
* `Bip32InvalidDerivePath = 116`
* `Bip39InvalidDictionary = 117`
* `Bip39InvalidWordCount = 118`
* `MnemonicGenerationFailed = 119`
* `MnemonicFromEntropyFailed = 120`
* `SigningBoxNotRegistered = 121`
* `InvalidSignature = 122`
* `EncryptionBoxNotRegistered = 123`
* `InvalidIvSize = 124`
* `UnsupportedCipherMode = 125`
* `CannotCreateCipher = 126`
* `EncryptDataError = 127`
* `DecryptDataError = 128`
* `IvRequired = 129`
* `CryptoBoxNotRegistered = 130`
* `InvalidCryptoBoxType = 131`
* `CryptoBoxSecretSerializationError = 132`
* `CryptoBoxSecretDeserializationError = 133`
* `InvalidNonceSize = 134`

### SigningBoxHandle

```ts
type SigningBoxHandle = number
```

### EncryptionBoxHandle

```ts
type EncryptionBoxHandle = number
```

### EncryptionBoxInfo

Encryption box information.

```ts
type EncryptionBoxInfo = {
    hdpath?: string,
    algorithm?: string,
    options?: any,
    public?: any
}
```

* `hdpath`?: *string* – Derivation path, for instance "m/44'/396'/0'/0/0"
* `algorithm`?: *string* – Cryptographic algorithm, used by this encryption box
* `options`?: *any* – Options, depends on algorithm and specific encryption box implementation
* `public`?: *any* – Public information, depends on algorithm

### EncryptionAlgorithmAESVariant

```ts
type EncryptionAlgorithmAESVariant = {
    value: AesParamsEB
}
```

* `value`: [*AesParamsEB*](#aesparamseb)

### EncryptionAlgorithmChaCha20Variant

```ts
type EncryptionAlgorithmChaCha20Variant = {
    value: ChaCha20ParamsEB
}
```

* `value`: [*ChaCha20ParamsEB*](#chacha20paramseb)

### EncryptionAlgorithmNaclBoxVariant

```ts
type EncryptionAlgorithmNaclBoxVariant = {
    value: NaclBoxParamsEB
}
```

* `value`: [*NaclBoxParamsEB*](#naclboxparamseb)

### EncryptionAlgorithmNaclSecretBoxVariant

```ts
type EncryptionAlgorithmNaclSecretBoxVariant = {
    value: NaclSecretBoxParamsEB
}
```

* `value`: [*NaclSecretBoxParamsEB*](#naclsecretboxparamseb)

### EncryptionAlgorithm

```ts
type EncryptionAlgorithm = ({
    type: 'AES'
} & EncryptionAlgorithmAESVariant) | ({
    type: 'ChaCha20'
} & EncryptionAlgorithmChaCha20Variant) | ({
    type: 'NaclBox'
} & EncryptionAlgorithmNaclBoxVariant) | ({
    type: 'NaclSecretBox'
} & EncryptionAlgorithmNaclSecretBoxVariant)
```

Depends on value of the `type` field.

When *type* is *'AES'*

* `value`: [*AesParamsEB*](#aesparamseb)

When *type* is *'ChaCha20'*

* `value`: [*ChaCha20ParamsEB*](#chacha20paramseb)

When *type* is *'NaclBox'*

* `value`: [*NaclBoxParamsEB*](#naclboxparamseb)

When *type* is *'NaclSecretBox'*

* `value`: [*NaclSecretBoxParamsEB*](#naclsecretboxparamseb)

Variant constructors:

```ts
function encryptionAlgorithmAES(value: AesParamsEB): EncryptionAlgorithm;
function encryptionAlgorithmChaCha20(value: ChaCha20ParamsEB): EncryptionAlgorithm;
function encryptionAlgorithmNaclBox(value: NaclBoxParamsEB): EncryptionAlgorithm;
function encryptionAlgorithmNaclSecretBox(value: NaclSecretBoxParamsEB): EncryptionAlgorithm;
```

### CipherMode

```ts
enum CipherMode {
    CBC = "CBC",
    CFB = "CFB",
    CTR = "CTR",
    ECB = "ECB",
    OFB = "OFB"
}
```

One of the following value:

* `CBC = "CBC"`
* `CFB = "CFB"`
* `CTR = "CTR"`
* `ECB = "ECB"`
* `OFB = "OFB"`

### AesParamsEB

```ts
type AesParamsEB = {
    mode: CipherMode,
    key: string,
    iv?: string
}
```

* `mode`: [*CipherMode*](#ciphermode)
* `key`: *string*
* `iv`?: *string*

### AesInfo

```ts
type AesInfo = {
    mode: CipherMode,
    iv?: string
}
```

* `mode`: [*CipherMode*](#ciphermode)
* `iv`?: *string*

### ChaCha20ParamsEB

```ts
type ChaCha20ParamsEB = {
    key: string,
    nonce: string
}
```

* `key`: *string* – 256-bit key.\
  Must be encoded with `hex`.
* `nonce`: *string* – 96-bit nonce.\
  Must be encoded with `hex`.

### NaclBoxParamsEB

```ts
type NaclBoxParamsEB = {
    their_public: string,
    secret: string,
    nonce: string
}
```

* `their_public`: *string* – 256-bit key.\
  Must be encoded with `hex`.
* `secret`: *string* – 256-bit key.\
  Must be encoded with `hex`.
* `nonce`: *string* – 96-bit nonce.\
  Must be encoded with `hex`.

### NaclSecretBoxParamsEB

```ts
type NaclSecretBoxParamsEB = {
    key: string,
    nonce: string
}
```

* `key`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string
* `nonce`: *string* – Nonce in `hex`

### CryptoBoxSecretRandomSeedPhraseVariant

Creates Crypto Box from a random seed phrase. This option can be used if a developer doesn't want the seed phrase to leave the core library's memory, where it is stored encrypted.

This type should be used upon the first wallet initialization, all further initializations should use `EncryptedSecret` type instead.

Get `encrypted_secret` with `get_crypto_box_info` function and store it on your side.

```ts
type CryptoBoxSecretRandomSeedPhraseVariant = {
    dictionary: MnemonicDictionary,
    wordcount: number
}
```

* `dictionary`: [*MnemonicDictionary*](#mnemonicdictionary)
* `wordcount`: *number*

### CryptoBoxSecretPredefinedSeedPhraseVariant

Restores crypto box instance from an existing seed phrase. This type should be used when Crypto Box is initialized from a seed phrase, entered by a user.

This type should be used only upon the first wallet initialization, all further initializations should use `EncryptedSecret` type instead.

Get `encrypted_secret` with `get_crypto_box_info` function and store it on your side.

```ts
type CryptoBoxSecretPredefinedSeedPhraseVariant = {
    phrase: string,
    dictionary: MnemonicDictionary,
    wordcount: number
}
```

* `phrase`: *string*
* `dictionary`: [*MnemonicDictionary*](#mnemonicdictionary)
* `wordcount`: *number*

### CryptoBoxSecretEncryptedSecretVariant

Use this type for wallet reinitializations, when you already have `encrypted_secret` on hands. To get `encrypted_secret`, use `get_crypto_box_info` function after you initialized your crypto box for the first time.

It is an object, containing seed phrase or private key, encrypted with `secret_encryption_salt` and password from `password_provider`.

Note that if you want to change salt or password provider, then you need to reinitialize the wallet with `PredefinedSeedPhrase`, then get `EncryptedSecret` via `get_crypto_box_info`, store it somewhere, and only after that initialize the wallet with `EncryptedSecret` type.

```ts
type CryptoBoxSecretEncryptedSecretVariant = {
    encrypted_secret: string
}
```

* `encrypted_secret`: *string* – It is an object, containing encrypted seed phrase or private key (now we support only seed phrase).

### CryptoBoxSecret

Crypto Box Secret.

```ts
type CryptoBoxSecret = ({
    type: 'RandomSeedPhrase'
} & CryptoBoxSecretRandomSeedPhraseVariant) | ({
    type: 'PredefinedSeedPhrase'
} & CryptoBoxSecretPredefinedSeedPhraseVariant) | ({
    type: 'EncryptedSecret'
} & CryptoBoxSecretEncryptedSecretVariant)
```

Depends on value of the `type` field.

When *type* is *'RandomSeedPhrase'*

Creates Crypto Box from a random seed phrase. This option can be used if a developer doesn't want the seed phrase to leave the core library's memory, where it is stored encrypted.

This type should be used upon the first wallet initialization, all further initializations should use `EncryptedSecret` type instead.

Get `encrypted_secret` with `get_crypto_box_info` function and store it on your side.

* `dictionary`: [*MnemonicDictionary*](#mnemonicdictionary)
* `wordcount`: *number*

When *type* is *'PredefinedSeedPhrase'*

Restores crypto box instance from an existing seed phrase. This type should be used when Crypto Box is initialized from a seed phrase, entered by a user.

This type should be used only upon the first wallet initialization, all further initializations should use `EncryptedSecret` type instead.

Get `encrypted_secret` with `get_crypto_box_info` function and store it on your side.

* `phrase`: *string*
* `dictionary`: [*MnemonicDictionary*](#mnemonicdictionary)
* `wordcount`: *number*

When *type* is *'EncryptedSecret'*

Use this type for wallet reinitializations, when you already have `encrypted_secret` on hands. To get `encrypted_secret`, use `get_crypto_box_info` function after you initialized your crypto box for the first time.

It is an object, containing seed phrase or private key, encrypted with `secret_encryption_salt` and password from `password_provider`.

Note that if you want to change salt or password provider, then you need to reinitialize the wallet with `PredefinedSeedPhrase`, then get `EncryptedSecret` via `get_crypto_box_info`, store it somewhere, and only after that initialize the wallet with `EncryptedSecret` type.

* `encrypted_secret`: *string* – It is an object, containing encrypted seed phrase or private key (now we support only seed phrase).

Variant constructors:

```ts
function cryptoBoxSecretRandomSeedPhrase(dictionary: MnemonicDictionary, wordcount: number): CryptoBoxSecret;
function cryptoBoxSecretPredefinedSeedPhrase(phrase: string, dictionary: MnemonicDictionary, wordcount: number): CryptoBoxSecret;
function cryptoBoxSecretEncryptedSecret(encrypted_secret: string): CryptoBoxSecret;
```

### CryptoBoxHandle

```ts
type CryptoBoxHandle = number
```

### BoxEncryptionAlgorithmChaCha20Variant

```ts
type BoxEncryptionAlgorithmChaCha20Variant = {
    value: ChaCha20ParamsCB
}
```

* `value`: [*ChaCha20ParamsCB*](#chacha20paramscb)

### BoxEncryptionAlgorithmNaclBoxVariant

```ts
type BoxEncryptionAlgorithmNaclBoxVariant = {
    value: NaclBoxParamsCB
}
```

* `value`: [*NaclBoxParamsCB*](#naclboxparamscb)

### BoxEncryptionAlgorithmNaclSecretBoxVariant

```ts
type BoxEncryptionAlgorithmNaclSecretBoxVariant = {
    value: NaclSecretBoxParamsCB
}
```

* `value`: [*NaclSecretBoxParamsCB*](#naclsecretboxparamscb)

### BoxEncryptionAlgorithm

```ts
type BoxEncryptionAlgorithm = ({
    type: 'ChaCha20'
} & BoxEncryptionAlgorithmChaCha20Variant) | ({
    type: 'NaclBox'
} & BoxEncryptionAlgorithmNaclBoxVariant) | ({
    type: 'NaclSecretBox'
} & BoxEncryptionAlgorithmNaclSecretBoxVariant)
```

Depends on value of the `type` field.

When *type* is *'ChaCha20'*

* `value`: [*ChaCha20ParamsCB*](#chacha20paramscb)

When *type* is *'NaclBox'*

* `value`: [*NaclBoxParamsCB*](#naclboxparamscb)

When *type* is *'NaclSecretBox'*

* `value`: [*NaclSecretBoxParamsCB*](#naclsecretboxparamscb)

Variant constructors:

```ts
function boxEncryptionAlgorithmChaCha20(value: ChaCha20ParamsCB): BoxEncryptionAlgorithm;
function boxEncryptionAlgorithmNaclBox(value: NaclBoxParamsCB): BoxEncryptionAlgorithm;
function boxEncryptionAlgorithmNaclSecretBox(value: NaclSecretBoxParamsCB): BoxEncryptionAlgorithm;
```

### ChaCha20ParamsCB

```ts
type ChaCha20ParamsCB = {
    nonce: string
}
```

* `nonce`: *string* – 96-bit nonce.\
  Must be encoded with `hex`.

### NaclBoxParamsCB

```ts
type NaclBoxParamsCB = {
    their_public: string,
    nonce: string
}
```

* `their_public`: *string* – 256-bit key.\
  Must be encoded with `hex`.
* `nonce`: *string* – 96-bit nonce.\
  Must be encoded with `hex`.

### NaclSecretBoxParamsCB

```ts
type NaclSecretBoxParamsCB = {
    nonce: string
}
```

* `nonce`: *string* – Nonce in `hex`

### MnemonicDictionary

```ts
enum MnemonicDictionary {
    Ton = 0,
    English = 1,
    ChineseSimplified = 2,
    ChineseTraditional = 3,
    French = 4,
    Italian = 5,
    Japanese = 6,
    Korean = 7,
    Spanish = 8
}
```

One of the following value:

* `Ton = 0` – TON compatible dictionary
* `English = 1` – English BIP-39 dictionary
* `ChineseSimplified = 2` – Chinese simplified BIP-39 dictionary
* `ChineseTraditional = 3` – Chinese traditional BIP-39 dictionary
* `French = 4` – French BIP-39 dictionary
* `Italian = 5` – Italian BIP-39 dictionary
* `Japanese = 6` – Japanese BIP-39 dictionary
* `Korean = 7` – Korean BIP-39 dictionary
* `Spanish = 8` – Spanish BIP-39 dictionary

### ParamsOfFactorize

```ts
type ParamsOfFactorize = {
    composite: string
}
```

* `composite`: *string* – Hexadecimal representation of u64 composite number.

### ResultOfFactorize

```ts
type ResultOfFactorize = {
    factors: string[]
}
```

* `factors`: *string\[]* – Two factors of composite or empty if composite can't be factorized.

### ParamsOfModularPower

```ts
type ParamsOfModularPower = {
    base: string,
    exponent: string,
    modulus: string
}
```

* `base`: *string* – `base` argument of calculation.
* `exponent`: *string* – `exponent` argument of calculation.
* `modulus`: *string* – `modulus` argument of calculation.

### ResultOfModularPower

```ts
type ResultOfModularPower = {
    modular_power: string
}
```

* `modular_power`: *string* – Result of modular exponentiation

### ParamsOfTonCrc16

```ts
type ParamsOfTonCrc16 = {
    data: string
}
```

* `data`: *string* – Input data for CRC calculation.\
  Encoded with `base64`.

### ResultOfTonCrc16

```ts
type ResultOfTonCrc16 = {
    crc: number
}
```

* `crc`: *number* – Calculated CRC for input data.

### ParamsOfGenerateRandomBytes

```ts
type ParamsOfGenerateRandomBytes = {
    length: number
}
```

* `length`: *number* – Size of random byte array.

### ResultOfGenerateRandomBytes

```ts
type ResultOfGenerateRandomBytes = {
    bytes: string
}
```

* `bytes`: *string* – Generated bytes encoded in `base64`.

### ParamsOfConvertPublicKeyToTonSafeFormat

```ts
type ParamsOfConvertPublicKeyToTonSafeFormat = {
    public_key: string
}
```

* `public_key`: *string* – Public key - 64 symbols hex string

### ResultOfConvertPublicKeyToTonSafeFormat

```ts
type ResultOfConvertPublicKeyToTonSafeFormat = {
    ton_public_key: string
}
```

* `ton_public_key`: *string* – Public key represented in TON safe format.

### KeyPair

```ts
type KeyPair = {
    public: string,
    secret: string
}
```

* `public`: *string* – Public key - 64 symbols hex string
* `secret`: *string* – Private key - u64 symbols hex string

### ParamsOfSign

```ts
type ParamsOfSign = {
    unsigned: string,
    keys: KeyPair
}
```

* `unsigned`: *string* – Data that must be signed encoded in `base64`.
* `keys`: [*KeyPair*](#keypair) – Sign keys.

### ResultOfSign

```ts
type ResultOfSign = {
    signed: string,
    signature: string
}
```

* `signed`: *string* – Signed data combined with signature encoded in `base64`.
* `signature`: *string* – Signature encoded in `hex`.

### ParamsOfVerifySignature

```ts
type ParamsOfVerifySignature = {
    signed: string,
    public: string
}
```

* `signed`: *string* – Signed data that must be verified encoded in `base64`.
* `public`: *string* – Signer's public key - 64 symbols hex string

### ResultOfVerifySignature

```ts
type ResultOfVerifySignature = {
    unsigned: string
}
```

* `unsigned`: *string* – Unsigned data encoded in `base64`.

### ParamsOfHash

```ts
type ParamsOfHash = {
    data: string
}
```

* `data`: *string* – Input data for hash calculation.\
  Encoded with `base64`.

### ResultOfHash

```ts
type ResultOfHash = {
    hash: string
}
```

* `hash`: *string* – Hash of input `data`.\
  Encoded with 'hex'.

### ParamsOfScrypt

```ts
type ParamsOfScrypt = {
    password: string,
    salt: string,
    log_n: number,
    r: number,
    p: number,
    dk_len: number
}
```

* `password`: *string* – The password bytes to be hashed. Must be encoded with `base64`.
* `salt`: *string* – Salt bytes that modify the hash to protect against Rainbow table attacks. Must be encoded with `base64`.
* `log_n`: *number* – CPU/memory cost parameter
* `r`: *number* – The block size parameter, which fine-tunes sequential memory read size and performance.
* `p`: *number* – Parallelization parameter.
* `dk_len`: *number* – Intended output length in octets of the derived key.

### ResultOfScrypt

```ts
type ResultOfScrypt = {
    key: string
}
```

* `key`: *string* – Derived key.\
  Encoded with `hex`.

### ParamsOfNaclSignKeyPairFromSecret

```ts
type ParamsOfNaclSignKeyPairFromSecret = {
    secret: string
}
```

* `secret`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

### ParamsOfNaclSign

```ts
type ParamsOfNaclSign = {
    unsigned: string,
    secret: string
}
```

* `unsigned`: *string* – Data that must be signed encoded in `base64`.
* `secret`: *string* – Signer's secret key - unprefixed 0-padded to 128 symbols hex string (concatenation of 64 symbols secret and 64 symbols public keys). See `nacl_sign_keypair_from_secret_key`.

### ResultOfNaclSign

```ts
type ResultOfNaclSign = {
    signed: string
}
```

* `signed`: *string* – Signed data, encoded in `base64`.

### ParamsOfNaclSignOpen

```ts
type ParamsOfNaclSignOpen = {
    signed: string,
    public: string
}
```

* `signed`: *string* – Signed data that must be unsigned.\
  Encoded with `base64`.
* `public`: *string* – Signer's public key - unprefixed 0-padded to 64 symbols hex string

### ResultOfNaclSignOpen

```ts
type ResultOfNaclSignOpen = {
    unsigned: string
}
```

* `unsigned`: *string* – Unsigned data, encoded in `base64`.

### ResultOfNaclSignDetached

```ts
type ResultOfNaclSignDetached = {
    signature: string
}
```

* `signature`: *string* – Signature encoded in `hex`.

### ParamsOfNaclSignDetachedVerify

```ts
type ParamsOfNaclSignDetachedVerify = {
    unsigned: string,
    signature: string,
    public: string
}
```

* `unsigned`: *string* – Unsigned data that must be verified.\
  Encoded with `base64`.
* `signature`: *string* – Signature that must be verified.\
  Encoded with `hex`.
* `public`: *string* – Signer's public key - unprefixed 0-padded to 64 symbols hex string.

### ResultOfNaclSignDetachedVerify

```ts
type ResultOfNaclSignDetachedVerify = {
    succeeded: boolean
}
```

* `succeeded`: *boolean* – `true` if verification succeeded or `false` if it failed

### ParamsOfNaclBoxKeyPairFromSecret

```ts
type ParamsOfNaclBoxKeyPairFromSecret = {
    secret: string
}
```

* `secret`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

### ParamsOfNaclBox

```ts
type ParamsOfNaclBox = {
    decrypted: string,
    nonce: string,
    their_public: string,
    secret: string
}
```

* `decrypted`: *string* – Data that must be encrypted encoded in `base64`.
* `nonce`: *string* – Nonce, encoded in `hex`
* `their_public`: *string* – Receiver's public key - unprefixed 0-padded to 64 symbols hex string
* `secret`: *string* – Sender's private key - unprefixed 0-padded to 64 symbols hex string

### ResultOfNaclBox

```ts
type ResultOfNaclBox = {
    encrypted: string
}
```

* `encrypted`: *string* – Encrypted data encoded in `base64`.

### ParamsOfNaclBoxOpen

```ts
type ParamsOfNaclBoxOpen = {
    encrypted: string,
    nonce: string,
    their_public: string,
    secret: string
}
```

* `encrypted`: *string* – Data that must be decrypted.\
  Encoded with `base64`.
* `nonce`: *string* – Nonce
* `their_public`: *string* – Sender's public key - unprefixed 0-padded to 64 symbols hex string
* `secret`: *string* – Receiver's private key - unprefixed 0-padded to 64 symbols hex string

### ResultOfNaclBoxOpen

```ts
type ResultOfNaclBoxOpen = {
    decrypted: string
}
```

* `decrypted`: *string* – Decrypted data encoded in `base64`.

### ParamsOfNaclSecretBox

```ts
type ParamsOfNaclSecretBox = {
    decrypted: string,
    nonce: string,
    key: string
}
```

* `decrypted`: *string* – Data that must be encrypted.\
  Encoded with `base64`.
* `nonce`: *string* – Nonce in `hex`
* `key`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

### ParamsOfNaclSecretBoxOpen

```ts
type ParamsOfNaclSecretBoxOpen = {
    encrypted: string,
    nonce: string,
    key: string
}
```

* `encrypted`: *string* – Data that must be decrypted.\
  Encoded with `base64`.
* `nonce`: *string* – Nonce in `hex`
* `key`: *string* – Secret key - unprefixed 0-padded to 64 symbols hex string

### ParamsOfMnemonicWords

```ts
type ParamsOfMnemonicWords = {
    dictionary?: MnemonicDictionary
}
```

* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier

### ResultOfMnemonicWords

```ts
type ResultOfMnemonicWords = {
    words: string
}
```

* `words`: *string* – The list of mnemonic words

### ParamsOfMnemonicFromRandom

```ts
type ParamsOfMnemonicFromRandom = {
    dictionary?: MnemonicDictionary,
    word_count?: number
}
```

* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Mnemonic word count

### ResultOfMnemonicFromRandom

```ts
type ResultOfMnemonicFromRandom = {
    phrase: string
}
```

* `phrase`: *string* – String of mnemonic words

### ParamsOfMnemonicFromEntropy

```ts
type ParamsOfMnemonicFromEntropy = {
    entropy: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}
```

* `entropy`: *string* – Entropy bytes.\
  Hex encoded.
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Mnemonic word count

### ResultOfMnemonicFromEntropy

```ts
type ResultOfMnemonicFromEntropy = {
    phrase: string
}
```

* `phrase`: *string* – Phrase

### ParamsOfMnemonicVerify

```ts
type ParamsOfMnemonicVerify = {
    phrase: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}
```

* `phrase`: *string* – Phrase
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Word count

### ResultOfMnemonicVerify

```ts
type ResultOfMnemonicVerify = {
    valid: boolean
}
```

* `valid`: *boolean* – Flag indicating if the mnemonic is valid or not

### ParamsOfMnemonicDeriveSignKeys

```ts
type ParamsOfMnemonicDeriveSignKeys = {
    phrase: string,
    path?: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}
```

* `phrase`: *string* – Phrase
* `path`?: *string* – Derivation path, for instance "m/44'/396'/0'/0/0"
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Word count

### ParamsOfHDKeyXPrvFromMnemonic

```ts
type ParamsOfHDKeyXPrvFromMnemonic = {
    phrase: string,
    dictionary?: MnemonicDictionary,
    word_count?: number
}
```

* `phrase`: *string* – String with seed phrase
* `dictionary`?: [*MnemonicDictionary*](#mnemonicdictionary) – Dictionary identifier
* `word_count`?: *number* – Mnemonic word count

### ResultOfHDKeyXPrvFromMnemonic

```ts
type ResultOfHDKeyXPrvFromMnemonic = {
    xprv: string
}
```

* `xprv`: *string* – Serialized extended master private key

### ParamsOfHDKeyDeriveFromXPrv

```ts
type ParamsOfHDKeyDeriveFromXPrv = {
    xprv: string,
    child_index: number,
    hardened: boolean
}
```

* `xprv`: *string* – Serialized extended private key
* `child_index`: *number* – Child index (see BIP-0032)
* `hardened`: *boolean* – Indicates the derivation of hardened/not-hardened key (see BIP-0032)

### ResultOfHDKeyDeriveFromXPrv

```ts
type ResultOfHDKeyDeriveFromXPrv = {
    xprv: string
}
```

* `xprv`: *string* – Serialized extended private key

### ParamsOfHDKeyDeriveFromXPrvPath

```ts
type ParamsOfHDKeyDeriveFromXPrvPath = {
    xprv: string,
    path: string
}
```

* `xprv`: *string* – Serialized extended private key
* `path`: *string* – Derivation path, for instance "m/44'/396'/0'/0/0"

### ResultOfHDKeyDeriveFromXPrvPath

```ts
type ResultOfHDKeyDeriveFromXPrvPath = {
    xprv: string
}
```

* `xprv`: *string* – Derived serialized extended private key

### ParamsOfHDKeySecretFromXPrv

```ts
type ParamsOfHDKeySecretFromXPrv = {
    xprv: string
}
```

* `xprv`: *string* – Serialized extended private key

### ResultOfHDKeySecretFromXPrv

```ts
type ResultOfHDKeySecretFromXPrv = {
    secret: string
}
```

* `secret`: *string* – Private key - 64 symbols hex string

### ParamsOfHDKeyPublicFromXPrv

```ts
type ParamsOfHDKeyPublicFromXPrv = {
    xprv: string
}
```

* `xprv`: *string* – Serialized extended private key

### ResultOfHDKeyPublicFromXPrv

```ts
type ResultOfHDKeyPublicFromXPrv = {
    public: string
}
```

* `public`: *string* – Public key - 64 symbols hex string

### ParamsOfChaCha20

```ts
type ParamsOfChaCha20 = {
    data: string,
    key: string,
    nonce: string
}
```

* `data`: *string* – Source data to be encrypted or decrypted.\
  Must be encoded with `base64`.
* `key`: *string* – 256-bit key.\
  Must be encoded with `hex`.
* `nonce`: *string* – 96-bit nonce.\
  Must be encoded with `hex`.

### ResultOfChaCha20

```ts
type ResultOfChaCha20 = {
    data: string
}
```

* `data`: *string* – Encrypted/decrypted data.\
  Encoded with `base64`.

### ParamsOfCreateCryptoBox

```ts
type ParamsOfCreateCryptoBox = {
    secret_encryption_salt: string,
    secret: CryptoBoxSecret
}
```

* `secret_encryption_salt`: *string* – Salt used for secret encryption. For example, a mobile device can use device ID as salt.
* `secret`: [*CryptoBoxSecret*](#cryptoboxsecret) – Cryptobox secret

### RegisteredCryptoBox

```ts
type RegisteredCryptoBox = {
    handle: CryptoBoxHandle
}
```

* `handle`: [*CryptoBoxHandle*](#cryptoboxhandle)

### ParamsOfAppPasswordProviderGetPasswordVariant

```ts
type ParamsOfAppPasswordProviderGetPasswordVariant = {
    encryption_public_key: string
}
```

* `encryption_public_key`: *string* – Temporary library pubkey, that is used on application side for password encryption, along with application temporary private key and nonce. Used for password decryption on library side.

### ParamsOfAppPasswordProvider

Interface that provides a callback that returns an encrypted password, used for cryptobox secret encryption

To secure the password while passing it from application to the library, the library generates a temporary key pair, passes the pubkey to the passwordProvider, decrypts the received password with private key, and deletes the key pair right away.

Application should generate a temporary nacl\_box\_keypair and encrypt the password with naclbox function using nacl\_box\_keypair.secret and encryption\_public\_key keys + nonce = 24-byte prefix of encryption\_public\_key.

```ts
type ParamsOfAppPasswordProvider = ({
    type: 'GetPassword'
} & ParamsOfAppPasswordProviderGetPasswordVariant)
```

Depends on value of the `type` field.

When *type* is *'GetPassword'*

* `encryption_public_key`: *string* – Temporary library pubkey, that is used on application side for password encryption, along with application temporary private key and nonce. Used for password decryption on library side.

Variant constructors:

```ts
function paramsOfAppPasswordProviderGetPassword(encryption_public_key: string): ParamsOfAppPasswordProvider;
```

### ResultOfAppPasswordProviderGetPasswordVariant

```ts
type ResultOfAppPasswordProviderGetPasswordVariant = {
    encrypted_password: string,
    app_encryption_pubkey: string
}
```

* `encrypted_password`: *string* – Password, encrypted and encoded to base64. Crypto box uses this password to decrypt its secret (seed phrase).
* `app_encryption_pubkey`: *string* – Hex encoded public key of a temporary key pair, used for password encryption on application side.\
  Used together with `encryption_public_key` to decode `encrypted_password`.

### ResultOfAppPasswordProvider

```ts
type ResultOfAppPasswordProvider = ({
    type: 'GetPassword'
} & ResultOfAppPasswordProviderGetPasswordVariant)
```

Depends on value of the `type` field.

When *type* is *'GetPassword'*

* `encrypted_password`: *string* – Password, encrypted and encoded to base64. Crypto box uses this password to decrypt its secret (seed phrase).
* `app_encryption_pubkey`: *string* – Hex encoded public key of a temporary key pair, used for password encryption on application side.\
  Used together with `encryption_public_key` to decode `encrypted_password`.

Variant constructors:

```ts
function resultOfAppPasswordProviderGetPassword(encrypted_password: string, app_encryption_pubkey: string): ResultOfAppPasswordProvider;
```

### ResultOfGetCryptoBoxInfo

```ts
type ResultOfGetCryptoBoxInfo = {
    encrypted_secret: string
}
```

* `encrypted_secret`: *string* – Secret (seed phrase) encrypted with salt and password.

### ResultOfGetCryptoBoxSeedPhrase

```ts
type ResultOfGetCryptoBoxSeedPhrase = {
    phrase: string,
    dictionary: MnemonicDictionary,
    wordcount: number
}
```

* `phrase`: *string*
* `dictionary`: [*MnemonicDictionary*](#mnemonicdictionary)
* `wordcount`: *number*

### ParamsOfGetSigningBoxFromCryptoBox

```ts
type ParamsOfGetSigningBoxFromCryptoBox = {
    handle: number,
    hdpath?: string,
    secret_lifetime?: number
}
```

* `handle`: *number* – Crypto Box Handle.
* `hdpath`?: *string* – HD key derivation path.\
  By default, Everscale HD path is used.
* `secret_lifetime`?: *number* – Store derived secret for this lifetime (in ms). The timer starts after each signing box operation. Secrets will be deleted immediately after each signing box operation, if this value is not set.

### RegisteredSigningBox

```ts
type RegisteredSigningBox = {
    handle: SigningBoxHandle
}
```

* `handle`: [*SigningBoxHandle*](#signingboxhandle) – Handle of the signing box.

### ParamsOfGetEncryptionBoxFromCryptoBox

```ts
type ParamsOfGetEncryptionBoxFromCryptoBox = {
    handle: number,
    hdpath?: string,
    algorithm: BoxEncryptionAlgorithm,
    secret_lifetime?: number
}
```

* `handle`: *number* – Crypto Box Handle.
* `hdpath`?: *string* – HD key derivation path.\
  By default, Everscale HD path is used.
* `algorithm`: [*BoxEncryptionAlgorithm*](#boxencryptionalgorithm) – Encryption algorithm.
* `secret_lifetime`?: *number* – Store derived secret for encryption algorithm for this lifetime (in ms). The timer starts after each encryption box operation. Secrets will be deleted (overwritten with zeroes) after each encryption operation, if this value is not set.

### RegisteredEncryptionBox

```ts
type RegisteredEncryptionBox = {
    handle: EncryptionBoxHandle
}
```

* `handle`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Handle of the encryption box.

### ParamsOfAppSigningBoxGetPublicKeyVariant

Get signing box public key

```ts
type ParamsOfAppSigningBoxGetPublicKeyVariant = {

}
```

### ParamsOfAppSigningBoxSignVariant

Sign data

```ts
type ParamsOfAppSigningBoxSignVariant = {
    unsigned: string
}
```

* `unsigned`: *string* – Data to sign encoded as base64

### ParamsOfAppSigningBox

Signing box callbacks.

```ts
type ParamsOfAppSigningBox = ({
    type: 'GetPublicKey'
} & ParamsOfAppSigningBoxGetPublicKeyVariant) | ({
    type: 'Sign'
} & ParamsOfAppSigningBoxSignVariant)
```

Depends on value of the `type` field.

When *type* is *'GetPublicKey'*

Get signing box public key

When *type* is *'Sign'*

Sign data

* `unsigned`: *string* – Data to sign encoded as base64

Variant constructors:

```ts
function paramsOfAppSigningBoxGetPublicKey(): ParamsOfAppSigningBox;
function paramsOfAppSigningBoxSign(unsigned: string): ParamsOfAppSigningBox;
```

### ResultOfAppSigningBoxGetPublicKeyVariant

Result of getting public key

```ts
type ResultOfAppSigningBoxGetPublicKeyVariant = {
    public_key: string
}
```

* `public_key`: *string* – Signing box public key

### ResultOfAppSigningBoxSignVariant

Result of signing data

```ts
type ResultOfAppSigningBoxSignVariant = {
    signature: string
}
```

* `signature`: *string* – Data signature encoded as hex

### ResultOfAppSigningBox

Returning values from signing box callbacks.

```ts
type ResultOfAppSigningBox = ({
    type: 'GetPublicKey'
} & ResultOfAppSigningBoxGetPublicKeyVariant) | ({
    type: 'Sign'
} & ResultOfAppSigningBoxSignVariant)
```

Depends on value of the `type` field.

When *type* is *'GetPublicKey'*

Result of getting public key

* `public_key`: *string* – Signing box public key

When *type* is *'Sign'*

Result of signing data

* `signature`: *string* – Data signature encoded as hex

Variant constructors:

```ts
function resultOfAppSigningBoxGetPublicKey(public_key: string): ResultOfAppSigningBox;
function resultOfAppSigningBoxSign(signature: string): ResultOfAppSigningBox;
```

### ResultOfSigningBoxGetPublicKey

```ts
type ResultOfSigningBoxGetPublicKey = {
    pubkey: string
}
```

* `pubkey`: *string* – Public key of signing box.\
  Encoded with hex

### ParamsOfSigningBoxSign

```ts
type ParamsOfSigningBoxSign = {
    signing_box: SigningBoxHandle,
    unsigned: string
}
```

* `signing_box`: [*SigningBoxHandle*](#signingboxhandle) – Signing Box handle.
* `unsigned`: *string* – Unsigned user data.\
  Must be encoded with `base64`.

### ResultOfSigningBoxSign

```ts
type ResultOfSigningBoxSign = {
    signature: string
}
```

* `signature`: *string* – Data signature.\
  Encoded with `hex`.

### ParamsOfAppEncryptionBoxGetInfoVariant

Get encryption box info

```ts
type ParamsOfAppEncryptionBoxGetInfoVariant = {

}
```

### ParamsOfAppEncryptionBoxEncryptVariant

Encrypt data

```ts
type ParamsOfAppEncryptionBoxEncryptVariant = {
    data: string
}
```

* `data`: *string* – Data, encoded in Base64

### ParamsOfAppEncryptionBoxDecryptVariant

Decrypt data

```ts
type ParamsOfAppEncryptionBoxDecryptVariant = {
    data: string
}
```

* `data`: *string* – Data, encoded in Base64

### ParamsOfAppEncryptionBox

Interface for data encryption/decryption

```ts
type ParamsOfAppEncryptionBox = ({
    type: 'GetInfo'
} & ParamsOfAppEncryptionBoxGetInfoVariant) | ({
    type: 'Encrypt'
} & ParamsOfAppEncryptionBoxEncryptVariant) | ({
    type: 'Decrypt'
} & ParamsOfAppEncryptionBoxDecryptVariant)
```

Depends on value of the `type` field.

When *type* is *'GetInfo'*

Get encryption box info

When *type* is *'Encrypt'*

Encrypt data

* `data`: *string* – Data, encoded in Base64

When *type* is *'Decrypt'*

Decrypt data

* `data`: *string* – Data, encoded in Base64

Variant constructors:

```ts
function paramsOfAppEncryptionBoxGetInfo(): ParamsOfAppEncryptionBox;
function paramsOfAppEncryptionBoxEncrypt(data: string): ParamsOfAppEncryptionBox;
function paramsOfAppEncryptionBoxDecrypt(data: string): ParamsOfAppEncryptionBox;
```

### ResultOfAppEncryptionBoxGetInfoVariant

Result of getting encryption box info

```ts
type ResultOfAppEncryptionBoxGetInfoVariant = {
    info: EncryptionBoxInfo
}
```

* `info`: [*EncryptionBoxInfo*](#encryptionboxinfo)

### ResultOfAppEncryptionBoxEncryptVariant

Result of encrypting data

```ts
type ResultOfAppEncryptionBoxEncryptVariant = {
    data: string
}
```

* `data`: *string* – Encrypted data, encoded in Base64

### ResultOfAppEncryptionBoxDecryptVariant

Result of decrypting data

```ts
type ResultOfAppEncryptionBoxDecryptVariant = {
    data: string
}
```

* `data`: *string* – Decrypted data, encoded in Base64

### ResultOfAppEncryptionBox

Returning values from signing box callbacks.

```ts
type ResultOfAppEncryptionBox = ({
    type: 'GetInfo'
} & ResultOfAppEncryptionBoxGetInfoVariant) | ({
    type: 'Encrypt'
} & ResultOfAppEncryptionBoxEncryptVariant) | ({
    type: 'Decrypt'
} & ResultOfAppEncryptionBoxDecryptVariant)
```

Depends on value of the `type` field.

When *type* is *'GetInfo'*

Result of getting encryption box info

* `info`: [*EncryptionBoxInfo*](#encryptionboxinfo)

When *type* is *'Encrypt'*

Result of encrypting data

* `data`: *string* – Encrypted data, encoded in Base64

When *type* is *'Decrypt'*

Result of decrypting data

* `data`: *string* – Decrypted data, encoded in Base64

Variant constructors:

```ts
function resultOfAppEncryptionBoxGetInfo(info: EncryptionBoxInfo): ResultOfAppEncryptionBox;
function resultOfAppEncryptionBoxEncrypt(data: string): ResultOfAppEncryptionBox;
function resultOfAppEncryptionBoxDecrypt(data: string): ResultOfAppEncryptionBox;
```

### ParamsOfEncryptionBoxGetInfo

```ts
type ParamsOfEncryptionBoxGetInfo = {
    encryption_box: EncryptionBoxHandle
}
```

* `encryption_box`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Encryption box handle

### ResultOfEncryptionBoxGetInfo

```ts
type ResultOfEncryptionBoxGetInfo = {
    info: EncryptionBoxInfo
}
```

* `info`: [*EncryptionBoxInfo*](#encryptionboxinfo) – Encryption box information

### ParamsOfEncryptionBoxEncrypt

```ts
type ParamsOfEncryptionBoxEncrypt = {
    encryption_box: EncryptionBoxHandle,
    data: string
}
```

* `encryption_box`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Encryption box handle
* `data`: *string* – Data to be encrypted, encoded in Base64

### ResultOfEncryptionBoxEncrypt

```ts
type ResultOfEncryptionBoxEncrypt = {
    data: string
}
```

* `data`: *string* – Encrypted data, encoded in Base64.\
  Padded to cipher block size

### ParamsOfEncryptionBoxDecrypt

```ts
type ParamsOfEncryptionBoxDecrypt = {
    encryption_box: EncryptionBoxHandle,
    data: string
}
```

* `encryption_box`: [*EncryptionBoxHandle*](#encryptionboxhandle) – Encryption box handle
* `data`: *string* – Data to be decrypted, encoded in Base64

### ResultOfEncryptionBoxDecrypt

```ts
type ResultOfEncryptionBoxDecrypt = {
    data: string
}
```

* `data`: *string* – Decrypted data, encoded in Base64.

### ParamsOfCreateEncryptionBox

```ts
type ParamsOfCreateEncryptionBox = {
    algorithm: EncryptionAlgorithm
}
```

* `algorithm`: [*EncryptionAlgorithm*](#encryptionalgorithm) – Encryption algorithm specifier including cipher parameters (key, IV, etc)

### AppPasswordProvider

Interface that provides a callback that returns an encrypted password, used for cryptobox secret encryption

To secure the password while passing it from application to the library, the library generates a temporary key pair, passes the pubkey to the passwordProvider, decrypts the received password with private key, and deletes the key pair right away.

Application should generate a temporary nacl\_box\_keypair and encrypt the password with naclbox function using nacl\_box\_keypair.secret and encryption\_public\_key keys + nonce = 24-byte prefix of encryption\_public\_key.

```ts

export interface AppPasswordProvider {
    get_password(params: ParamsOfAppPasswordProviderGetPasswordVariant): Promise<ResultOfAppPasswordProviderGetPasswordVariant>,
}
```

### get\_password

```ts
type ParamsOfAppPasswordProviderGetPasswordVariant = ParamsOfAppPasswordProviderGetPasswordVariant

type ResultOfAppPasswordProviderGetPasswordVariant = ResultOfAppPasswordProviderGetPasswordVariant

function get_password(
    params: ParamsOfAppPasswordProviderGetPasswordVariant,
): Promise<ResultOfAppPasswordProviderGetPasswordVariant>;

function get_password_sync(
    params: ParamsOfAppPasswordProviderGetPasswordVariant,
): ResultOfAppPasswordProviderGetPasswordVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `encryption_public_key`: *string* – Temporary library pubkey, that is used on application side for password encryption, along with application temporary private key and nonce. Used for password decryption on library side.

#### Result

* `encrypted_password`: *string* – Password, encrypted and encoded to base64. Crypto box uses this password to decrypt its secret (seed phrase).
* `app_encryption_pubkey`: *string* – Hex encoded public key of a temporary key pair, used for password encryption on application side.\
  Used together with `encryption_public_key` to decode `encrypted_password`.

### AppSigningBox

Signing box callbacks.

```ts

export interface AppSigningBox {
    get_public_key(): Promise<ResultOfAppSigningBoxGetPublicKeyVariant>,
    sign(params: ParamsOfAppSigningBoxSignVariant): Promise<ResultOfAppSigningBoxSignVariant>,
}
```

### get\_public\_key

Get signing box public key

```ts
type ResultOfAppSigningBoxGetPublicKeyVariant = ResultOfAppSigningBoxGetPublicKeyVariant

function get_public_key(): Promise<ResultOfAppSigningBoxGetPublicKeyVariant>;

function get_public_key_sync(): ResultOfAppSigningBoxGetPublicKeyVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `public_key`: *string* – Signing box public key

### sign

Sign data

```ts
type ParamsOfAppSigningBoxSignVariant = ParamsOfAppSigningBoxSignVariant

type ResultOfAppSigningBoxSignVariant = ResultOfAppSigningBoxSignVariant

function sign(
    params: ParamsOfAppSigningBoxSignVariant,
): Promise<ResultOfAppSigningBoxSignVariant>;

function sign_sync(
    params: ParamsOfAppSigningBoxSignVariant,
): ResultOfAppSigningBoxSignVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `unsigned`: *string* – Data to sign encoded as base64

#### Result

* `signature`: *string* – Data signature encoded as hex

### AppEncryptionBox

Interface for data encryption/decryption

```ts

export interface AppEncryptionBox {
    get_info(): Promise<ResultOfAppEncryptionBoxGetInfoVariant>,
    encrypt(params: ParamsOfAppEncryptionBoxEncryptVariant): Promise<ResultOfAppEncryptionBoxEncryptVariant>,
    decrypt(params: ParamsOfAppEncryptionBoxDecryptVariant): Promise<ResultOfAppEncryptionBoxDecryptVariant>,
}
```

### get\_info

Get encryption box info

```ts
type ResultOfAppEncryptionBoxGetInfoVariant = ResultOfAppEncryptionBoxGetInfoVariant

function get_info(): Promise<ResultOfAppEncryptionBoxGetInfoVariant>;

function get_info_sync(): ResultOfAppEncryptionBoxGetInfoVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `info`: [*EncryptionBoxInfo*](#encryptionboxinfo)

### encrypt

Encrypt data

```ts
type ParamsOfAppEncryptionBoxEncryptVariant = ParamsOfAppEncryptionBoxEncryptVariant

type ResultOfAppEncryptionBoxEncryptVariant = ResultOfAppEncryptionBoxEncryptVariant

function encrypt(
    params: ParamsOfAppEncryptionBoxEncryptVariant,
): Promise<ResultOfAppEncryptionBoxEncryptVariant>;

function encrypt_sync(
    params: ParamsOfAppEncryptionBoxEncryptVariant,
): ResultOfAppEncryptionBoxEncryptVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `data`: *string* – Data, encoded in Base64

#### Result

* `data`: *string* – Encrypted data, encoded in Base64

### decrypt

Decrypt data

```ts
type ParamsOfAppEncryptionBoxDecryptVariant = ParamsOfAppEncryptionBoxDecryptVariant

type ResultOfAppEncryptionBoxDecryptVariant = ResultOfAppEncryptionBoxDecryptVariant

function decrypt(
    params: ParamsOfAppEncryptionBoxDecryptVariant,
): Promise<ResultOfAppEncryptionBoxDecryptVariant>;

function decrypt_sync(
    params: ParamsOfAppEncryptionBoxDecryptVariant,
): ResultOfAppEncryptionBoxDecryptVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `data`: *string* – Data, encoded in Base64

#### Result

* `data`: *string* – Decrypted data, encoded in Base64


# Module debot

## Module debot

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Module for working with debot.

### Functions

[init](#init) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Creates and instance of DeBot.

[start](#start) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Starts the DeBot.

[fetch](#fetch) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Fetches DeBot metadata from blockchain.

[execute](#execute) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Executes debot action.

[send](#send) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Sends message to Debot.

[remove](#remove) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Destroys debot handle.

### Types

[DebotErrorCode](#deboterrorcode)

[DebotHandle](#debothandle) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Handle of registered in SDK debot

[DebotAction](#debotaction) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes a debot action in a Debot Context.

[DebotInfo](#debotinfo) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes DeBot metadata.

[DebotActivityTransactionVariant](#debotactivitytransactionvariant) – DeBot wants to create new transaction in blockchain.

[DebotActivity](#debotactivity) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes the operation that the DeBot wants to perform.

[Spending](#spending) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes how much funds will be debited from the target contract balance as a result of the transaction.

[ParamsOfInit](#paramsofinit) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters to init DeBot.

[RegisteredDebot](#registereddebot) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Structure for storing debot handle returned from `init` function.

[ParamsOfAppDebotBrowserLogVariant](#paramsofappdebotbrowserlogvariant) – Print message to user.

[ParamsOfAppDebotBrowserSwitchVariant](#paramsofappdebotbrowserswitchvariant) – Switch debot to another context (menu).

[ParamsOfAppDebotBrowserSwitchCompletedVariant](#paramsofappdebotbrowserswitchcompletedvariant) – Notify browser that all context actions are shown.

[ParamsOfAppDebotBrowserShowActionVariant](#paramsofappdebotbrowsershowactionvariant) – Show action to the user. Called after `switch` for each action in context.

[ParamsOfAppDebotBrowserInputVariant](#paramsofappdebotbrowserinputvariant) – Request user input.

[ParamsOfAppDebotBrowserGetSigningBoxVariant](#paramsofappdebotbrowsergetsigningboxvariant) – Get signing box to sign data.

[ParamsOfAppDebotBrowserInvokeDebotVariant](#paramsofappdebotbrowserinvokedebotvariant) – Execute action of another debot.

[ParamsOfAppDebotBrowserSendVariant](#paramsofappdebotbrowsersendvariant) – Used by Debot to call DInterface implemented by Debot Browser.

[ParamsOfAppDebotBrowserApproveVariant](#paramsofappdebotbrowserapprovevariant) – Requests permission from DeBot Browser to execute DeBot operation.

[ParamsOfAppDebotBrowser](#paramsofappdebotbrowser) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Debot Browser callbacks

[ResultOfAppDebotBrowserInputVariant](#resultofappdebotbrowserinputvariant) – Result of user input.

[ResultOfAppDebotBrowserGetSigningBoxVariant](#resultofappdebotbrowsergetsigningboxvariant) – Result of getting signing box.

[ResultOfAppDebotBrowserInvokeDebotVariant](#resultofappdebotbrowserinvokedebotvariant) – Result of debot invoking.

[ResultOfAppDebotBrowserApproveVariant](#resultofappdebotbrowserapprovevariant) – Result of `approve` callback.

[ResultOfAppDebotBrowser](#resultofappdebotbrowser) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Returning values from Debot Browser callbacks.

[ParamsOfStart](#paramsofstart) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters to start DeBot. DeBot must be already initialized with init() function.

[ParamsOfFetch](#paramsoffetch) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters to fetch DeBot metadata.

[ResultOfFetch](#resultoffetch) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md)

[ParamsOfExecute](#paramsofexecute) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters for executing debot action.

[ParamsOfSend](#paramsofsend) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters of `send` function.

[ParamsOfRemove](#paramsofremove) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md)

[AppDebotBrowser](#appdebotbrowser) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Debot Browser callbacks

## Functions

### init

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Creates and instance of DeBot.

Downloads debot smart contract (code and data) from blockchain and creates an instance of Debot Engine for it.

## Remarks

It does not switch debot to context 0. Browser Callbacks are not called.

```ts
type ParamsOfInit = {
    address: string
}

type RegisteredDebot = {
    debot_handle: DebotHandle,
    debot_abi: string,
    info: DebotInfo
}

function init(
    params: ParamsOfInit,
    obj: AppDebotBrowser,
): Promise<RegisteredDebot>;

function init_sync(
    params: ParamsOfInit,
): RegisteredDebot;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `address`: *string* – Debot smart contract address
* `obj`: [AppDebotBrowser](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/mod_AppDebotBrowser.md#appdebotbrowser) – [UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Debot Browser callbacks

#### Result

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.
* `debot_abi`: *string* – Debot abi as json string.
* `info`: [*DebotInfo*](#debotinfo) – Debot metadata.

### start

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Starts the DeBot.

Downloads debot smart contract from blockchain and switches it to context zero.

This function must be used by Debot Browser to start a dialog with debot. While the function is executing, several Browser Callbacks can be called, since the debot tries to display all actions from the context 0 to the user.

When the debot starts SDK registers `BrowserCallbacks` AppObject. Therefore when `debote.remove` is called the debot is being deleted and the callback is called with `finish`=`true` which indicates that it will never be used again.

```ts
type ParamsOfStart = {
    debot_handle: DebotHandle
}

function start(
    params: ParamsOfStart,
): Promise<void>;

function start_sync(
    params: ParamsOfStart,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.

### fetch

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Fetches DeBot metadata from blockchain.

Downloads DeBot from blockchain and creates and fetches its metadata.

```ts
type ParamsOfFetch = {
    address: string
}

type ResultOfFetch = {
    info: DebotInfo
}

function fetch(
    params: ParamsOfFetch,
): Promise<ResultOfFetch>;

function fetch_sync(
    params: ParamsOfFetch,
): ResultOfFetch;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `address`: *string* – Debot smart contract address.

#### Result

* `info`: [*DebotInfo*](#debotinfo) – Debot metadata.

### execute

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Executes debot action.

Calls debot engine referenced by debot handle to execute input action. Calls Debot Browser Callbacks if needed.

## Remarks

Chain of actions can be executed if input action generates a list of subactions.

```ts
type ParamsOfExecute = {
    debot_handle: DebotHandle,
    action: DebotAction
}

function execute(
    params: ParamsOfExecute,
): Promise<void>;

function execute_sync(
    params: ParamsOfExecute,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.
* `action`: [*DebotAction*](#debotaction) – Debot Action that must be executed.

### send

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Sends message to Debot.

Used by Debot Browser to send response on Dinterface call or from other Debots.

```ts
type ParamsOfSend = {
    debot_handle: DebotHandle,
    message: string
}

function send(
    params: ParamsOfSend,
): Promise<void>;

function send_sync(
    params: ParamsOfSend,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.
* `message`: *string* – BOC of internal message to debot encoded in base64 format.

### remove

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Destroys debot handle.

Removes handle from Client Context and drops debot engine referenced by that handle.

```ts
type ParamsOfRemove = {
    debot_handle: DebotHandle
}

function remove(
    params: ParamsOfRemove,
): Promise<void>;

function remove_sync(
    params: ParamsOfRemove,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.

## Types

### DebotErrorCode

```ts
enum DebotErrorCode {
    DebotStartFailed = 801,
    DebotFetchFailed = 802,
    DebotExecutionFailed = 803,
    DebotInvalidHandle = 804,
    DebotInvalidJsonParams = 805,
    DebotInvalidFunctionId = 806,
    DebotInvalidAbi = 807,
    DebotGetMethodFailed = 808,
    DebotInvalidMsg = 809,
    DebotExternalCallFailed = 810,
    DebotBrowserCallbackFailed = 811,
    DebotOperationRejected = 812,
    DebotNoCode = 813
}
```

One of the following value:

* `DebotStartFailed = 801`
* `DebotFetchFailed = 802`
* `DebotExecutionFailed = 803`
* `DebotInvalidHandle = 804`
* `DebotInvalidJsonParams = 805`
* `DebotInvalidFunctionId = 806`
* `DebotInvalidAbi = 807`
* `DebotGetMethodFailed = 808`
* `DebotInvalidMsg = 809`
* `DebotExternalCallFailed = 810`
* `DebotBrowserCallbackFailed = 811`
* `DebotOperationRejected = 812`
* `DebotNoCode = 813`

### DebotHandle

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Handle of registered in SDK debot

```ts
type DebotHandle = number
```

### DebotAction

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes a debot action in a Debot Context.

```ts
type DebotAction = {
    description: string,
    name: string,
    action_type: number,
    to: number,
    attributes: string,
    misc: string
}
```

* `description`: *string* – A short action description.\
  Should be used by Debot Browser as name of menu item.
* `name`: *string* – Depends on action type.\
  Can be a debot function name or a print string (for Print Action).
* `action_type`: *number* – Action type.
* `to`: *number* – ID of debot context to switch after action execution.
* `attributes`: *string* – Action attributes.\
  In the form of "param=value,flag". attribute example: instant, args, fargs, sign.
* `misc`: *string* – Some internal action data.\
  Used by debot only.

### DebotInfo

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes DeBot metadata.

```ts
type DebotInfo = {
    name?: string,
    version?: string,
    publisher?: string,
    caption?: string,
    author?: string,
    support?: string,
    hello?: string,
    language?: string,
    dabi?: string,
    icon?: string,
    interfaces: string[],
    dabiVersion: string
}
```

* `name`?: *string* – DeBot short name.
* `version`?: *string* – DeBot semantic version.
* `publisher`?: *string* – The name of DeBot deployer.
* `caption`?: *string* – Short info about DeBot.
* `author`?: *string* – The name of DeBot developer.
* `support`?: *string* – TON address of author for questions and donations.
* `hello`?: *string* – String with the first messsage from DeBot.
* `language`?: *string* – String with DeBot interface language (ISO-639).
* `dabi`?: *string* – String with DeBot ABI.
* `icon`?: *string* – DeBot icon.
* `interfaces`: *string\[]* – Vector with IDs of DInterfaces used by DeBot.
* `dabiVersion`: *string* – ABI version ("x.y") supported by DeBot

### DebotActivityTransactionVariant

DeBot wants to create new transaction in blockchain.

```ts
type DebotActivityTransactionVariant = {
    msg: string,
    dst: string,
    out: Spending[],
    fee: bigint,
    setcode: boolean,
    signkey: string,
    signing_box_handle: number
}
```

* `msg`: *string* – External inbound message BOC.
* `dst`: *string* – Target smart contract address.
* `out`: [*Spending*](#spending)*\[]* – List of spendings as a result of transaction.
* `fee`: *bigint* – Transaction total fee.
* `setcode`: *boolean* – Indicates if target smart contract updates its code.
* `signkey`: *string* – Public key from keypair that was used to sign external message.
* `signing_box_handle`: *number* – Signing box handle used to sign external message.

### DebotActivity

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes the operation that the DeBot wants to perform.

```ts
type DebotActivity = ({
    type: 'Transaction'
} & DebotActivityTransactionVariant)
```

Depends on value of the `type` field.

When *type* is *'Transaction'*

DeBot wants to create new transaction in blockchain.

* `msg`: *string* – External inbound message BOC.
* `dst`: *string* – Target smart contract address.
* `out`: [*Spending*](#spending)*\[]* – List of spendings as a result of transaction.
* `fee`: *bigint* – Transaction total fee.
* `setcode`: *boolean* – Indicates if target smart contract updates its code.
* `signkey`: *string* – Public key from keypair that was used to sign external message.
* `signing_box_handle`: *number* – Signing box handle used to sign external message.

Variant constructors:

```ts
function debotActivityTransaction(msg: string, dst: string, out: Spending[], fee: bigint, setcode: boolean, signkey: string, signing_box_handle: number): DebotActivity;
```

### Spending

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Describes how much funds will be debited from the target contract balance as a result of the transaction.

```ts
type Spending = {
    amount: bigint,
    dst: string
}
```

* `amount`: *bigint* – Amount of nanotokens that will be sent to `dst` address.
* `dst`: *string* – Destination address of recipient of funds.

### ParamsOfInit

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters to init DeBot.

```ts
type ParamsOfInit = {
    address: string
}
```

* `address`: *string* – Debot smart contract address

### RegisteredDebot

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Structure for storing debot handle returned from `init` function.

```ts
type RegisteredDebot = {
    debot_handle: DebotHandle,
    debot_abi: string,
    info: DebotInfo
}
```

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.
* `debot_abi`: *string* – Debot abi as json string.
* `info`: [*DebotInfo*](#debotinfo) – Debot metadata.

### ParamsOfAppDebotBrowserLogVariant

Print message to user.

```ts
type ParamsOfAppDebotBrowserLogVariant = {
    msg: string
}
```

* `msg`: *string* – A string that must be printed to user.

### ParamsOfAppDebotBrowserSwitchVariant

Switch debot to another context (menu).

```ts
type ParamsOfAppDebotBrowserSwitchVariant = {
    context_id: number
}
```

* `context_id`: *number* – Debot context ID to which debot is switched.

### ParamsOfAppDebotBrowserSwitchCompletedVariant

Notify browser that all context actions are shown.

```ts
type ParamsOfAppDebotBrowserSwitchCompletedVariant = {

}
```

### ParamsOfAppDebotBrowserShowActionVariant

Show action to the user. Called after `switch` for each action in context.

```ts
type ParamsOfAppDebotBrowserShowActionVariant = {
    action: DebotAction
}
```

* `action`: [*DebotAction*](#debotaction) – Debot action that must be shown to user as menu item. At least `description` property must be shown from \[DebotAction] structure.

### ParamsOfAppDebotBrowserInputVariant

Request user input.

```ts
type ParamsOfAppDebotBrowserInputVariant = {
    prompt: string
}
```

* `prompt`: *string* – A prompt string that must be printed to user before input request.

### ParamsOfAppDebotBrowserGetSigningBoxVariant

Get signing box to sign data.

Signing box returned is owned and disposed by debot engine

```ts
type ParamsOfAppDebotBrowserGetSigningBoxVariant = {

}
```

### ParamsOfAppDebotBrowserInvokeDebotVariant

Execute action of another debot.

```ts
type ParamsOfAppDebotBrowserInvokeDebotVariant = {
    debot_addr: string,
    action: DebotAction
}
```

* `debot_addr`: *string* – Address of debot in blockchain.
* `action`: [*DebotAction*](#debotaction) – Debot action to execute.

### ParamsOfAppDebotBrowserSendVariant

Used by Debot to call DInterface implemented by Debot Browser.

```ts
type ParamsOfAppDebotBrowserSendVariant = {
    message: string
}
```

* `message`: *string* – Internal message to DInterface address.\
  Message body contains interface function and parameters.

### ParamsOfAppDebotBrowserApproveVariant

Requests permission from DeBot Browser to execute DeBot operation.

```ts
type ParamsOfAppDebotBrowserApproveVariant = {
    activity: DebotActivity
}
```

* `activity`: [*DebotActivity*](#debotactivity) – DeBot activity details.

### ParamsOfAppDebotBrowser

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Debot Browser callbacks

Called by debot engine to communicate with debot browser.

```ts
type ParamsOfAppDebotBrowser = ({
    type: 'Log'
} & ParamsOfAppDebotBrowserLogVariant) | ({
    type: 'Switch'
} & ParamsOfAppDebotBrowserSwitchVariant) | ({
    type: 'SwitchCompleted'
} & ParamsOfAppDebotBrowserSwitchCompletedVariant) | ({
    type: 'ShowAction'
} & ParamsOfAppDebotBrowserShowActionVariant) | ({
    type: 'Input'
} & ParamsOfAppDebotBrowserInputVariant) | ({
    type: 'GetSigningBox'
} & ParamsOfAppDebotBrowserGetSigningBoxVariant) | ({
    type: 'InvokeDebot'
} & ParamsOfAppDebotBrowserInvokeDebotVariant) | ({
    type: 'Send'
} & ParamsOfAppDebotBrowserSendVariant) | ({
    type: 'Approve'
} & ParamsOfAppDebotBrowserApproveVariant)
```

Depends on value of the `type` field.

When *type* is *'Log'*

Print message to user.

* `msg`: *string* – A string that must be printed to user.

When *type* is *'Switch'*

Switch debot to another context (menu).

* `context_id`: *number* – Debot context ID to which debot is switched.

When *type* is *'SwitchCompleted'*

Notify browser that all context actions are shown.

When *type* is *'ShowAction'*

Show action to the user. Called after `switch` for each action in context.

* `action`: [*DebotAction*](#debotaction) – Debot action that must be shown to user as menu item. At least `description` property must be shown from \[DebotAction] structure.

When *type* is *'Input'*

Request user input.

* `prompt`: *string* – A prompt string that must be printed to user before input request.

When *type* is *'GetSigningBox'*

Get signing box to sign data.

Signing box returned is owned and disposed by debot engine

When *type* is *'InvokeDebot'*

Execute action of another debot.

* `debot_addr`: *string* – Address of debot in blockchain.
* `action`: [*DebotAction*](#debotaction) – Debot action to execute.

When *type* is *'Send'*

Used by Debot to call DInterface implemented by Debot Browser.

* `message`: *string* – Internal message to DInterface address.\
  Message body contains interface function and parameters.

When *type* is *'Approve'*

Requests permission from DeBot Browser to execute DeBot operation.

* `activity`: [*DebotActivity*](#debotactivity) – DeBot activity details.

Variant constructors:

```ts
function paramsOfAppDebotBrowserLog(msg: string): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserSwitch(context_id: number): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserSwitchCompleted(): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserShowAction(action: DebotAction): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserInput(prompt: string): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserGetSigningBox(): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserInvokeDebot(debot_addr: string, action: DebotAction): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserSend(message: string): ParamsOfAppDebotBrowser;
function paramsOfAppDebotBrowserApprove(activity: DebotActivity): ParamsOfAppDebotBrowser;
```

### ResultOfAppDebotBrowserInputVariant

Result of user input.

```ts
type ResultOfAppDebotBrowserInputVariant = {
    value: string
}
```

* `value`: *string* – String entered by user.

### ResultOfAppDebotBrowserGetSigningBoxVariant

Result of getting signing box.

```ts
type ResultOfAppDebotBrowserGetSigningBoxVariant = {
    signing_box: SigningBoxHandle
}
```

* `signing_box`: [*SigningBoxHandle*](/ever-sdk/reference/types-and-methods/mod_crypto#signingboxhandle) – Signing box for signing data requested by debot engine.\
  Signing box is owned and disposed by debot engine

### ResultOfAppDebotBrowserInvokeDebotVariant

Result of debot invoking.

```ts
type ResultOfAppDebotBrowserInvokeDebotVariant = {

}
```

### ResultOfAppDebotBrowserApproveVariant

Result of `approve` callback.

```ts
type ResultOfAppDebotBrowserApproveVariant = {
    approved: boolean
}
```

* `approved`: *boolean* – Indicates whether the DeBot is allowed to perform the specified operation.

### ResultOfAppDebotBrowser

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Returning values from Debot Browser callbacks.

```ts
type ResultOfAppDebotBrowser = ({
    type: 'Input'
} & ResultOfAppDebotBrowserInputVariant) | ({
    type: 'GetSigningBox'
} & ResultOfAppDebotBrowserGetSigningBoxVariant) | ({
    type: 'InvokeDebot'
} & ResultOfAppDebotBrowserInvokeDebotVariant) | ({
    type: 'Approve'
} & ResultOfAppDebotBrowserApproveVariant)
```

Depends on value of the `type` field.

When *type* is *'Input'*

Result of user input.

* `value`: *string* – String entered by user.

When *type* is *'GetSigningBox'*

Result of getting signing box.

* `signing_box`: [*SigningBoxHandle*](/ever-sdk/reference/types-and-methods/mod_crypto#signingboxhandle) – Signing box for signing data requested by debot engine.\
  Signing box is owned and disposed by debot engine

When *type* is *'InvokeDebot'*

Result of debot invoking.

When *type* is *'Approve'*

Result of `approve` callback.

* `approved`: *boolean* – Indicates whether the DeBot is allowed to perform the specified operation.

Variant constructors:

```ts
function resultOfAppDebotBrowserInput(value: string): ResultOfAppDebotBrowser;
function resultOfAppDebotBrowserGetSigningBox(signing_box: SigningBoxHandle): ResultOfAppDebotBrowser;
function resultOfAppDebotBrowserInvokeDebot(): ResultOfAppDebotBrowser;
function resultOfAppDebotBrowserApprove(approved: boolean): ResultOfAppDebotBrowser;
```

### ParamsOfStart

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters to start DeBot. DeBot must be already initialized with init() function.

```ts
type ParamsOfStart = {
    debot_handle: DebotHandle
}
```

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.

### ParamsOfFetch

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters to fetch DeBot metadata.

```ts
type ParamsOfFetch = {
    address: string
}
```

* `address`: *string* – Debot smart contract address.

### ResultOfFetch

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md)

```ts
type ResultOfFetch = {
    info: DebotInfo
}
```

* `info`: [*DebotInfo*](#debotinfo) – Debot metadata.

### ParamsOfExecute

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters for executing debot action.

```ts
type ParamsOfExecute = {
    debot_handle: DebotHandle,
    action: DebotAction
}
```

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.
* `action`: [*DebotAction*](#debotaction) – Debot Action that must be executed.

### ParamsOfSend

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Parameters of `send` function.

```ts
type ParamsOfSend = {
    debot_handle: DebotHandle,
    message: string
}
```

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.
* `message`: *string* – BOC of internal message to debot encoded in base64 format.

### ParamsOfRemove

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md)

```ts
type ParamsOfRemove = {
    debot_handle: DebotHandle
}
```

* `debot_handle`: [*DebotHandle*](#debothandle) – Debot handle which references an instance of debot engine.

### AppDebotBrowser

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Debot Browser callbacks

Called by debot engine to communicate with debot browser.

```ts

export interface AppDebotBrowser {
    log(params: ParamsOfAppDebotBrowserLogVariant): void,
    switch(params: ParamsOfAppDebotBrowserSwitchVariant): void,
    switch_completed(): void,
    show_action(params: ParamsOfAppDebotBrowserShowActionVariant): void,
    input(params: ParamsOfAppDebotBrowserInputVariant): Promise<ResultOfAppDebotBrowserInputVariant>,
    get_signing_box(): Promise<ResultOfAppDebotBrowserGetSigningBoxVariant>,
    invoke_debot(params: ParamsOfAppDebotBrowserInvokeDebotVariant): Promise<void>,
    send(params: ParamsOfAppDebotBrowserSendVariant): void,
    approve(params: ParamsOfAppDebotBrowserApproveVariant): Promise<ResultOfAppDebotBrowserApproveVariant>,
}
```

### log

Print message to user.

```ts
type ParamsOfAppDebotBrowserLogVariant = ParamsOfAppDebotBrowserLogVariant

function log(
    params: ParamsOfAppDebotBrowserLogVariant,
): Promise<>;

function log_sync(
    params: ParamsOfAppDebotBrowserLogVariant,
): ;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `msg`: *string* – A string that must be printed to user.

### switch

Switch debot to another context (menu).

```ts
type ParamsOfAppDebotBrowserSwitchVariant = ParamsOfAppDebotBrowserSwitchVariant

function switch(
    params: ParamsOfAppDebotBrowserSwitchVariant,
): Promise<>;

function switch_sync(
    params: ParamsOfAppDebotBrowserSwitchVariant,
): ;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `context_id`: *number* – Debot context ID to which debot is switched.

### switch\_completed

Notify browser that all context actions are shown.

```ts
function switch_completed(): Promise<>;

function switch_completed_sync(): ;
```

NOTE: Sync version is available only for `lib-node` binding.

### show\_action

Show action to the user. Called after `switch` for each action in context.

```ts
type ParamsOfAppDebotBrowserShowActionVariant = ParamsOfAppDebotBrowserShowActionVariant

function show_action(
    params: ParamsOfAppDebotBrowserShowActionVariant,
): Promise<>;

function show_action_sync(
    params: ParamsOfAppDebotBrowserShowActionVariant,
): ;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `action`: [*DebotAction*](#debotaction) – Debot action that must be shown to user as menu item. At least `description` property must be shown from \[DebotAction] structure.

### input

Request user input.

```ts
type ParamsOfAppDebotBrowserInputVariant = ParamsOfAppDebotBrowserInputVariant

type ResultOfAppDebotBrowserInputVariant = ResultOfAppDebotBrowserInputVariant

function input(
    params: ParamsOfAppDebotBrowserInputVariant,
): Promise<ResultOfAppDebotBrowserInputVariant>;

function input_sync(
    params: ParamsOfAppDebotBrowserInputVariant,
): ResultOfAppDebotBrowserInputVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `prompt`: *string* – A prompt string that must be printed to user before input request.

#### Result

* `value`: *string* – String entered by user.

### get\_signing\_box

Get signing box to sign data.

Signing box returned is owned and disposed by debot engine

```ts
type ResultOfAppDebotBrowserGetSigningBoxVariant = ResultOfAppDebotBrowserGetSigningBoxVariant

function get_signing_box(): Promise<ResultOfAppDebotBrowserGetSigningBoxVariant>;

function get_signing_box_sync(): ResultOfAppDebotBrowserGetSigningBoxVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `signing_box`: [*SigningBoxHandle*](/ever-sdk/reference/types-and-methods/mod_crypto#signingboxhandle) – Signing box for signing data requested by debot engine.\
  Signing box is owned and disposed by debot engine

### invoke\_debot

Execute action of another debot.

```ts
type ParamsOfAppDebotBrowserInvokeDebotVariant = ParamsOfAppDebotBrowserInvokeDebotVariant

function invoke_debot(
    params: ParamsOfAppDebotBrowserInvokeDebotVariant,
): Promise<void>;

function invoke_debot_sync(
    params: ParamsOfAppDebotBrowserInvokeDebotVariant,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `debot_addr`: *string* – Address of debot in blockchain.
* `action`: [*DebotAction*](#debotaction) – Debot action to execute.

### send

Used by Debot to call DInterface implemented by Debot Browser.

```ts
type ParamsOfAppDebotBrowserSendVariant = ParamsOfAppDebotBrowserSendVariant

function send(
    params: ParamsOfAppDebotBrowserSendVariant,
): Promise<>;

function send_sync(
    params: ParamsOfAppDebotBrowserSendVariant,
): ;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `message`: *string* – Internal message to DInterface address.\
  Message body contains interface function and parameters.

### approve

Requests permission from DeBot Browser to execute DeBot operation.

```ts
type ParamsOfAppDebotBrowserApproveVariant = ParamsOfAppDebotBrowserApproveVariant

type ResultOfAppDebotBrowserApproveVariant = ResultOfAppDebotBrowserApproveVariant

function approve(
    params: ParamsOfAppDebotBrowserApproveVariant,
): Promise<ResultOfAppDebotBrowserApproveVariant>;

function approve_sync(
    params: ParamsOfAppDebotBrowserApproveVariant,
): ResultOfAppDebotBrowserApproveVariant;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `activity`: [*DebotActivity*](#debotactivity) – DeBot activity details.

#### Result

* `approved`: *boolean* – Indicates whether the DeBot is allowed to perform the specified operation.


# Module net

## Module net

Network access.

### Functions

[query](#query) – Performs DAppServer GraphQL query.

[batch\_query](#batch_query) – Performs multiple queries per single fetch.

[query\_collection](#query_collection) – Queries collection data

[aggregate\_collection](#aggregate_collection) – Aggregates collection data.

[wait\_for\_collection](#wait_for_collection) – Returns an object that fulfills the conditions or waits for its appearance

[unsubscribe](#unsubscribe) – Cancels a subscription

[subscribe\_collection](#subscribe_collection) – Creates a collection subscription

[subscribe](#subscribe) – Creates a subscription

[suspend](#suspend) – Suspends network module to stop any network activity

[resume](#resume) – Resumes network module to enable network activity

[find\_last\_shard\_block](#find_last_shard_block) – Returns ID of the last block in a specified account shard

[fetch\_endpoints](#fetch_endpoints) – Requests the list of alternative endpoints from server

[set\_endpoints](#set_endpoints) – Sets the list of endpoints to use on reinit

[get\_endpoints](#get_endpoints) – Requests the list of alternative endpoints from server

[query\_counterparties](#query_counterparties) – Allows to query and paginate through the list of accounts that the specified account has interacted with, sorted by the time of the last internal message between accounts

[query\_transaction\_tree](#query_transaction_tree) – Returns a tree of transactions triggered by a specific message.

[create\_block\_iterator](#create_block_iterator) – Creates block iterator.

[resume\_block\_iterator](#resume_block_iterator) – Resumes block iterator.

[create\_transaction\_iterator](#create_transaction_iterator) – Creates transaction iterator.

[resume\_transaction\_iterator](#resume_transaction_iterator) – Resumes transaction iterator.

[iterator\_next](#iterator_next) – Returns next available items.

[remove\_iterator](#remove_iterator) – Removes an iterator

[get\_signature\_id](#get_signature_id) – Returns signature ID for configured network if it should be used in messages signature

### Types

[NetErrorCode](#neterrorcode)

[OrderBy](#orderby)

[SortDirection](#sortdirection)

[ParamsOfQueryOperation](#paramsofqueryoperation)

[FieldAggregation](#fieldaggregation)

[AggregationFn](#aggregationfn)

[TransactionNode](#transactionnode)

[MessageNode](#messagenode)

[ParamsOfQuery](#paramsofquery)

[ResultOfQuery](#resultofquery)

[ParamsOfBatchQuery](#paramsofbatchquery)

[ResultOfBatchQuery](#resultofbatchquery)

[ParamsOfQueryCollection](#paramsofquerycollection)

[ResultOfQueryCollection](#resultofquerycollection)

[ParamsOfAggregateCollection](#paramsofaggregatecollection)

[ResultOfAggregateCollection](#resultofaggregatecollection)

[ParamsOfWaitForCollection](#paramsofwaitforcollection)

[ResultOfWaitForCollection](#resultofwaitforcollection)

[ResultOfSubscribeCollection](#resultofsubscribecollection)

[ParamsOfSubscribeCollection](#paramsofsubscribecollection)

[ParamsOfSubscribe](#paramsofsubscribe)

[ParamsOfFindLastShardBlock](#paramsoffindlastshardblock)

[ResultOfFindLastShardBlock](#resultoffindlastshardblock)

[EndpointsSet](#endpointsset)

[ResultOfGetEndpoints](#resultofgetendpoints)

[ParamsOfQueryCounterparties](#paramsofquerycounterparties)

[ParamsOfQueryTransactionTree](#paramsofquerytransactiontree)

[ResultOfQueryTransactionTree](#resultofquerytransactiontree)

[ParamsOfCreateBlockIterator](#paramsofcreateblockiterator)

[RegisteredIterator](#registerediterator)

[ParamsOfResumeBlockIterator](#paramsofresumeblockiterator)

[ParamsOfCreateTransactionIterator](#paramsofcreatetransactioniterator)

[ParamsOfResumeTransactionIterator](#paramsofresumetransactioniterator)

[ParamsOfIteratorNext](#paramsofiteratornext)

[ResultOfIteratorNext](#resultofiteratornext)

[ResultOfGetSignatureId](#resultofgetsignatureid)

## Functions

### query

Performs DAppServer GraphQL query.

```ts
type ParamsOfQuery = {
    query: string,
    variables?: any
}

type ResultOfQuery = {
    result: any
}

function query(
    params: ParamsOfQuery,
): Promise<ResultOfQuery>;

function query_sync(
    params: ParamsOfQuery,
): ResultOfQuery;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `query`: *string* – GraphQL query text.
* `variables`?: *any* – Variables used in query.\
  Must be a map with named values that can be used in query.

#### Result

* `result`: *any* – Result provided by DAppServer.

### batch\_query

Performs multiple queries per single fetch.

```ts
type ParamsOfBatchQuery = {
    operations: ParamsOfQueryOperation[]
}

type ResultOfBatchQuery = {
    results: any[]
}

function batch_query(
    params: ParamsOfBatchQuery,
): Promise<ResultOfBatchQuery>;

function batch_query_sync(
    params: ParamsOfBatchQuery,
): ResultOfBatchQuery;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `operations`: [*ParamsOfQueryOperation*](#paramsofqueryoperation)*\[]* – List of query operations that must be performed per single fetch.

#### Result

* `results`: *any\[]* – Result values for batched queries.\
  Returns an array of values. Each value corresponds to `queries` item.

### query\_collection

Queries collection data

Queries data that satisfies the `filter` conditions, limits the number of returned records and orders them. The projection fields are limited to `result` fields

```ts
type ParamsOfQueryCollection = {
    collection: string,
    filter?: any,
    result: string,
    order?: OrderBy[],
    limit?: number
}

type ResultOfQueryCollection = {
    result: any[]
}

function query_collection(
    params: ParamsOfQueryCollection,
): Promise<ResultOfQueryCollection>;

function query_collection_sync(
    params: ParamsOfQueryCollection,
): ResultOfQueryCollection;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string
* `order`?: [*OrderBy*](#orderby)*\[]* – Sorting order
* `limit`?: *number* – Number of documents to return

#### Result

* `result`: *any\[]* – Objects that match the provided criteria

### aggregate\_collection

Aggregates collection data.

Aggregates values from the specified `fields` for records that satisfies the `filter` conditions,

```ts
type ParamsOfAggregateCollection = {
    collection: string,
    filter?: any,
    fields?: FieldAggregation[]
}

type ResultOfAggregateCollection = {
    values: any
}

function aggregate_collection(
    params: ParamsOfAggregateCollection,
): Promise<ResultOfAggregateCollection>;

function aggregate_collection_sync(
    params: ParamsOfAggregateCollection,
): ResultOfAggregateCollection;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `fields`?: [*FieldAggregation*](#fieldaggregation)*\[]* – Projection (result) string

#### Result

* `values`: *any* – Values for requested fields.\
  Returns an array of strings. Each string refers to the corresponding `fields` item.\
  Numeric value is returned as a decimal string representations.

### wait\_for\_collection

Returns an object that fulfills the conditions or waits for its appearance

Triggers only once. If object that satisfies the `filter` conditions already exists - returns it immediately. If not - waits for insert/update of data within the specified `timeout`, and returns it. The projection fields are limited to `result` fields

```ts
type ParamsOfWaitForCollection = {
    collection: string,
    filter?: any,
    result: string,
    timeout?: number
}

type ResultOfWaitForCollection = {
    result: any
}

function wait_for_collection(
    params: ParamsOfWaitForCollection,
): Promise<ResultOfWaitForCollection>;

function wait_for_collection_sync(
    params: ParamsOfWaitForCollection,
): ResultOfWaitForCollection;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string
* `timeout`?: *number* – Query timeout

#### Result

* `result`: *any* – First found object that matches the provided criteria

### unsubscribe

Cancels a subscription

Cancels a subscription specified by its handle.

```ts
type ResultOfSubscribeCollection = {
    handle: number
}

function unsubscribe(
    params: ResultOfSubscribeCollection,
): Promise<void>;

function unsubscribe_sync(
    params: ResultOfSubscribeCollection,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: *number* – Subscription handle.\
  Must be closed with `unsubscribe`

### subscribe\_collection

Creates a collection subscription

Triggers for each insert/update of data that satisfies the `filter` conditions. The projection fields are limited to `result` fields.

The subscription is a persistent communication channel between client and Free TON Network. All changes in the blockchain will be reflected in realtime. Changes means inserts and updates of the blockchain entities.

#### Important Notes on Subscriptions

Unfortunately sometimes the connection with the network brakes down. In this situation the library attempts to reconnect to the network. This reconnection sequence can take significant time. All of this time the client is disconnected from the network.

Bad news is that all blockchain changes that happened while the client was disconnected are lost.

Good news is that the client report errors to the callback when it loses and resumes connection.

So, if the lost changes are important to the application then the application must handle these error reports.

Library reports errors with `responseType` == 101 and the error object passed via `params`.

When the library has successfully reconnected the application receives callback with `responseType` == 101 and `params.code` == 614 (NetworkModuleResumed).

Application can use several ways to handle this situation:

* If application monitors changes for the single blockchain object (for example specific account): application can perform a query for this object and handle actual data as a regular data from the subscription.
* If application monitors sequence of some blockchain objects (for example transactions of the specific account): application must refresh all cached (or visible to user) lists where this sequences presents.

```ts
type ParamsOfSubscribeCollection = {
    collection: string,
    filter?: any,
    result: string
}

type ResultOfSubscribeCollection = {
    handle: number
}

function subscribe_collection(
    params: ParamsOfSubscribeCollection,
    responseHandler?: ResponseHandler,
): Promise<ResultOfSubscribeCollection>;

function subscribe_collection_sync(
    params: ParamsOfSubscribeCollection,
): ResultOfSubscribeCollection;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string
* `responseHandler`?: [*ResponseHandler*](/ever-sdk/reference/types-and-methods/modules#responsehandler) – additional responses handler.

#### Result

* `handle`: *number* – Subscription handle.\
  Must be closed with `unsubscribe`

### subscribe

Creates a subscription

The subscription is a persistent communication channel between client and Everscale Network.

#### Important Notes on Subscriptions

Unfortunately sometimes the connection with the network breaks down. In this situation the library attempts to reconnect to the network. This reconnection sequence can take significant time. All of this time the client is disconnected from the network.

Bad news is that all changes that happened while the client was disconnected are lost.

Good news is that the client report errors to the callback when it loses and resumes connection.

So, if the lost changes are important to the application then the application must handle these error reports.

Library reports errors with `responseType` == 101 and the error object passed via `params`.

When the library has successfully reconnected the application receives callback with `responseType` == 101 and `params.code` == 614 (NetworkModuleResumed).

Application can use several ways to handle this situation:

* If application monitors changes for the single object (for example specific account): application can perform a query for this object and handle actual data as a regular data from the subscription.
* If application monitors sequence of some objects (for example transactions of the specific account): application must refresh all cached (or visible to user) lists where this sequences presents.

```ts
type ParamsOfSubscribe = {
    subscription: string,
    variables?: any
}

type ResultOfSubscribeCollection = {
    handle: number
}

function subscribe(
    params: ParamsOfSubscribe,
    responseHandler?: ResponseHandler,
): Promise<ResultOfSubscribeCollection>;

function subscribe_sync(
    params: ParamsOfSubscribe,
): ResultOfSubscribeCollection;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `subscription`: *string* – GraphQL subscription text.
* `variables`?: *any* – Variables used in subscription.\
  Must be a map with named values that can be used in query.
* `responseHandler`?: [*ResponseHandler*](/ever-sdk/reference/types-and-methods/modules#responsehandler) – additional responses handler.

#### Result

* `handle`: *number* – Subscription handle.\
  Must be closed with `unsubscribe`

### suspend

Suspends network module to stop any network activity

```ts
function suspend(): Promise<void>;

function suspend_sync(): void;
```

NOTE: Sync version is available only for `lib-node` binding.

### resume

Resumes network module to enable network activity

```ts
function resume(): Promise<void>;

function resume_sync(): void;
```

NOTE: Sync version is available only for `lib-node` binding.

### find\_last\_shard\_block

Returns ID of the last block in a specified account shard

```ts
type ParamsOfFindLastShardBlock = {
    address: string
}

type ResultOfFindLastShardBlock = {
    block_id: string
}

function find_last_shard_block(
    params: ParamsOfFindLastShardBlock,
): Promise<ResultOfFindLastShardBlock>;

function find_last_shard_block_sync(
    params: ParamsOfFindLastShardBlock,
): ResultOfFindLastShardBlock;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `address`: *string* – Account address

#### Result

* `block_id`: *string* – Account shard last block ID

### fetch\_endpoints

Requests the list of alternative endpoints from server

```ts
type EndpointsSet = {
    endpoints: string[]
}

function fetch_endpoints(): Promise<EndpointsSet>;

function fetch_endpoints_sync(): EndpointsSet;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `endpoints`: *string\[]* – List of endpoints provided by server

### set\_endpoints

Sets the list of endpoints to use on reinit

```ts
type EndpointsSet = {
    endpoints: string[]
}

function set_endpoints(
    params: EndpointsSet,
): Promise<void>;

function set_endpoints_sync(
    params: EndpointsSet,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `endpoints`: *string\[]* – List of endpoints provided by server

### get\_endpoints

Requests the list of alternative endpoints from server

```ts
type ResultOfGetEndpoints = {
    query: string,
    endpoints: string[]
}

function get_endpoints(): Promise<ResultOfGetEndpoints>;

function get_endpoints_sync(): ResultOfGetEndpoints;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `query`: *string* – Current query endpoint
* `endpoints`: *string\[]* – List of all endpoints used by client

### query\_counterparties

Allows to query and paginate through the list of accounts that the specified account has interacted with, sorted by the time of the last internal message between accounts

*Attention* this query retrieves data from 'Counterparties' service which is not supported in the opensource version of DApp Server (and will not be supported) as well as in Evernode SE (will be supported in SE in future), but is always accessible via [EVER OS Clouds](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/ton-os-api/networks.md)

```ts
type ParamsOfQueryCounterparties = {
    account: string,
    result: string,
    first?: number,
    after?: string
}

type ResultOfQueryCollection = {
    result: any[]
}

function query_counterparties(
    params: ParamsOfQueryCounterparties,
): Promise<ResultOfQueryCollection>;

function query_counterparties_sync(
    params: ParamsOfQueryCounterparties,
): ResultOfQueryCollection;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `account`: *string* – Account address
* `result`: *string* – Projection (result) string
* `first`?: *number* – Number of counterparties to return
* `after`?: *string* – `cursor` field of the last received result

#### Result

* `result`: *any\[]* – Objects that match the provided criteria

### query\_transaction\_tree

Returns a tree of transactions triggered by a specific message.

Performs recursive retrieval of a transactions tree produced by a specific message: in\_msg -> dst\_transaction -> out\_messages -> dst\_transaction -> ... If the chain of transactions execution is in progress while the function is running, it will wait for the next transactions to appear until the full tree or more than 50 transactions are received.

All the retrieved messages and transactions are included into `result.messages` and `result.transactions` respectively.

Function reads transactions layer by layer, by pages of 20 transactions.

The retrieval process goes like this: Let's assume we have an infinite chain of transactions and each transaction generates 5 messages.

1. Retrieve 1st message (input parameter) and corresponding transaction - put it into result. It is the first level of the tree of transactions - its root. Retrieve 5 out message ids from the transaction for next steps.
2. Retrieve 5 messages and corresponding transactions on the 2nd layer. Put them into result. Retrieve 5\*5 out message ids from these transactions for next steps
3. Retrieve 20 (size of the page) messages and transactions (3rd layer) and 20\*5=100 message ids (4th layer).
4. Retrieve the last 5 messages and 5 transactions on the 3rd layer + 15 messages and transactions (of 100) from the 4th layer

* 25 message ids of the 4th layer + 75 message ids of the 5th layer.

5. Retrieve 20 more messages and 20 more transactions of the 4th layer + 100 more message ids of the 5th layer.
6. Now we have 1+5+20+20+20 = 66 transactions, which is more than 50. Function exits with the tree of 1m->1t->5m->5t->25m->25t->35m->35t. If we see any message ids in the last transactions out\_msgs, which don't have corresponding messages in the function result, it means that the full tree was not received and we need to continue iteration.

To summarize, it is guaranteed that each message in `result.messages` has the corresponding transaction in the `result.transactions`. But there is no guarantee that all messages from transactions `out_msgs` are presented in `result.messages`. So the application has to continue retrieval for missing messages if it requires.

```ts
type ParamsOfQueryTransactionTree = {
    in_msg: string,
    abi_registry?: Abi[],
    timeout?: number,
    transaction_max_count?: number
}

type ResultOfQueryTransactionTree = {
    messages: MessageNode[],
    transactions: TransactionNode[]
}

function query_transaction_tree(
    params: ParamsOfQueryTransactionTree,
): Promise<ResultOfQueryTransactionTree>;

function query_transaction_tree_sync(
    params: ParamsOfQueryTransactionTree,
): ResultOfQueryTransactionTree;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `in_msg`: *string* – Input message id.
* `abi_registry`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi)*\[]* – List of contract ABIs that will be used to decode message bodies. Library will try to decode each returned message body using any ABI from the registry.
* `timeout`?: *number* – Timeout used to limit waiting time for the missing messages and transaction.\
  If some of the following messages and transactions are missing yet\
  The maximum waiting time is regulated by this option.\
  \
  Default value is 60000 (1 min). If `timeout` is set to 0 then function will wait infinitely\
  until the whole transaction tree is executed
* `transaction_max_count`?: *number* – Maximum transaction count to wait.\
  If transaction tree contains more transaction then this parameter then only first `transaction_max_count` transaction are awaited and returned.\
  \
  Default value is 50. If `transaction_max_count` is set to 0 then no limitation on\
  transaction count is used and all transaction are returned.

#### Result

* `messages`: [*MessageNode*](#messagenode)*\[]* – Messages.
* `transactions`: [*TransactionNode*](#transactionnode)*\[]* – Transactions.

### create\_block\_iterator

Creates block iterator.

Block iterator uses robust iteration methods that guaranties that every block in the specified range isn't missed or iterated twice.

Iterated range can be reduced with some filters:

* `start_time` – the bottom time range. Only blocks with `gen_utime` more or equal to this value is iterated. If this parameter is omitted then there is no bottom time edge, so all blocks since zero state is iterated.
* `end_time` – the upper time range. Only blocks with `gen_utime` less then this value is iterated. If this parameter is omitted then there is no upper time edge, so iterator never finishes.
* `shard_filter` – workchains and shard prefixes that reduce the set of interesting blocks. Block conforms to the shard filter if it belongs to the filter workchain and the first bits of block's `shard` fields matches to the shard prefix. Only blocks with suitable shard are iterated.

Items iterated is a JSON objects with block data. The minimal set of returned fields is:

```
id
gen_utime
workchain_id
shard
after_split
after_merge
prev_ref {
    root_hash
}
prev_alt_ref {
    root_hash
}
```

Application can request additional fields in the `result` parameter.

Application should call the `remove_iterator` when iterator is no longer required.

```ts
type ParamsOfCreateBlockIterator = {
    start_time?: number,
    end_time?: number,
    shard_filter?: string[],
    result?: string
}

type RegisteredIterator = {
    handle: number
}

function create_block_iterator(
    params: ParamsOfCreateBlockIterator,
): Promise<RegisteredIterator>;

function create_block_iterator_sync(
    params: ParamsOfCreateBlockIterator,
): RegisteredIterator;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `start_time`?: *number* – Starting time to iterate from.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` >= `start_time`.\
  Otherwise the iteration starts from zero state.\
  \
  Must be specified in seconds.
* `end_time`?: *number* – Optional end time to iterate for.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` < `end_time`.\
  Otherwise the iteration never stops.\
  \
  Must be specified in seconds.
* `shard_filter`?: *string\[]* – Shard prefix filter.\
  If the application specifies this parameter and it is not the empty array\
  then the iteration will include items related to accounts that belongs to\
  the specified shard prefixes.\
  Shard prefix must be represented as a string "workchain:prefix".\
  Where `workchain` is a signed integer and the `prefix` if a hexadecimal\
  representation if the 64-bit unsigned integer with tagged shard prefix.\
  For example: "0:3800000000000000".
* `result`?: *string* – Projection (result) string.\
  List of the fields that must be returned for iterated items.\
  This field is the same as the `result` parameter of\
  the `query_collection` function.\
  Note that iterated items can contains additional fields that are\
  not requested in the `result`.

#### Result

* `handle`: *number* – Iterator handle.\
  Must be removed using `remove_iterator`\
  when it is no more needed for the application.

### resume\_block\_iterator

Resumes block iterator.

The iterator stays exactly at the same position where the `resume_state` was caught.

Application should call the `remove_iterator` when iterator is no longer required.

```ts
type ParamsOfResumeBlockIterator = {
    resume_state: any
}

type RegisteredIterator = {
    handle: number
}

function resume_block_iterator(
    params: ParamsOfResumeBlockIterator,
): Promise<RegisteredIterator>;

function resume_block_iterator_sync(
    params: ParamsOfResumeBlockIterator,
): RegisteredIterator;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `resume_state`: *any* – Iterator state from which to resume.\
  Same as value returned from `iterator_next`.

#### Result

* `handle`: *number* – Iterator handle.\
  Must be removed using `remove_iterator`\
  when it is no more needed for the application.

### create\_transaction\_iterator

Creates transaction iterator.

Transaction iterator uses robust iteration methods that guaranty that every transaction in the specified range isn't missed or iterated twice.

Iterated range can be reduced with some filters:

* `start_time` – the bottom time range. Only transactions with `now` more or equal to this value are iterated. If this parameter is omitted then there is no bottom time edge, so all the transactions since zero state are iterated.
* `end_time` – the upper time range. Only transactions with `now` less then this value are iterated. If this parameter is omitted then there is no upper time edge, so iterator never finishes.
* `shard_filter` – workchains and shard prefixes that reduce the set of interesting accounts. Account address conforms to the shard filter if it belongs to the filter workchain and the first bits of address match to the shard prefix. Only transactions with suitable account addresses are iterated.
* `accounts_filter` – set of account addresses whose transactions must be iterated. Note that accounts filter can conflict with shard filter so application must combine these filters carefully.

Iterated item is a JSON objects with transaction data. The minimal set of returned fields is:

```
id
account_addr
now
balance_delta(format:DEC)
bounce { bounce_type }
in_message {
    id
    value(format:DEC)
    msg_type
    src
}
out_messages {
    id
    value(format:DEC)
    msg_type
    dst
}
```

Application can request an additional fields in the `result` parameter.

Another parameter that affects on the returned fields is the `include_transfers`. When this parameter is `true` the iterator computes and adds `transfer` field containing list of the useful `TransactionTransfer` objects. Each transfer is calculated from the particular message related to the transaction and has the following structure:

* message – source message identifier.
* isBounced – indicates that the transaction is bounced, which means the value will be returned back to the sender.
* isDeposit – indicates that this transfer is the deposit (true) or withdraw (false).
* counterparty – account address of the transfer source or destination depending on `isDeposit`.
* value – amount of nano tokens transferred. The value is represented as a decimal string because the actual value can be more precise than the JSON number can represent. Application must use this string carefully – conversion to number can follow to loose of precision.

Application should call the `remove_iterator` when iterator is no longer required.

```ts
type ParamsOfCreateTransactionIterator = {
    start_time?: number,
    end_time?: number,
    shard_filter?: string[],
    accounts_filter?: string[],
    result?: string,
    include_transfers?: boolean
}

type RegisteredIterator = {
    handle: number
}

function create_transaction_iterator(
    params: ParamsOfCreateTransactionIterator,
): Promise<RegisteredIterator>;

function create_transaction_iterator_sync(
    params: ParamsOfCreateTransactionIterator,
): RegisteredIterator;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `start_time`?: *number* – Starting time to iterate from.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` >= `start_time`.\
  Otherwise the iteration starts from zero state.\
  \
  Must be specified in seconds.
* `end_time`?: *number* – Optional end time to iterate for.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` < `end_time`.\
  Otherwise the iteration never stops.\
  \
  Must be specified in seconds.
* `shard_filter`?: *string\[]* – Shard prefix filters.\
  If the application specifies this parameter and it is not an empty array\
  then the iteration will include items related to accounts that belongs to\
  the specified shard prefixes.\
  Shard prefix must be represented as a string "workchain:prefix".\
  Where `workchain` is a signed integer and the `prefix` if a hexadecimal\
  representation if the 64-bit unsigned integer with tagged shard prefix.\
  For example: "0:3800000000000000".\
  Account address conforms to the shard filter if\
  it belongs to the filter workchain and the first bits of address match to\
  the shard prefix. Only transactions with suitable account addresses are iterated.
* `accounts_filter`?: *string\[]* – Account address filter.\
  Application can specify the list of accounts for which\
  it wants to iterate transactions.\
  \
  If this parameter is missing or an empty list then the library iterates\
  transactions for all accounts that pass the shard filter.\
  \
  Note that the library doesn't detect conflicts between the account filter and the shard filter\
  if both are specified.\
  So it is an application responsibility to specify the correct filter combination.
* `result`?: *string* – Projection (result) string.\
  List of the fields that must be returned for iterated items.\
  This field is the same as the `result` parameter of\
  the `query_collection` function.\
  Note that iterated items can contain additional fields that are\
  not requested in the `result`.
* `include_transfers`?: *boolean* – Include `transfers` field in iterated transactions.\
  If this parameter is `true` then each transaction contains field\
  `transfers` with list of transfer. See more about this structure in function description.

#### Result

* `handle`: *number* – Iterator handle.\
  Must be removed using `remove_iterator`\
  when it is no more needed for the application.

### resume\_transaction\_iterator

Resumes transaction iterator.

The iterator stays exactly at the same position where the `resume_state` was caught. Note that `resume_state` doesn't store the account filter. If the application requires to use the same account filter as it was when the iterator was created then the application must pass the account filter again in `accounts_filter` parameter.

Application should call the `remove_iterator` when iterator is no longer required.

```ts
type ParamsOfResumeTransactionIterator = {
    resume_state: any,
    accounts_filter?: string[]
}

type RegisteredIterator = {
    handle: number
}

function resume_transaction_iterator(
    params: ParamsOfResumeTransactionIterator,
): Promise<RegisteredIterator>;

function resume_transaction_iterator_sync(
    params: ParamsOfResumeTransactionIterator,
): RegisteredIterator;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `resume_state`: *any* – Iterator state from which to resume.\
  Same as value returned from `iterator_next`.
* `accounts_filter`?: *string\[]* – Account address filter.\
  Application can specify the list of accounts for which\
  it wants to iterate transactions.\
  \
  If this parameter is missing or an empty list then the library iterates\
  transactions for all accounts that passes the shard filter.\
  \
  Note that the library doesn't detect conflicts between the account filter and the shard filter\
  if both are specified.\
  So it is the application's responsibility to specify the correct filter combination.

#### Result

* `handle`: *number* – Iterator handle.\
  Must be removed using `remove_iterator`\
  when it is no more needed for the application.

### iterator\_next

Returns next available items.

In addition to available items this function returns the `has_more` flag indicating that the iterator isn't reach the end of the iterated range yet.

This function can return the empty list of available items but indicates that there are more items is available. This situation appears when the iterator doesn't reach iterated range but database doesn't contains available items yet.

If application requests resume state in `return_resume_state` parameter then this function returns `resume_state` that can be used later to resume the iteration from the position after returned items.

The structure of the items returned depends on the iterator used. See the description to the appropriated iterator creation function.

```ts
type ParamsOfIteratorNext = {
    iterator: number,
    limit?: number,
    return_resume_state?: boolean
}

type ResultOfIteratorNext = {
    items: any[],
    has_more: boolean,
    resume_state?: any
}

function iterator_next(
    params: ParamsOfIteratorNext,
): Promise<ResultOfIteratorNext>;

function iterator_next_sync(
    params: ParamsOfIteratorNext,
): ResultOfIteratorNext;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `iterator`: *number* – Iterator handle
* `limit`?: *number* – Maximum count of the returned items.\
  If value is missing or is less than 1 the library uses 1.
* `return_resume_state`?: *boolean* – Indicates that function must return the iterator state that can be used for resuming iteration.

#### Result

* `items`: *any\[]* – Next available items.\
  Note that `iterator_next` can return an empty items and `has_more` equals to `true`.\
  In this case the application have to continue iteration.\
  Such situation can take place when there is no data yet but\
  the requested `end_time` is not reached.
* `has_more`: *boolean* – Indicates that there are more available items in iterated range.
* `resume_state`?: *any* – Optional iterator state that can be used for resuming iteration.\
  This field is returned only if the `return_resume_state` parameter\
  is specified.\
  \
  Note that `resume_state` corresponds to the iteration position\
  after the returned items.

### remove\_iterator

Removes an iterator

Frees all resources allocated in library to serve iterator.

Application always should call the `remove_iterator` when iterator is no longer required.

```ts
type RegisteredIterator = {
    handle: number
}

function remove_iterator(
    params: RegisteredIterator,
): Promise<void>;

function remove_iterator_sync(
    params: RegisteredIterator,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `handle`: *number* – Iterator handle.\
  Must be removed using `remove_iterator`\
  when it is no more needed for the application.

### get\_signature\_id

Returns signature ID for configured network if it should be used in messages signature

```ts
type ResultOfGetSignatureId = {
    signature_id?: number
}

function get_signature_id(): Promise<ResultOfGetSignatureId>;

function get_signature_id_sync(): ResultOfGetSignatureId;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Result

* `signature_id`?: *number* – Signature ID for configured network if it should be used in messages signature

## Types

### NetErrorCode

```ts
enum NetErrorCode {
    QueryFailed = 601,
    SubscribeFailed = 602,
    WaitForFailed = 603,
    GetSubscriptionResultFailed = 604,
    InvalidServerResponse = 605,
    ClockOutOfSync = 606,
    WaitForTimeout = 607,
    GraphqlError = 608,
    NetworkModuleSuspended = 609,
    WebsocketDisconnected = 610,
    NotSupported = 611,
    NoEndpointsProvided = 612,
    GraphqlWebsocketInitError = 613,
    NetworkModuleResumed = 614,
    Unauthorized = 615,
    QueryTransactionTreeTimeout = 616,
    GraphqlConnectionError = 617,
    WrongWebscoketProtocolSequence = 618
}
```

One of the following value:

* `QueryFailed = 601`
* `SubscribeFailed = 602`
* `WaitForFailed = 603`
* `GetSubscriptionResultFailed = 604`
* `InvalidServerResponse = 605`
* `ClockOutOfSync = 606`
* `WaitForTimeout = 607`
* `GraphqlError = 608`
* `NetworkModuleSuspended = 609`
* `WebsocketDisconnected = 610`
* `NotSupported = 611`
* `NoEndpointsProvided = 612`
* `GraphqlWebsocketInitError = 613`
* `NetworkModuleResumed = 614`
* `Unauthorized = 615`
* `QueryTransactionTreeTimeout = 616`
* `GraphqlConnectionError = 617`
* `WrongWebscoketProtocolSequence = 618`

### OrderBy

```ts
type OrderBy = {
    path: string,
    direction: SortDirection
}
```

* `path`: *string*
* `direction`: [*SortDirection*](#sortdirection)

### SortDirection

```ts
enum SortDirection {
    ASC = "ASC",
    DESC = "DESC"
}
```

One of the following value:

* `ASC = "ASC"`
* `DESC = "DESC"`

### ParamsOfQueryOperation

```ts
type ParamsOfQueryOperation = ({
    type: 'QueryCollection'
} & ParamsOfQueryCollection) | ({
    type: 'WaitForCollection'
} & ParamsOfWaitForCollection) | ({
    type: 'AggregateCollection'
} & ParamsOfAggregateCollection) | ({
    type: 'QueryCounterparties'
} & ParamsOfQueryCounterparties)
```

Depends on value of the `type` field.

When *type* is *'QueryCollection'*

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string
* `order`?: [*OrderBy*](#orderby)*\[]* – Sorting order
* `limit`?: *number* – Number of documents to return

When *type* is *'WaitForCollection'*

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string
* `timeout`?: *number* – Query timeout

When *type* is *'AggregateCollection'*

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `fields`?: [*FieldAggregation*](#fieldaggregation)*\[]* – Projection (result) string

When *type* is *'QueryCounterparties'*

* `account`: *string* – Account address
* `result`: *string* – Projection (result) string
* `first`?: *number* – Number of counterparties to return
* `after`?: *string* – `cursor` field of the last received result

Variant constructors:

```ts
function paramsOfQueryOperationQueryCollection(params: ParamsOfQueryCollection): ParamsOfQueryOperation;
function paramsOfQueryOperationWaitForCollection(params: ParamsOfWaitForCollection): ParamsOfQueryOperation;
function paramsOfQueryOperationAggregateCollection(params: ParamsOfAggregateCollection): ParamsOfQueryOperation;
function paramsOfQueryOperationQueryCounterparties(params: ParamsOfQueryCounterparties): ParamsOfQueryOperation;
```

### FieldAggregation

```ts
type FieldAggregation = {
    field: string,
    fn: AggregationFn
}
```

* `field`: *string* – Dot separated path to the field
* `fn`: [*AggregationFn*](#aggregationfn) – Aggregation function that must be applied to field values

### AggregationFn

```ts
enum AggregationFn {
    COUNT = "COUNT",
    MIN = "MIN",
    MAX = "MAX",
    SUM = "SUM",
    AVERAGE = "AVERAGE"
}
```

One of the following value:

* `COUNT = "COUNT"` – Returns count of filtered record
* `MIN = "MIN"` – Returns the minimal value for a field in filtered records
* `MAX = "MAX"` – Returns the maximal value for a field in filtered records
* `SUM = "SUM"` – Returns a sum of values for a field in filtered records
* `AVERAGE = "AVERAGE"` – Returns an average value for a field in filtered records

### TransactionNode

```ts
type TransactionNode = {
    id: string,
    in_msg: string,
    out_msgs: string[],
    account_addr: string,
    total_fees: string,
    aborted: boolean,
    exit_code?: number
}
```

* `id`: *string* – Transaction id.
* `in_msg`: *string* – In message id.
* `out_msgs`: *string\[]* – Out message ids.
* `account_addr`: *string* – Account address.
* `total_fees`: *string* – Transactions total fees.
* `aborted`: *boolean* – Aborted flag.
* `exit_code`?: *number* – Compute phase exit code.

### MessageNode

```ts
type MessageNode = {
    id: string,
    src_transaction_id?: string,
    dst_transaction_id?: string,
    src?: string,
    dst?: string,
    value?: string,
    bounce: boolean,
    decoded_body?: DecodedMessageBody
}
```

* `id`: *string* – Message id.
* `src_transaction_id`?: *string* – Source transaction id.\
  This field is missing for an external inbound messages.
* `dst_transaction_id`?: *string* – Destination transaction id.\
  This field is missing for an external outbound messages.
* `src`?: *string* – Source address.
* `dst`?: *string* – Destination address.
* `value`?: *string* – Transferred tokens value.
* `bounce`: *boolean* – Bounce flag.
* `decoded_body`?: [*DecodedMessageBody*](/ever-sdk/reference/types-and-methods/mod_abi#decodedmessagebody) – Decoded body.\
  Library tries to decode message body using provided `params.abi_registry`.\
  This field will be missing if none of the provided abi can be used to decode.

### ParamsOfQuery

```ts
type ParamsOfQuery = {
    query: string,
    variables?: any
}
```

* `query`: *string* – GraphQL query text.
* `variables`?: *any* – Variables used in query.\
  Must be a map with named values that can be used in query.

### ResultOfQuery

```ts
type ResultOfQuery = {
    result: any
}
```

* `result`: *any* – Result provided by DAppServer.

### ParamsOfBatchQuery

```ts
type ParamsOfBatchQuery = {
    operations: ParamsOfQueryOperation[]
}
```

* `operations`: [*ParamsOfQueryOperation*](#paramsofqueryoperation)*\[]* – List of query operations that must be performed per single fetch.

### ResultOfBatchQuery

```ts
type ResultOfBatchQuery = {
    results: any[]
}
```

* `results`: *any\[]* – Result values for batched queries.\
  Returns an array of values. Each value corresponds to `queries` item.

### ParamsOfQueryCollection

```ts
type ParamsOfQueryCollection = {
    collection: string,
    filter?: any,
    result: string,
    order?: OrderBy[],
    limit?: number
}
```

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string
* `order`?: [*OrderBy*](#orderby)*\[]* – Sorting order
* `limit`?: *number* – Number of documents to return

### ResultOfQueryCollection

```ts
type ResultOfQueryCollection = {
    result: any[]
}
```

* `result`: *any\[]* – Objects that match the provided criteria

### ParamsOfAggregateCollection

```ts
type ParamsOfAggregateCollection = {
    collection: string,
    filter?: any,
    fields?: FieldAggregation[]
}
```

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `fields`?: [*FieldAggregation*](#fieldaggregation)*\[]* – Projection (result) string

### ResultOfAggregateCollection

```ts
type ResultOfAggregateCollection = {
    values: any
}
```

* `values`: *any* – Values for requested fields.\
  Returns an array of strings. Each string refers to the corresponding `fields` item.\
  Numeric value is returned as a decimal string representations.

### ParamsOfWaitForCollection

```ts
type ParamsOfWaitForCollection = {
    collection: string,
    filter?: any,
    result: string,
    timeout?: number
}
```

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string
* `timeout`?: *number* – Query timeout

### ResultOfWaitForCollection

```ts
type ResultOfWaitForCollection = {
    result: any
}
```

* `result`: *any* – First found object that matches the provided criteria

### ResultOfSubscribeCollection

```ts
type ResultOfSubscribeCollection = {
    handle: number
}
```

* `handle`: *number* – Subscription handle.\
  Must be closed with `unsubscribe`

### ParamsOfSubscribeCollection

```ts
type ParamsOfSubscribeCollection = {
    collection: string,
    filter?: any,
    result: string
}
```

* `collection`: *string* – Collection name (accounts, blocks, transactions, messages, block\_signatures)
* `filter`?: *any* – Collection filter
* `result`: *string* – Projection (result) string

### ParamsOfSubscribe

```ts
type ParamsOfSubscribe = {
    subscription: string,
    variables?: any
}
```

* `subscription`: *string* – GraphQL subscription text.
* `variables`?: *any* – Variables used in subscription.\
  Must be a map with named values that can be used in query.

### ParamsOfFindLastShardBlock

```ts
type ParamsOfFindLastShardBlock = {
    address: string
}
```

* `address`: *string* – Account address

### ResultOfFindLastShardBlock

```ts
type ResultOfFindLastShardBlock = {
    block_id: string
}
```

* `block_id`: *string* – Account shard last block ID

### EndpointsSet

```ts
type EndpointsSet = {
    endpoints: string[]
}
```

* `endpoints`: *string\[]* – List of endpoints provided by server

### ResultOfGetEndpoints

```ts
type ResultOfGetEndpoints = {
    query: string,
    endpoints: string[]
}
```

* `query`: *string* – Current query endpoint
* `endpoints`: *string\[]* – List of all endpoints used by client

### ParamsOfQueryCounterparties

```ts
type ParamsOfQueryCounterparties = {
    account: string,
    result: string,
    first?: number,
    after?: string
}
```

* `account`: *string* – Account address
* `result`: *string* – Projection (result) string
* `first`?: *number* – Number of counterparties to return
* `after`?: *string* – `cursor` field of the last received result

### ParamsOfQueryTransactionTree

```ts
type ParamsOfQueryTransactionTree = {
    in_msg: string,
    abi_registry?: Abi[],
    timeout?: number,
    transaction_max_count?: number
}
```

* `in_msg`: *string* – Input message id.
* `abi_registry`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi)*\[]* – List of contract ABIs that will be used to decode message bodies. Library will try to decode each returned message body using any ABI from the registry.
* `timeout`?: *number* – Timeout used to limit waiting time for the missing messages and transaction.\
  If some of the following messages and transactions are missing yet\
  The maximum waiting time is regulated by this option.\
  \
  Default value is 60000 (1 min). If `timeout` is set to 0 then function will wait infinitely\
  until the whole transaction tree is executed
* `transaction_max_count`?: *number* – Maximum transaction count to wait.\
  If transaction tree contains more transaction then this parameter then only first `transaction_max_count` transaction are awaited and returned.\
  \
  Default value is 50. If `transaction_max_count` is set to 0 then no limitation on\
  transaction count is used and all transaction are returned.

### ResultOfQueryTransactionTree

```ts
type ResultOfQueryTransactionTree = {
    messages: MessageNode[],
    transactions: TransactionNode[]
}
```

* `messages`: [*MessageNode*](#messagenode)*\[]* – Messages.
* `transactions`: [*TransactionNode*](#transactionnode)*\[]* – Transactions.

### ParamsOfCreateBlockIterator

```ts
type ParamsOfCreateBlockIterator = {
    start_time?: number,
    end_time?: number,
    shard_filter?: string[],
    result?: string
}
```

* `start_time`?: *number* – Starting time to iterate from.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` >= `start_time`.\
  Otherwise the iteration starts from zero state.\
  \
  Must be specified in seconds.
* `end_time`?: *number* – Optional end time to iterate for.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` < `end_time`.\
  Otherwise the iteration never stops.\
  \
  Must be specified in seconds.
* `shard_filter`?: *string\[]* – Shard prefix filter.\
  If the application specifies this parameter and it is not the empty array\
  then the iteration will include items related to accounts that belongs to\
  the specified shard prefixes.\
  Shard prefix must be represented as a string "workchain:prefix".\
  Where `workchain` is a signed integer and the `prefix` if a hexadecimal\
  representation if the 64-bit unsigned integer with tagged shard prefix.\
  For example: "0:3800000000000000".
* `result`?: *string* – Projection (result) string.\
  List of the fields that must be returned for iterated items.\
  This field is the same as the `result` parameter of\
  the `query_collection` function.\
  Note that iterated items can contains additional fields that are\
  not requested in the `result`.

### RegisteredIterator

```ts
type RegisteredIterator = {
    handle: number
}
```

* `handle`: *number* – Iterator handle.\
  Must be removed using `remove_iterator`\
  when it is no more needed for the application.

### ParamsOfResumeBlockIterator

```ts
type ParamsOfResumeBlockIterator = {
    resume_state: any
}
```

* `resume_state`: *any* – Iterator state from which to resume.\
  Same as value returned from `iterator_next`.

### ParamsOfCreateTransactionIterator

```ts
type ParamsOfCreateTransactionIterator = {
    start_time?: number,
    end_time?: number,
    shard_filter?: string[],
    accounts_filter?: string[],
    result?: string,
    include_transfers?: boolean
}
```

* `start_time`?: *number* – Starting time to iterate from.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` >= `start_time`.\
  Otherwise the iteration starts from zero state.\
  \
  Must be specified in seconds.
* `end_time`?: *number* – Optional end time to iterate for.\
  If the application specifies this parameter then the iteration\
  includes blocks with `gen_utime` < `end_time`.\
  Otherwise the iteration never stops.\
  \
  Must be specified in seconds.
* `shard_filter`?: *string\[]* – Shard prefix filters.\
  If the application specifies this parameter and it is not an empty array\
  then the iteration will include items related to accounts that belongs to\
  the specified shard prefixes.\
  Shard prefix must be represented as a string "workchain:prefix".\
  Where `workchain` is a signed integer and the `prefix` if a hexadecimal\
  representation if the 64-bit unsigned integer with tagged shard prefix.\
  For example: "0:3800000000000000".\
  Account address conforms to the shard filter if\
  it belongs to the filter workchain and the first bits of address match to\
  the shard prefix. Only transactions with suitable account addresses are iterated.
* `accounts_filter`?: *string\[]* – Account address filter.\
  Application can specify the list of accounts for which\
  it wants to iterate transactions.\
  \
  If this parameter is missing or an empty list then the library iterates\
  transactions for all accounts that pass the shard filter.\
  \
  Note that the library doesn't detect conflicts between the account filter and the shard filter\
  if both are specified.\
  So it is an application responsibility to specify the correct filter combination.
* `result`?: *string* – Projection (result) string.\
  List of the fields that must be returned for iterated items.\
  This field is the same as the `result` parameter of\
  the `query_collection` function.\
  Note that iterated items can contain additional fields that are\
  not requested in the `result`.
* `include_transfers`?: *boolean* – Include `transfers` field in iterated transactions.\
  If this parameter is `true` then each transaction contains field\
  `transfers` with list of transfer. See more about this structure in function description.

### ParamsOfResumeTransactionIterator

```ts
type ParamsOfResumeTransactionIterator = {
    resume_state: any,
    accounts_filter?: string[]
}
```

* `resume_state`: *any* – Iterator state from which to resume.\
  Same as value returned from `iterator_next`.
* `accounts_filter`?: *string\[]* – Account address filter.\
  Application can specify the list of accounts for which\
  it wants to iterate transactions.\
  \
  If this parameter is missing or an empty list then the library iterates\
  transactions for all accounts that passes the shard filter.\
  \
  Note that the library doesn't detect conflicts between the account filter and the shard filter\
  if both are specified.\
  So it is the application's responsibility to specify the correct filter combination.

### ParamsOfIteratorNext

```ts
type ParamsOfIteratorNext = {
    iterator: number,
    limit?: number,
    return_resume_state?: boolean
}
```

* `iterator`: *number* – Iterator handle
* `limit`?: *number* – Maximum count of the returned items.\
  If value is missing or is less than 1 the library uses 1.
* `return_resume_state`?: *boolean* – Indicates that function must return the iterator state that can be used for resuming iteration.

### ResultOfIteratorNext

```ts
type ResultOfIteratorNext = {
    items: any[],
    has_more: boolean,
    resume_state?: any
}
```

* `items`: *any\[]* – Next available items.\
  Note that `iterator_next` can return an empty items and `has_more` equals to `true`.\
  In this case the application have to continue iteration.\
  Such situation can take place when there is no data yet but\
  the requested `end_time` is not reached.
* `has_more`: *boolean* – Indicates that there are more available items in iterated range.
* `resume_state`?: *any* – Optional iterator state that can be used for resuming iteration.\
  This field is returned only if the `return_resume_state` parameter\
  is specified.\
  \
  Note that `resume_state` corresponds to the iteration position\
  after the returned items.

### ResultOfGetSignatureId

```ts
type ResultOfGetSignatureId = {
    signature_id?: number
}
```

* `signature_id`?: *number* – Signature ID for configured network if it should be used in messages signature


# Module processing

## Module processing

Message processing module.

This module incorporates functions related to complex message processing scenarios.

### Functions

[monitor\_messages](#monitor_messages) – Starts monitoring for the processing results of the specified messages.

[get\_monitor\_info](#get_monitor_info) – Returns summary information about current state of the specified monitoring queue.

[fetch\_next\_monitor\_results](#fetch_next_monitor_results) – Fetches next resolved results from the specified monitoring queue.

[cancel\_monitor](#cancel_monitor) – Cancels all background activity and releases all allocated system resources for the specified monitoring queue.

[send\_messages](#send_messages) – Sends specified messages to the blockchain.

[send\_message](#send_message) – Sends message to the network

[wait\_for\_transaction](#wait_for_transaction) – Performs monitoring of the network for the result transaction of the external inbound message processing.

[process\_message](#process_message) – Creates message, sends it to the network and monitors its processing.

### Types

[ProcessingErrorCode](#processingerrorcode)

[ProcessingEventWillFetchFirstBlockVariant](#processingeventwillfetchfirstblockvariant) – Notifies the application that the account's current shard block will be fetched from the network. This step is performed before the message sending so that sdk knows starting from which block it will search for the transaction.

[ProcessingEventFetchFirstBlockFailedVariant](#processingeventfetchfirstblockfailedvariant) – Notifies the app that the client has failed to fetch the account's current shard block.

[ProcessingEventWillSendVariant](#processingeventwillsendvariant) – Notifies the app that the message will be sent to the network. This event means that the account's current shard block was successfully fetched and the message was successfully created (`abi.encode_message` function was executed successfully).

[ProcessingEventDidSendVariant](#processingeventdidsendvariant) – Notifies the app that the message was sent to the network, i.e `processing.send_message` was successfully executed. Now, the message is in the blockchain. If Application exits at this phase, Developer needs to proceed with processing after the application is restored with `wait_for_transaction` function, passing shard\_block\_id and message from this event.

[ProcessingEventSendFailedVariant](#processingeventsendfailedvariant) – Notifies the app that the sending operation was failed with network error.

[ProcessingEventWillFetchNextBlockVariant](#processingeventwillfetchnextblockvariant) – Notifies the app that the next shard block will be fetched from the network.

[ProcessingEventFetchNextBlockFailedVariant](#processingeventfetchnextblockfailedvariant) – Notifies the app that the next block can't be fetched.

[ProcessingEventMessageExpiredVariant](#processingeventmessageexpiredvariant) – Notifies the app that the message was not executed within expire timeout on-chain and will never be because it is already expired. The expiration timeout can be configured with `AbiConfig` parameters.

[ProcessingEventRempSentToValidatorsVariant](#processingeventrempsenttovalidatorsvariant) – Notifies the app that the message has been delivered to the thread's validators

[ProcessingEventRempIncludedIntoBlockVariant](#processingeventrempincludedintoblockvariant) – Notifies the app that the message has been successfully included into a block candidate by the thread's collator

[ProcessingEventRempIncludedIntoAcceptedBlockVariant](#processingeventrempincludedintoacceptedblockvariant) – Notifies the app that the block candidate with the message has been accepted by the thread's validators

[ProcessingEventRempOtherVariant](#processingeventrempothervariant) – Notifies the app about some other minor REMP statuses occurring during message processing

[ProcessingEventRempErrorVariant](#processingeventremperrorvariant) – Notifies the app about any problem that has occurred in REMP processing - in this case library switches to the fallback transaction awaiting scenario (sequential block reading).

[ProcessingEvent](#processingevent)

[ResultOfProcessMessage](#resultofprocessmessage)

[DecodedOutput](#decodedoutput)

[MessageMonitoringTransactionCompute](#messagemonitoringtransactioncompute)

[MessageMonitoringTransaction](#messagemonitoringtransaction)

[MessageMonitoringParams](#messagemonitoringparams)

[MessageMonitoringResult](#messagemonitoringresult)

[MonitorFetchWaitMode](#monitorfetchwaitmode)

[MonitoredMessageBocVariant](#monitoredmessagebocvariant) – BOC of the message.

[MonitoredMessageHashAddressVariant](#monitoredmessagehashaddressvariant) – Message's hash and destination address.

[MonitoredMessage](#monitoredmessage)

[MessageMonitoringStatus](#messagemonitoringstatus)

[MessageSendingParams](#messagesendingparams)

[ParamsOfMonitorMessages](#paramsofmonitormessages)

[ParamsOfGetMonitorInfo](#paramsofgetmonitorinfo)

[MonitoringQueueInfo](#monitoringqueueinfo)

[ParamsOfFetchNextMonitorResults](#paramsoffetchnextmonitorresults)

[ResultOfFetchNextMonitorResults](#resultoffetchnextmonitorresults)

[ParamsOfCancelMonitor](#paramsofcancelmonitor)

[ParamsOfSendMessages](#paramsofsendmessages)

[ResultOfSendMessages](#resultofsendmessages)

[ParamsOfSendMessage](#paramsofsendmessage)

[ResultOfSendMessage](#resultofsendmessage)

[ParamsOfWaitForTransaction](#paramsofwaitfortransaction)

[ParamsOfProcessMessage](#paramsofprocessmessage)

## Functions

### monitor\_messages

Starts monitoring for the processing results of the specified messages.

Message monitor performs background monitoring for a message processing results for the specified set of messages.

Message monitor can serve several isolated monitoring queues. Each monitor queue has a unique application defined identifier (or name) used to separate several queue's.

There are two important lists inside of the monitoring queue:

* unresolved messages: contains messages requested by the application for monitoring and not yet resolved;
* resolved results: contains resolved processing results for monitored messages.

Each monitoring queue tracks own unresolved and resolved lists. Application can add more messages to the monitoring queue at any time.

Message monitor accumulates resolved results. Application should fetch this results with `fetchNextMonitorResults` function.

When both unresolved and resolved lists becomes empty, monitor stops any background activity and frees all allocated internal memory.

If monitoring queue with specified name already exists then messages will be added to the unresolved list.

If monitoring queue with specified name does not exist then monitoring queue will be created with specified unresolved messages.

```ts
type ParamsOfMonitorMessages = {
    queue: string,
    messages: MessageMonitoringParams[]
}

function monitor_messages(
    params: ParamsOfMonitorMessages,
): Promise<void>;

function monitor_messages_sync(
    params: ParamsOfMonitorMessages,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `queue`: *string* – Name of the monitoring queue.
* `messages`: [*MessageMonitoringParams*](#messagemonitoringparams)*\[]* – Messages to start monitoring for.

### get\_monitor\_info

Returns summary information about current state of the specified monitoring queue.

```ts
type ParamsOfGetMonitorInfo = {
    queue: string
}

type MonitoringQueueInfo = {
    unresolved: number,
    resolved: number
}

function get_monitor_info(
    params: ParamsOfGetMonitorInfo,
): Promise<MonitoringQueueInfo>;

function get_monitor_info_sync(
    params: ParamsOfGetMonitorInfo,
): MonitoringQueueInfo;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `queue`: *string* – Name of the monitoring queue.

#### Result

* `unresolved`: *number* – Count of the unresolved messages.
* `resolved`: *number* – Count of resolved results.

### fetch\_next\_monitor\_results

Fetches next resolved results from the specified monitoring queue.

Results and waiting options are depends on the `wait` parameter. All returned results will be removed from the queue's resolved list.

```ts
type ParamsOfFetchNextMonitorResults = {
    queue: string,
    wait_mode?: MonitorFetchWaitMode
}

type ResultOfFetchNextMonitorResults = {
    results: MessageMonitoringResult[]
}

function fetch_next_monitor_results(
    params: ParamsOfFetchNextMonitorResults,
): Promise<ResultOfFetchNextMonitorResults>;

function fetch_next_monitor_results_sync(
    params: ParamsOfFetchNextMonitorResults,
): ResultOfFetchNextMonitorResults;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `queue`: *string* – Name of the monitoring queue.
* `wait_mode`?: [*MonitorFetchWaitMode*](#monitorfetchwaitmode) – Wait mode.\
  Default is `NO_WAIT`.

#### Result

* `results`: [*MessageMonitoringResult*](#messagemonitoringresult)*\[]* – List of the resolved results.

### cancel\_monitor

Cancels all background activity and releases all allocated system resources for the specified monitoring queue.

```ts
type ParamsOfCancelMonitor = {
    queue: string
}

function cancel_monitor(
    params: ParamsOfCancelMonitor,
): Promise<void>;

function cancel_monitor_sync(
    params: ParamsOfCancelMonitor,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `queue`: *string* – Name of the monitoring queue.

### send\_messages

Sends specified messages to the blockchain.

```ts
type ParamsOfSendMessages = {
    messages: MessageSendingParams[],
    monitor_queue?: string
}

type ResultOfSendMessages = {
    messages: MessageMonitoringParams[]
}

function send_messages(
    params: ParamsOfSendMessages,
): Promise<ResultOfSendMessages>;

function send_messages_sync(
    params: ParamsOfSendMessages,
): ResultOfSendMessages;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `messages`: [*MessageSendingParams*](#messagesendingparams)*\[]* – Messages that must be sent to the blockchain.
* `monitor_queue`?: *string* – Optional message monitor queue that starts monitoring for the processing results for sent messages.

#### Result

* `messages`: [*MessageMonitoringParams*](#messagemonitoringparams)*\[]* – Messages that was sent to the blockchain for execution.

### send\_message

Sends message to the network

Sends message to the network and returns the last generated shard block of the destination account before the message was sent. It will be required later for message processing.

```ts
type ParamsOfSendMessage = {
    message: string,
    abi?: Abi,
    send_events?: boolean
}

type ResultOfSendMessage = {
    shard_block_id: string,
    sending_endpoints: string[]
}

function send_message(
    params: ParamsOfSendMessage,
    responseHandler?: ResponseHandler,
): Promise<ResultOfSendMessage>;

function send_message_sync(
    params: ParamsOfSendMessage,
): ResultOfSendMessage;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `message`: *string* – Message BOC.
* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Optional message ABI.\
  If this parameter is specified and the message has the\
  `expire` header then expiration time will be checked against\
  the current time to prevent unnecessary sending of already expired message.\
  \
  The `message already expired` error will be returned in this\
  case.\
  \
  Note, that specifying `abi` for ABI compliant contracts is\
  strongly recommended, so that proper processing strategy can be\
  chosen.
* `send_events`?: *boolean* – Flag for requesting events sending. Default is `false`.
* `responseHandler`?: [*ResponseHandler*](/ever-sdk/reference/types-and-methods/modules#responsehandler) – additional responses handler.

#### Result

* `shard_block_id`: *string* – The last generated shard block of the message destination account before the message was sent.\
  This block id must be used as a parameter of the\
  `wait_for_transaction`.
* `sending_endpoints`: *string\[]* – The list of endpoints to which the message was sent.\
  This list id must be used as a parameter of the\
  `wait_for_transaction`.

### wait\_for\_transaction

Performs monitoring of the network for the result transaction of the external inbound message processing.

`send_events` enables intermediate events, such as `WillFetchNextBlock`, `FetchNextBlockFailed` that may be useful for logging of new shard blocks creation during message processing.

Note, that presence of the `abi` parameter is critical for ABI compliant contracts. Message processing uses drastically different strategy for processing message for contracts which ABI includes "expire" header.

When the ABI header `expire` is present, the processing uses `message expiration` strategy:

* The maximum block gen time is set to `message_expiration_timeout + transaction_wait_timeout`.
* When maximum block gen time is reached, the processing will be finished with `MessageExpired` error.

When the ABI header `expire` isn't present or `abi` parameter isn't specified, the processing uses `transaction waiting` strategy:

* The maximum block gen time is set to `now() + transaction_wait_timeout`.
* If maximum block gen time is reached and no result transaction is found, the processing will exit with an error.

```ts
type ParamsOfWaitForTransaction = {
    abi?: Abi,
    message: string,
    shard_block_id: string,
    send_events?: boolean,
    sending_endpoints?: string[]
}

type ResultOfProcessMessage = {
    transaction: any,
    out_messages: string[],
    decoded?: DecodedOutput,
    fees: TransactionFees
}

function wait_for_transaction(
    params: ParamsOfWaitForTransaction,
    responseHandler?: ResponseHandler,
): Promise<ResultOfProcessMessage>;

function wait_for_transaction_sync(
    params: ParamsOfWaitForTransaction,
): ResultOfProcessMessage;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Optional ABI for decoding the transaction result.\
  If it is specified, then the output messages' bodies will be\
  decoded according to this ABI.\
  \
  The `abi_decoded` result field will be filled out.
* `message`: *string* – Message BOC.\
  Encoded with `base64`.
* `shard_block_id`: *string* – The last generated block id of the destination account shard before the message was sent.\
  You must provide the same value as the `send_message` has returned.
* `send_events`?: *boolean* – Flag that enables/disables intermediate events. Default is `false`.
* `sending_endpoints`?: *string\[]* – The list of endpoints to which the message was sent.\
  Use this field to get more informative errors.\
  Provide the same value as the `send_message` has returned.\
  If the message was not delivered (expired), SDK will log the endpoint URLs, used for its sending.
* `responseHandler`?: [*ResponseHandler*](/ever-sdk/reference/types-and-methods/modules#responsehandler) – additional responses handler.

#### Result

* `transaction`: *any* – Parsed transaction.\
  In addition to the regular transaction fields there is a\
  `boc` field encoded with `base64` which contains source\
  transaction BOC.
* `out_messages`: *string\[]* – List of output messages' BOCs.\
  Encoded as `base64`
* `decoded`?: [*DecodedOutput*](#decodedoutput) – Optional decoded message bodies according to the optional `abi` parameter.
* `fees`: [*TransactionFees*](/ever-sdk/reference/types-and-methods/mod_tvm#transactionfees) – Transaction fees

### process\_message

Creates message, sends it to the network and monitors its processing.

Creates ABI-compatible message, sends it to the network and monitors for the result transaction. Decodes the output messages' bodies.

If contract's ABI includes "expire" header, then SDK implements retries in case of unsuccessful message delivery within the expiration timeout: SDK recreates the message, sends it and processes it again.

The intermediate events, such as `WillFetchFirstBlock`, `WillSend`, `DidSend`, `WillFetchNextBlock`, etc - are switched on/off by `send_events` flag and logged into the supplied callback function.

The retry configuration parameters are defined in the client's `NetworkConfig` and `AbiConfig`.

If contract's ABI does not include "expire" header then, if no transaction is found within the network timeout (see config parameter ), exits with error.

```ts
type ParamsOfProcessMessage = {
    message_encode_params: ParamsOfEncodeMessage,
    send_events?: boolean
}

type ResultOfProcessMessage = {
    transaction: any,
    out_messages: string[],
    decoded?: DecodedOutput,
    fees: TransactionFees
}

function process_message(
    params: ParamsOfProcessMessage,
    responseHandler?: ResponseHandler,
): Promise<ResultOfProcessMessage>;

function process_message_sync(
    params: ParamsOfProcessMessage,
): ResultOfProcessMessage;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `message_encode_params`: [*ParamsOfEncodeMessage*](/ever-sdk/reference/types-and-methods/mod_abi#paramsofencodemessage) – Message encode parameters.
* `send_events`?: *boolean* – Flag for requesting events sending. Default is `false`.
* `responseHandler`?: [*ResponseHandler*](/ever-sdk/reference/types-and-methods/modules#responsehandler) – additional responses handler.

#### Result

* `transaction`: *any* – Parsed transaction.\
  In addition to the regular transaction fields there is a\
  `boc` field encoded with `base64` which contains source\
  transaction BOC.
* `out_messages`: *string\[]* – List of output messages' BOCs.\
  Encoded as `base64`
* `decoded`?: [*DecodedOutput*](#decodedoutput) – Optional decoded message bodies according to the optional `abi` parameter.
* `fees`: [*TransactionFees*](/ever-sdk/reference/types-and-methods/mod_tvm#transactionfees) – Transaction fees

## Types

### ProcessingErrorCode

```ts
enum ProcessingErrorCode {
    MessageAlreadyExpired = 501,
    MessageHasNotDestinationAddress = 502,
    CanNotBuildMessageCell = 503,
    FetchBlockFailed = 504,
    SendMessageFailed = 505,
    InvalidMessageBoc = 506,
    MessageExpired = 507,
    TransactionWaitTimeout = 508,
    InvalidBlockReceived = 509,
    CanNotCheckBlockShard = 510,
    BlockNotFound = 511,
    InvalidData = 512,
    ExternalSignerMustNotBeUsed = 513,
    MessageRejected = 514,
    InvalidRempStatus = 515,
    NextRempStatusTimeout = 516
}
```

One of the following value:

* `MessageAlreadyExpired = 501`
* `MessageHasNotDestinationAddress = 502`
* `CanNotBuildMessageCell = 503`
* `FetchBlockFailed = 504`
* `SendMessageFailed = 505`
* `InvalidMessageBoc = 506`
* `MessageExpired = 507`
* `TransactionWaitTimeout = 508`
* `InvalidBlockReceived = 509`
* `CanNotCheckBlockShard = 510`
* `BlockNotFound = 511`
* `InvalidData = 512`
* `ExternalSignerMustNotBeUsed = 513`
* `MessageRejected = 514`
* `InvalidRempStatus = 515`
* `NextRempStatusTimeout = 516`

### ProcessingEventWillFetchFirstBlockVariant

Notifies the application that the account's current shard block will be fetched from the network. This step is performed before the message sending so that sdk knows starting from which block it will search for the transaction.

Fetched block will be used later in waiting phase.

```ts
type ProcessingEventWillFetchFirstBlockVariant = {
    message_id: string,
    message_dst: string
}
```

* `message_id`: *string*
* `message_dst`: *string*

### ProcessingEventFetchFirstBlockFailedVariant

Notifies the app that the client has failed to fetch the account's current shard block.

This may happen due to the network issues. Receiving this event means that message processing will not proceed - message was not sent, and Developer can try to run `process_message` again, in the hope that the connection is restored.

```ts
type ProcessingEventFetchFirstBlockFailedVariant = {
    error: ClientError,
    message_id: string,
    message_dst: string
}
```

* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)
* `message_id`: *string*
* `message_dst`: *string*

### ProcessingEventWillSendVariant

Notifies the app that the message will be sent to the network. This event means that the account's current shard block was successfully fetched and the message was successfully created (`abi.encode_message` function was executed successfully).

```ts
type ProcessingEventWillSendVariant = {
    shard_block_id: string,
    message_id: string,
    message_dst: string,
    message: string
}
```

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*

### ProcessingEventDidSendVariant

Notifies the app that the message was sent to the network, i.e `processing.send_message` was successfully executed. Now, the message is in the blockchain. If Application exits at this phase, Developer needs to proceed with processing after the application is restored with `wait_for_transaction` function, passing shard\_block\_id and message from this event.

Do not forget to specify abi of your contract as well, it is crucial for processing. See `processing.wait_for_transaction` documentation.

```ts
type ProcessingEventDidSendVariant = {
    shard_block_id: string,
    message_id: string,
    message_dst: string,
    message: string
}
```

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*

### ProcessingEventSendFailedVariant

Notifies the app that the sending operation was failed with network error.

Nevertheless the processing will be continued at the waiting phase because the message possibly has been delivered to the node. If Application exits at this phase, Developer needs to proceed with processing after the application is restored with `wait_for_transaction` function, passing shard\_block\_id and message from this event. Do not forget to specify abi of your contract as well, it is crucial for processing. See `processing.wait_for_transaction` documentation.

```ts
type ProcessingEventSendFailedVariant = {
    shard_block_id: string,
    message_id: string,
    message_dst: string,
    message: string,
    error: ClientError
}
```

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

### ProcessingEventWillFetchNextBlockVariant

Notifies the app that the next shard block will be fetched from the network.

Event can occurs more than one time due to block walking procedure. If Application exits at this phase, Developer needs to proceed with processing after the application is restored with `wait_for_transaction` function, passing shard\_block\_id and message from this event. Do not forget to specify abi of your contract as well, it is crucial for processing. See `processing.wait_for_transaction` documentation.

```ts
type ProcessingEventWillFetchNextBlockVariant = {
    shard_block_id: string,
    message_id: string,
    message_dst: string,
    message: string
}
```

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*

### ProcessingEventFetchNextBlockFailedVariant

Notifies the app that the next block can't be fetched.

If no block was fetched within `NetworkConfig.wait_for_timeout` then processing stops. This may happen when the shard stops, or there are other network issues. In this case Developer should resume message processing with `wait_for_transaction`, passing shard\_block\_id, message and contract abi to it. Note that passing ABI is crucial, because it will influence the processing strategy.

Another way to tune this is to specify long timeout in `NetworkConfig.wait_for_timeout`

```ts
type ProcessingEventFetchNextBlockFailedVariant = {
    shard_block_id: string,
    message_id: string,
    message_dst: string,
    message: string,
    error: ClientError
}
```

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

### ProcessingEventMessageExpiredVariant

Notifies the app that the message was not executed within expire timeout on-chain and will never be because it is already expired. The expiration timeout can be configured with `AbiConfig` parameters.

This event occurs only for the contracts which ABI includes "expire" header.

If Application specifies `NetworkConfig.message_retries_count` > 0, then `process_message` will perform retries: will create a new message and send it again and repeat it until it reaches the maximum retries count or receives a successful result. All the processing events will be repeated.

```ts
type ProcessingEventMessageExpiredVariant = {
    message_id: string,
    message_dst: string,
    message: string,
    error: ClientError
}
```

* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

### ProcessingEventRempSentToValidatorsVariant

Notifies the app that the message has been delivered to the thread's validators

```ts
type ProcessingEventRempSentToValidatorsVariant = {
    message_id: string,
    message_dst: string,
    timestamp: bigint,
    json: any
}
```

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

### ProcessingEventRempIncludedIntoBlockVariant

Notifies the app that the message has been successfully included into a block candidate by the thread's collator

```ts
type ProcessingEventRempIncludedIntoBlockVariant = {
    message_id: string,
    message_dst: string,
    timestamp: bigint,
    json: any
}
```

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

### ProcessingEventRempIncludedIntoAcceptedBlockVariant

Notifies the app that the block candidate with the message has been accepted by the thread's validators

```ts
type ProcessingEventRempIncludedIntoAcceptedBlockVariant = {
    message_id: string,
    message_dst: string,
    timestamp: bigint,
    json: any
}
```

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

### ProcessingEventRempOtherVariant

Notifies the app about some other minor REMP statuses occurring during message processing

```ts
type ProcessingEventRempOtherVariant = {
    message_id: string,
    message_dst: string,
    timestamp: bigint,
    json: any
}
```

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

### ProcessingEventRempErrorVariant

Notifies the app about any problem that has occurred in REMP processing - in this case library switches to the fallback transaction awaiting scenario (sequential block reading).

```ts
type ProcessingEventRempErrorVariant = {
    message_id: string,
    message_dst: string,
    error: ClientError
}
```

* `message_id`: *string*
* `message_dst`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

### ProcessingEvent

```ts
type ProcessingEvent = ({
    type: 'WillFetchFirstBlock'
} & ProcessingEventWillFetchFirstBlockVariant) | ({
    type: 'FetchFirstBlockFailed'
} & ProcessingEventFetchFirstBlockFailedVariant) | ({
    type: 'WillSend'
} & ProcessingEventWillSendVariant) | ({
    type: 'DidSend'
} & ProcessingEventDidSendVariant) | ({
    type: 'SendFailed'
} & ProcessingEventSendFailedVariant) | ({
    type: 'WillFetchNextBlock'
} & ProcessingEventWillFetchNextBlockVariant) | ({
    type: 'FetchNextBlockFailed'
} & ProcessingEventFetchNextBlockFailedVariant) | ({
    type: 'MessageExpired'
} & ProcessingEventMessageExpiredVariant) | ({
    type: 'RempSentToValidators'
} & ProcessingEventRempSentToValidatorsVariant) | ({
    type: 'RempIncludedIntoBlock'
} & ProcessingEventRempIncludedIntoBlockVariant) | ({
    type: 'RempIncludedIntoAcceptedBlock'
} & ProcessingEventRempIncludedIntoAcceptedBlockVariant) | ({
    type: 'RempOther'
} & ProcessingEventRempOtherVariant) | ({
    type: 'RempError'
} & ProcessingEventRempErrorVariant)
```

Depends on value of the `type` field.

When *type* is *'WillFetchFirstBlock'*

Notifies the application that the account's current shard block will be fetched from the network. This step is performed before the message sending so that sdk knows starting from which block it will search for the transaction.

Fetched block will be used later in waiting phase.

* `message_id`: *string*
* `message_dst`: *string*

When *type* is *'FetchFirstBlockFailed'*

Notifies the app that the client has failed to fetch the account's current shard block.

This may happen due to the network issues. Receiving this event means that message processing will not proceed - message was not sent, and Developer can try to run `process_message` again, in the hope that the connection is restored.

* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)
* `message_id`: *string*
* `message_dst`: *string*

When *type* is *'WillSend'*

Notifies the app that the message will be sent to the network. This event means that the account's current shard block was successfully fetched and the message was successfully created (`abi.encode_message` function was executed successfully).

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*

When *type* is *'DidSend'*

Notifies the app that the message was sent to the network, i.e `processing.send_message` was successfully executed. Now, the message is in the blockchain. If Application exits at this phase, Developer needs to proceed with processing after the application is restored with `wait_for_transaction` function, passing shard\_block\_id and message from this event.

Do not forget to specify abi of your contract as well, it is crucial for processing. See `processing.wait_for_transaction` documentation.

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*

When *type* is *'SendFailed'*

Notifies the app that the sending operation was failed with network error.

Nevertheless the processing will be continued at the waiting phase because the message possibly has been delivered to the node. If Application exits at this phase, Developer needs to proceed with processing after the application is restored with `wait_for_transaction` function, passing shard\_block\_id and message from this event. Do not forget to specify abi of your contract as well, it is crucial for processing. See `processing.wait_for_transaction` documentation.

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

When *type* is *'WillFetchNextBlock'*

Notifies the app that the next shard block will be fetched from the network.

Event can occurs more than one time due to block walking procedure. If Application exits at this phase, Developer needs to proceed with processing after the application is restored with `wait_for_transaction` function, passing shard\_block\_id and message from this event. Do not forget to specify abi of your contract as well, it is crucial for processing. See `processing.wait_for_transaction` documentation.

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*

When *type* is *'FetchNextBlockFailed'*

Notifies the app that the next block can't be fetched.

If no block was fetched within `NetworkConfig.wait_for_timeout` then processing stops. This may happen when the shard stops, or there are other network issues. In this case Developer should resume message processing with `wait_for_transaction`, passing shard\_block\_id, message and contract abi to it. Note that passing ABI is crucial, because it will influence the processing strategy.

Another way to tune this is to specify long timeout in `NetworkConfig.wait_for_timeout`

* `shard_block_id`: *string*
* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

When *type* is *'MessageExpired'*

Notifies the app that the message was not executed within expire timeout on-chain and will never be because it is already expired. The expiration timeout can be configured with `AbiConfig` parameters.

This event occurs only for the contracts which ABI includes "expire" header.

If Application specifies `NetworkConfig.message_retries_count` > 0, then `process_message` will perform retries: will create a new message and send it again and repeat it until it reaches the maximum retries count or receives a successful result. All the processing events will be repeated.

* `message_id`: *string*
* `message_dst`: *string*
* `message`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

When *type* is *'RempSentToValidators'*

Notifies the app that the message has been delivered to the thread's validators

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

When *type* is *'RempIncludedIntoBlock'*

Notifies the app that the message has been successfully included into a block candidate by the thread's collator

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

When *type* is *'RempIncludedIntoAcceptedBlock'*

Notifies the app that the block candidate with the message has been accepted by the thread's validators

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

When *type* is *'RempOther'*

Notifies the app about some other minor REMP statuses occurring during message processing

* `message_id`: *string*
* `message_dst`: *string*
* `timestamp`: *bigint*
* `json`: *any*

When *type* is *'RempError'*

Notifies the app about any problem that has occurred in REMP processing - in this case library switches to the fallback transaction awaiting scenario (sequential block reading).

* `message_id`: *string*
* `message_dst`: *string*
* `error`: [*ClientError*](/ever-sdk/reference/types-and-methods/mod_client#clienterror)

Variant constructors:

```ts
function processingEventWillFetchFirstBlock(message_id: string, message_dst: string): ProcessingEvent;
function processingEventFetchFirstBlockFailed(error: ClientError, message_id: string, message_dst: string): ProcessingEvent;
function processingEventWillSend(shard_block_id: string, message_id: string, message_dst: string, message: string): ProcessingEvent;
function processingEventDidSend(shard_block_id: string, message_id: string, message_dst: string, message: string): ProcessingEvent;
function processingEventSendFailed(shard_block_id: string, message_id: string, message_dst: string, message: string, error: ClientError): ProcessingEvent;
function processingEventWillFetchNextBlock(shard_block_id: string, message_id: string, message_dst: string, message: string): ProcessingEvent;
function processingEventFetchNextBlockFailed(shard_block_id: string, message_id: string, message_dst: string, message: string, error: ClientError): ProcessingEvent;
function processingEventMessageExpired(message_id: string, message_dst: string, message: string, error: ClientError): ProcessingEvent;
function processingEventRempSentToValidators(message_id: string, message_dst: string, timestamp: bigint, json: any): ProcessingEvent;
function processingEventRempIncludedIntoBlock(message_id: string, message_dst: string, timestamp: bigint, json: any): ProcessingEvent;
function processingEventRempIncludedIntoAcceptedBlock(message_id: string, message_dst: string, timestamp: bigint, json: any): ProcessingEvent;
function processingEventRempOther(message_id: string, message_dst: string, timestamp: bigint, json: any): ProcessingEvent;
function processingEventRempError(message_id: string, message_dst: string, error: ClientError): ProcessingEvent;
```

### ResultOfProcessMessage

```ts
type ResultOfProcessMessage = {
    transaction: any,
    out_messages: string[],
    decoded?: DecodedOutput,
    fees: TransactionFees
}
```

* `transaction`: *any* – Parsed transaction.\
  In addition to the regular transaction fields there is a\
  `boc` field encoded with `base64` which contains source\
  transaction BOC.
* `out_messages`: *string\[]* – List of output messages' BOCs.\
  Encoded as `base64`
* `decoded`?: [*DecodedOutput*](#decodedoutput) – Optional decoded message bodies according to the optional `abi` parameter.
* `fees`: [*TransactionFees*](/ever-sdk/reference/types-and-methods/mod_tvm#transactionfees) – Transaction fees

### DecodedOutput

```ts
type DecodedOutput = {
    out_messages: DecodedMessageBody | null[],
    output?: any
}
```

* `out_messages`: [*DecodedMessageBody*](/ever-sdk/reference/types-and-methods/mod_abi#decodedmessagebody)*?\[]* – Decoded bodies of the out messages.\
  If the message can't be decoded, then `None` will be stored in\
  the appropriate position.
* `output`?: *any* – Decoded body of the function output message.

### MessageMonitoringTransactionCompute

```ts
type MessageMonitoringTransactionCompute = {
    exit_code: number
}
```

* `exit_code`: *number* – Compute phase exit code.

### MessageMonitoringTransaction

```ts
type MessageMonitoringTransaction = {
    hash?: string,
    aborted: boolean,
    compute?: MessageMonitoringTransactionCompute
}
```

* `hash`?: *string* – Hash of the transaction. Present if transaction was included into the blocks. When then transaction was emulated this field will be missing.
* `aborted`: *boolean* – Aborted field of the transaction.
* `compute`?: [*MessageMonitoringTransactionCompute*](#messagemonitoringtransactioncompute) – Optional information about the compute phase of the transaction.

### MessageMonitoringParams

```ts
type MessageMonitoringParams = {
    message: MonitoredMessage,
    wait_until: number,
    user_data?: any
}
```

* `message`: [*MonitoredMessage*](#monitoredmessage) – Monitored message identification. Can be provided as a message's BOC or (hash, address) pair. BOC is a preferable way because it helps to determine possible error reason (using TVM execution of the message).
* `wait_until`: *number* – Block time Must be specified as a UNIX timestamp in seconds
* `user_data`?: *any* – User defined data associated with this message. Helps to identify this message when user received `MessageMonitoringResult`.

### MessageMonitoringResult

```ts
type MessageMonitoringResult = {
    hash: string,
    status: MessageMonitoringStatus,
    transaction?: MessageMonitoringTransaction,
    error?: string,
    user_data?: any
}
```

* `hash`: *string* – Hash of the message.
* `status`: [*MessageMonitoringStatus*](#messagemonitoringstatus) – Processing status.
* `transaction`?: [*MessageMonitoringTransaction*](#messagemonitoringtransaction) – In case of `Finalized` the transaction is extracted from the block. In case of `Timeout` the transaction is emulated using the last known account state.
* `error`?: *string* – In case of `Timeout` contains possible error reason.
* `user_data`?: *any* – User defined data related to this message. This is the same value as passed before with `MessageMonitoringParams` or `SendMessageParams`.

### MonitorFetchWaitMode

```ts
enum MonitorFetchWaitMode {
    AtLeastOne = "AtLeastOne",
    All = "All",
    NoWait = "NoWait"
}
```

One of the following value:

* `AtLeastOne = "AtLeastOne"` – If there are no resolved results yet, then monitor awaits for the next resolved result.
* `All = "All"` – Monitor waits until all unresolved messages will be resolved. If there are no unresolved messages then monitor will wait.
* `NoWait = "NoWait"`

### MonitoredMessageBocVariant

BOC of the message.

```ts
type MonitoredMessageBocVariant = {
    boc: string
}
```

* `boc`: *string*

### MonitoredMessageHashAddressVariant

Message's hash and destination address.

```ts
type MonitoredMessageHashAddressVariant = {
    hash: string,
    address: string
}
```

* `hash`: *string* – Hash of the message.
* `address`: *string* – Destination address of the message.

### MonitoredMessage

```ts
type MonitoredMessage = ({
    type: 'Boc'
} & MonitoredMessageBocVariant) | ({
    type: 'HashAddress'
} & MonitoredMessageHashAddressVariant)
```

Depends on value of the `type` field.

When *type* is *'Boc'*

BOC of the message.

* `boc`: *string*

When *type* is *'HashAddress'*

Message's hash and destination address.

* `hash`: *string* – Hash of the message.
* `address`: *string* – Destination address of the message.

Variant constructors:

```ts
function monitoredMessageBoc(boc: string): MonitoredMessage;
function monitoredMessageHashAddress(hash: string, address: string): MonitoredMessage;
```

### MessageMonitoringStatus

```ts
enum MessageMonitoringStatus {
    Finalized = "Finalized",
    Timeout = "Timeout",
    Reserved = "Reserved"
}
```

One of the following value:

* `Finalized = "Finalized"` – Returned when the messages was processed and included into finalized block before `wait_until` block time.
* `Timeout = "Timeout"` – Returned when the message was not processed until `wait_until` block time.
* `Reserved = "Reserved"` – Reserved for future statuses.\
  Is never returned. Application should wait for one of the `Finalized` or `Timeout` statuses.\
  All other statuses are intermediate.

### MessageSendingParams

```ts
type MessageSendingParams = {
    boc: string,
    wait_until: number,
    user_data?: any
}
```

* `boc`: *string* – BOC of the message, that must be sent to the blockchain.
* `wait_until`: *number* – Expiration time of the message. Must be specified as a UNIX timestamp in seconds.
* `user_data`?: *any* – User defined data associated with this message. Helps to identify this message when user received `MessageMonitoringResult`.

### ParamsOfMonitorMessages

```ts
type ParamsOfMonitorMessages = {
    queue: string,
    messages: MessageMonitoringParams[]
}
```

* `queue`: *string* – Name of the monitoring queue.
* `messages`: [*MessageMonitoringParams*](#messagemonitoringparams)*\[]* – Messages to start monitoring for.

### ParamsOfGetMonitorInfo

```ts
type ParamsOfGetMonitorInfo = {
    queue: string
}
```

* `queue`: *string* – Name of the monitoring queue.

### MonitoringQueueInfo

```ts
type MonitoringQueueInfo = {
    unresolved: number,
    resolved: number
}
```

* `unresolved`: *number* – Count of the unresolved messages.
* `resolved`: *number* – Count of resolved results.

### ParamsOfFetchNextMonitorResults

```ts
type ParamsOfFetchNextMonitorResults = {
    queue: string,
    wait_mode?: MonitorFetchWaitMode
}
```

* `queue`: *string* – Name of the monitoring queue.
* `wait_mode`?: [*MonitorFetchWaitMode*](#monitorfetchwaitmode) – Wait mode.\
  Default is `NO_WAIT`.

### ResultOfFetchNextMonitorResults

```ts
type ResultOfFetchNextMonitorResults = {
    results: MessageMonitoringResult[]
}
```

* `results`: [*MessageMonitoringResult*](#messagemonitoringresult)*\[]* – List of the resolved results.

### ParamsOfCancelMonitor

```ts
type ParamsOfCancelMonitor = {
    queue: string
}
```

* `queue`: *string* – Name of the monitoring queue.

### ParamsOfSendMessages

```ts
type ParamsOfSendMessages = {
    messages: MessageSendingParams[],
    monitor_queue?: string
}
```

* `messages`: [*MessageSendingParams*](#messagesendingparams)*\[]* – Messages that must be sent to the blockchain.
* `monitor_queue`?: *string* – Optional message monitor queue that starts monitoring for the processing results for sent messages.

### ResultOfSendMessages

```ts
type ResultOfSendMessages = {
    messages: MessageMonitoringParams[]
}
```

* `messages`: [*MessageMonitoringParams*](#messagemonitoringparams)*\[]* – Messages that was sent to the blockchain for execution.

### ParamsOfSendMessage

```ts
type ParamsOfSendMessage = {
    message: string,
    abi?: Abi,
    send_events?: boolean
}
```

* `message`: *string* – Message BOC.
* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Optional message ABI.\
  If this parameter is specified and the message has the\
  `expire` header then expiration time will be checked against\
  the current time to prevent unnecessary sending of already expired message.\
  \
  The `message already expired` error will be returned in this\
  case.\
  \
  Note, that specifying `abi` for ABI compliant contracts is\
  strongly recommended, so that proper processing strategy can be\
  chosen.
* `send_events`?: *boolean* – Flag for requesting events sending. Default is `false`.

### ResultOfSendMessage

```ts
type ResultOfSendMessage = {
    shard_block_id: string,
    sending_endpoints: string[]
}
```

* `shard_block_id`: *string* – The last generated shard block of the message destination account before the message was sent.\
  This block id must be used as a parameter of the\
  `wait_for_transaction`.
* `sending_endpoints`: *string\[]* – The list of endpoints to which the message was sent.\
  This list id must be used as a parameter of the\
  `wait_for_transaction`.

### ParamsOfWaitForTransaction

```ts
type ParamsOfWaitForTransaction = {
    abi?: Abi,
    message: string,
    shard_block_id: string,
    send_events?: boolean,
    sending_endpoints?: string[]
}
```

* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Optional ABI for decoding the transaction result.\
  If it is specified, then the output messages' bodies will be\
  decoded according to this ABI.\
  \
  The `abi_decoded` result field will be filled out.
* `message`: *string* – Message BOC.\
  Encoded with `base64`.
* `shard_block_id`: *string* – The last generated block id of the destination account shard before the message was sent.\
  You must provide the same value as the `send_message` has returned.
* `send_events`?: *boolean* – Flag that enables/disables intermediate events. Default is `false`.
* `sending_endpoints`?: *string\[]* – The list of endpoints to which the message was sent.\
  Use this field to get more informative errors.\
  Provide the same value as the `send_message` has returned.\
  If the message was not delivered (expired), SDK will log the endpoint URLs, used for its sending.

### ParamsOfProcessMessage

```ts
type ParamsOfProcessMessage = {
    message_encode_params: ParamsOfEncodeMessage,
    send_events?: boolean
}
```

* `message_encode_params`: [*ParamsOfEncodeMessage*](/ever-sdk/reference/types-and-methods/mod_abi#paramsofencodemessage) – Message encode parameters.
* `send_events`?: *boolean* – Flag for requesting events sending. Default is `false`.


# Module proofs

## Module proofs

[UNSTABLE](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tonlabs/TON-SDK/blob/gitbook/docs/reference/types-and-methods/DEPRECATED.md) Module for proving data, retrieved from TONOS API.

### Functions

[proof\_block\_data](#proof_block_data) – Proves that a given block's data, which is queried from TONOS API, can be trusted.

[proof\_transaction\_data](#proof_transaction_data) – Proves that a given transaction's data, which is queried from TONOS API, can be trusted.

[proof\_message\_data](#proof_message_data) – Proves that a given message's data, which is queried from TONOS API, can be trusted.

### Types

[ProofsErrorCode](#proofserrorcode)

[ParamsOfProofBlockData](#paramsofproofblockdata)

[ParamsOfProofTransactionData](#paramsofprooftransactiondata)

[ParamsOfProofMessageData](#paramsofproofmessagedata)

## Functions

### proof\_block\_data

Proves that a given block's data, which is queried from TONOS API, can be trusted.

This function checks block proofs and compares given data with the proven. If the given data differs from the proven, the exception will be thrown. The input param is a single block's JSON object, which was queried from DApp server using functions such as `net.query`, `net.query_collection` or `net.wait_for_collection`. If block's BOC is not provided in the JSON, it will be queried from DApp server (in this case it is required to provide at least `id` of block).

Please note, that joins (like `signatures` in `Block`) are separated entities and not supported, so function will throw an exception in a case if JSON being checked has such entities in it.

If `cache_in_local_storage` in config is set to `true` (default), downloaded proofs and master-chain BOCs are saved into the persistent local storage (e.g. file system for native environments or browser's IndexedDB for the web); otherwise all the data is cached only in memory in current client's context and will be lost after destruction of the client.

**Why Proofs are needed**

Proofs are needed to ensure that the data downloaded from a DApp server is real blockchain data. Checking proofs can protect from the malicious DApp server which can potentially provide fake data, or also from "Man in the Middle" attacks class.

**What Proofs are**

Simply, proof is a list of signatures of validators', which have signed this particular master- block.

The very first validator set's public keys are included in the zero-state. Whe know a root hash of the zero-state, because it is stored in the network configuration file, it is our authority root. For proving zero-state it is enough to calculate and compare its root hash.

In each new validator cycle the validator set is changed. The new one is stored in a key-block, which is signed by the validator set, which we already trust, the next validator set will be stored to the new key-block and signed by the current validator set, and so on.

In order to prove any block in the master-chain we need to check, that it has been signed by a trusted validator set. So we need to check all key-blocks' proofs, started from the zero-state and until the block, which we want to prove. But it can take a lot of time and traffic to download and prove all key-blocks on a client. For solving this, special trusted blocks are used in Ever-SDK.

The trusted block is the authority root, as well, as the zero-state. Each trusted block is the `id` (e.g. `root_hash`) of the already proven key-block. There can be plenty of trusted blocks, so there can be a lot of authority roots. The hashes of trusted blocks for MainNet and DevNet are hardcoded in SDK in a separated binary file (trusted\_key\_blocks.bin) and is being updated for each release by using `update_trusted_blocks` utility.

See [update\_trusted\_blocks](https://github.com/tonlabs/TON-SDK/blob/gitbook/tools/update_trusted_blocks/README.md) directory for more info.

In future SDK releases, one will also be able to provide their hashes of trusted blocks for other networks, besides for MainNet and DevNet. By using trusted key-blocks, in order to prove any block, we can prove chain of key-blocks to the closest previous trusted key-block, not only to the zero-state.

But shard-blocks don't have proofs on DApp server. In this case, in order to prove any shard- block data, we search for a corresponding master-block, which contains the root hash of this shard-block, or some shard block which is linked to that block in shard-chain. After proving this master-block, we traverse through each link and calculate and compare hashes with links, one-by-one. After that we can ensure that this shard-block has also been proven.

```ts
type ParamsOfProofBlockData = {
    block: any
}

function proof_block_data(
    params: ParamsOfProofBlockData,
): Promise<void>;

function proof_block_data_sync(
    params: ParamsOfProofBlockData,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `block`: *any* – Single block's data, retrieved from TONOS API, that needs proof. Required fields are `id` and/or top-level `boc` (for block identification), others are optional.

### proof\_transaction\_data

Proves that a given transaction's data, which is queried from TONOS API, can be trusted.

This function requests the corresponding block, checks block proofs, ensures that given transaction exists in the proven block and compares given data with the proven. If the given data differs from the proven, the exception will be thrown. The input parameter is a single transaction's JSON object (see params description), which was queried from TONOS API using functions such as `net.query`, `net.query_collection` or `net.wait_for_collection`.

If transaction's BOC and/or `block_id` are not provided in the JSON, they will be queried from TONOS API.

Please note, that joins (like `account`, `in_message`, `out_messages`, etc. in `Transaction` entity) are separated entities and not supported, so function will throw an exception in a case if JSON being checked has such entities in it.

For more information about proofs checking, see description of `proof_block_data` function.

```ts
type ParamsOfProofTransactionData = {
    transaction: any
}

function proof_transaction_data(
    params: ParamsOfProofTransactionData,
): Promise<void>;

function proof_transaction_data_sync(
    params: ParamsOfProofTransactionData,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `transaction`: *any* – Single transaction's data as queried from DApp server, without modifications. The required fields are `id` and/or top-level `boc`, others are optional. In order to reduce network requests count, it is recommended to provide `block_id` and `boc` of transaction.

### proof\_message\_data

Proves that a given message's data, which is queried from TONOS API, can be trusted.

This function first proves the corresponding transaction, ensures that the proven transaction refers to the given message and compares given data with the proven. If the given data differs from the proven, the exception will be thrown. The input parameter is a single message's JSON object (see params description), which was queried from TONOS API using functions such as `net.query`, `net.query_collection` or `net.wait_for_collection`.

If message's BOC and/or non-null `src_transaction.id` or `dst_transaction.id` are not provided in the JSON, they will be queried from TONOS API.

Please note, that joins (like `block`, `dst_account`, `dst_transaction`, `src_account`, `src_transaction`, etc. in `Message` entity) are separated entities and not supported, so function will throw an exception in a case if JSON being checked has such entities in it.

For more information about proofs checking, see description of `proof_block_data` function.

```ts
type ParamsOfProofMessageData = {
    message: any
}

function proof_message_data(
    params: ParamsOfProofMessageData,
): Promise<void>;

function proof_message_data_sync(
    params: ParamsOfProofMessageData,
): void;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `message`: *any* – Single message's data as queried from DApp server, without modifications. The required fields are `id` and/or top-level `boc`, others are optional. In order to reduce network requests count, it is recommended to provide at least `boc` of message and non-null `src_transaction.id` or `dst_transaction.id`.

## Types

### ProofsErrorCode

```ts
enum ProofsErrorCode {
    InvalidData = 901,
    ProofCheckFailed = 902,
    InternalError = 903,
    DataDiffersFromProven = 904
}
```

One of the following value:

* `InvalidData = 901`
* `ProofCheckFailed = 902`
* `InternalError = 903`
* `DataDiffersFromProven = 904`

### ParamsOfProofBlockData

```ts
type ParamsOfProofBlockData = {
    block: any
}
```

* `block`: *any* – Single block's data, retrieved from TONOS API, that needs proof. Required fields are `id` and/or top-level `boc` (for block identification), others are optional.

### ParamsOfProofTransactionData

```ts
type ParamsOfProofTransactionData = {
    transaction: any
}
```

* `transaction`: *any* – Single transaction's data as queried from DApp server, without modifications. The required fields are `id` and/or top-level `boc`, others are optional. In order to reduce network requests count, it is recommended to provide `block_id` and `boc` of transaction.

### ParamsOfProofMessageData

```ts
type ParamsOfProofMessageData = {
    message: any
}
```

* `message`: *any* – Single message's data as queried from DApp server, without modifications. The required fields are `id` and/or top-level `boc`, others are optional. In order to reduce network requests count, it is recommended to provide at least `boc` of message and non-null `src_transaction.id` or `dst_transaction.id`.


# Module tvm

## Module tvm

### Functions

[run\_executor](#run_executor) – Emulates all the phases of contract execution locally

[run\_tvm](#run_tvm) – Executes get-methods of ABI-compatible contracts

[run\_get](#run_get) – Executes a get-method of FIFT contract

### Types

[TvmErrorCode](#tvmerrorcode)

[ExecutionOptions](#executionoptions)

[AccountForExecutorNoneVariant](#accountforexecutornonevariant) – Non-existing account to run a creation internal message. Should be used with `skip_transaction_check = true` if the message has no deploy data since transactions on the uninitialized account are always aborted

[AccountForExecutorUninitVariant](#accountforexecutoruninitvariant) – Emulate uninitialized account to run deploy message

[AccountForExecutorAccountVariant](#accountforexecutoraccountvariant) – Account state to run message

[AccountForExecutor](#accountforexecutor)

[TransactionFees](#transactionfees)

[ParamsOfRunExecutor](#paramsofrunexecutor)

[ResultOfRunExecutor](#resultofrunexecutor)

[ParamsOfRunTvm](#paramsofruntvm)

[ResultOfRunTvm](#resultofruntvm)

[ParamsOfRunGet](#paramsofrunget)

[ResultOfRunGet](#resultofrunget)

## Functions

### run\_executor

Emulates all the phases of contract execution locally

Performs all the phases of contract execution on Transaction Executor - the same component that is used on Validator Nodes.

Can be used for contract debugging, to find out the reason why a message was not delivered successfully. Validators throw away the failed external inbound messages (if they failed before `ACCEPT`) in the real network. This is why these messages are impossible to debug in the real network. With the help of run\_executor you can do that. In fact, `process_message` function performs local check with `run_executor` if there was no transaction as a result of processing and returns the error, if there is one.

Another use case to use `run_executor` is to estimate fees for message execution. Set `AccountForExecutor::Account.unlimited_balance` to `true` so that emulation will not depend on the actual balance. This may be needed to calculate deploy fees for an account that does not exist yet. JSON with fees is in `fees` field of the result.

One more use case - you can produce the sequence of operations, thus emulating the sequential contract calls locally. And so on.

Transaction executor requires account BOC (bag of cells) as a parameter. To get the account BOC - use `net.query` method to download it from GraphQL API (field `boc` of `account`) or generate it with `abi.encode_account` method.

Also it requires message BOC. To get the message BOC - use `abi.encode_message` or `abi.encode_internal_message`.

If you need this emulation to be as precise as possible (for instance - emulate transaction with particular lt in particular block or use particular blockchain config, downloaded from a particular key block - then specify `execution_options` parameter.

If you need to see the aborted transaction as a result, not as an error, set `skip_transaction_check` to `true`.

```ts
type ParamsOfRunExecutor = {
    message: string,
    account: AccountForExecutor,
    execution_options?: ExecutionOptions,
    abi?: Abi,
    skip_transaction_check?: boolean,
    boc_cache?: BocCacheType,
    return_updated_account?: boolean
}

type ResultOfRunExecutor = {
    transaction: any,
    out_messages: string[],
    decoded?: DecodedOutput,
    account: string,
    fees: TransactionFees
}

function run_executor(
    params: ParamsOfRunExecutor,
): Promise<ResultOfRunExecutor>;

function run_executor_sync(
    params: ParamsOfRunExecutor,
): ResultOfRunExecutor;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `message`: *string* – Input message BOC.\
  Must be encoded as base64.
* `account`: [*AccountForExecutor*](#accountforexecutor) – Account to run on executor
* `execution_options`?: [*ExecutionOptions*](#executionoptions) – Execution options.
* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `skip_transaction_check`?: *boolean* – Skip transaction check flag
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided
* `return_updated_account`?: *boolean* – Return updated account flag.\
  Empty string is returned if the flag is `false`

#### Result

* `transaction`: *any* – Parsed transaction.\
  In addition to the regular transaction fields there is a\
  `boc` field encoded with `base64` which contains source\
  transaction BOC.
* `out_messages`: *string\[]* – List of output messages' BOCs.\
  Encoded as `base64`
* `decoded`?: [*DecodedOutput*](/ever-sdk/reference/types-and-methods/mod_processing#decodedoutput) – Optional decoded message bodies according to the optional `abi` parameter.
* `account`: *string* – Updated account state BOC.\
  Encoded as `base64`
* `fees`: [*TransactionFees*](#transactionfees) – Transaction fees

### run\_tvm

Executes get-methods of ABI-compatible contracts

Performs only a part of compute phase of transaction execution that is used to run get-methods of ABI-compatible contracts.

If you try to run get-methods with `run_executor` you will get an error, because it checks ACCEPT and exits if there is none, which is actually true for get-methods.

To get the account BOC (bag of cells) - use `net.query` method to download it from GraphQL API (field `boc` of `account`) or generate it with `abi.encode_account method`. To get the message BOC - use `abi.encode_message` or prepare it any other way, for instance, with FIFT script.

Attention! Updated account state is produces as well, but only `account_state.storage.state.data` part of the BOC is updated.

```ts
type ParamsOfRunTvm = {
    message: string,
    account: string,
    execution_options?: ExecutionOptions,
    abi?: Abi,
    boc_cache?: BocCacheType,
    return_updated_account?: boolean
}

type ResultOfRunTvm = {
    out_messages: string[],
    decoded?: DecodedOutput,
    account: string
}

function run_tvm(
    params: ParamsOfRunTvm,
): Promise<ResultOfRunTvm>;

function run_tvm_sync(
    params: ParamsOfRunTvm,
): ResultOfRunTvm;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `message`: *string* – Input message BOC.\
  Must be encoded as base64.
* `account`: *string* – Account BOC.\
  Must be encoded as base64.
* `execution_options`?: [*ExecutionOptions*](#executionoptions) – Execution options.
* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided
* `return_updated_account`?: *boolean* – Return updated account flag.\
  Empty string is returned if the flag is `false`

#### Result

* `out_messages`: *string\[]* – List of output messages' BOCs.\
  Encoded as `base64`
* `decoded`?: [*DecodedOutput*](/ever-sdk/reference/types-and-methods/mod_processing#decodedoutput) – Optional decoded message bodies according to the optional `abi` parameter.
* `account`: *string* – Updated account state BOC.\
  Encoded as `base64`. Attention! Only `account_state.storage.state.data` part of the BOC is updated.

### run\_get

Executes a get-method of FIFT contract

Executes a get-method of FIFT contract that fulfills the smc-guidelines <https://test.ton.org/smc-guidelines.txt> and returns the result data from TVM's stack

```ts
type ParamsOfRunGet = {
    account: string,
    function_name: string,
    input?: any,
    execution_options?: ExecutionOptions,
    tuple_list_as_array?: boolean
}

type ResultOfRunGet = {
    output: any
}

function run_get(
    params: ParamsOfRunGet,
): Promise<ResultOfRunGet>;

function run_get_sync(
    params: ParamsOfRunGet,
): ResultOfRunGet;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `account`: *string* – Account BOC in `base64`
* `function_name`: *string* – Function name
* `input`?: *any* – Input parameters
* `execution_options`?: [*ExecutionOptions*](#executionoptions) – Execution options
* `tuple_list_as_array`?: *boolean* – Convert lists based on nested tuples in the **result** into plain arrays.\
  Default is `false`. Input parameters may use any of lists representations\
  If you receive this error on Web: "Runtime error. Unreachable code should not be executed...",\
  set this flag to true.\
  This may happen, for example, when elector contract contains too many participants

#### Result

* `output`: *any* – Values returned by get-method on stack

## Types

### TvmErrorCode

```ts
enum TvmErrorCode {
    CanNotReadTransaction = 401,
    CanNotReadBlockchainConfig = 402,
    TransactionAborted = 403,
    InternalError = 404,
    ActionPhaseFailed = 405,
    AccountCodeMissing = 406,
    LowBalance = 407,
    AccountFrozenOrDeleted = 408,
    AccountMissing = 409,
    UnknownExecutionError = 410,
    InvalidInputStack = 411,
    InvalidAccountBoc = 412,
    InvalidMessageType = 413,
    ContractExecutionError = 414,
    AccountIsSuspended = 415
}
```

One of the following value:

* `CanNotReadTransaction = 401`
* `CanNotReadBlockchainConfig = 402`
* `TransactionAborted = 403`
* `InternalError = 404`
* `ActionPhaseFailed = 405`
* `AccountCodeMissing = 406`
* `LowBalance = 407`
* `AccountFrozenOrDeleted = 408`
* `AccountMissing = 409`
* `UnknownExecutionError = 410`
* `InvalidInputStack = 411`
* `InvalidAccountBoc = 412`
* `InvalidMessageType = 413`
* `ContractExecutionError = 414`
* `AccountIsSuspended = 415`

### ExecutionOptions

```ts
type ExecutionOptions = {
    blockchain_config?: string,
    block_time?: number,
    block_lt?: bigint,
    transaction_lt?: bigint,
    chksig_always_succeed?: boolean,
    signature_id?: number
}
```

* `blockchain_config`?: *string* – boc with config
* `block_time`?: *number* – time that is used as transaction time
* `block_lt`?: *bigint* – block logical time
* `transaction_lt`?: *bigint* – transaction logical time
* `chksig_always_succeed`?: *boolean* – Overrides standard TVM behaviour. If set to `true` then CHKSIG always will return `true`.
* `signature_id`?: *number* – Signature ID to be used in signature verifying instructions when CapSignatureWithId capability is enabled

### AccountForExecutorNoneVariant

Non-existing account to run a creation internal message. Should be used with `skip_transaction_check = true` if the message has no deploy data since transactions on the uninitialized account are always aborted

```ts
type AccountForExecutorNoneVariant = {

}
```

### AccountForExecutorUninitVariant

Emulate uninitialized account to run deploy message

```ts
type AccountForExecutorUninitVariant = {

}
```

### AccountForExecutorAccountVariant

Account state to run message

```ts
type AccountForExecutorAccountVariant = {
    boc: string,
    unlimited_balance?: boolean
}
```

* `boc`: *string* – Account BOC.\
  Encoded as base64.
* `unlimited_balance`?: *boolean* – Flag for running account with the unlimited balance.\
  Can be used to calculate transaction fees without balance check

### AccountForExecutor

```ts
type AccountForExecutor = ({
    type: 'None'
} & AccountForExecutorNoneVariant) | ({
    type: 'Uninit'
} & AccountForExecutorUninitVariant) | ({
    type: 'Account'
} & AccountForExecutorAccountVariant)
```

Depends on value of the `type` field.

When *type* is *'None'*

Non-existing account to run a creation internal message. Should be used with `skip_transaction_check = true` if the message has no deploy data since transactions on the uninitialized account are always aborted

When *type* is *'Uninit'*

Emulate uninitialized account to run deploy message

When *type* is *'Account'*

Account state to run message

* `boc`: *string* – Account BOC.\
  Encoded as base64.
* `unlimited_balance`?: *boolean* – Flag for running account with the unlimited balance.\
  Can be used to calculate transaction fees without balance check

Variant constructors:

```ts
function accountForExecutorNone(): AccountForExecutor;
function accountForExecutorUninit(): AccountForExecutor;
function accountForExecutorAccount(boc: string, unlimited_balance?: boolean): AccountForExecutor;
```

### TransactionFees

```ts
type TransactionFees = {
    in_msg_fwd_fee: bigint,
    storage_fee: bigint,
    gas_fee: bigint,
    out_msgs_fwd_fee: bigint,
    total_account_fees: bigint,
    total_output: bigint,
    ext_in_msg_fee: bigint,
    total_fwd_fees: bigint,
    account_fees: bigint
}
```

* `in_msg_fwd_fee`: *bigint* – Deprecated.\
  Contains the same data as ext\_in\_msg\_fee field
* `storage_fee`: *bigint* – Fee for account storage
* `gas_fee`: *bigint* – Fee for processing
* `out_msgs_fwd_fee`: *bigint* – Deprecated.\
  Contains the same data as total\_fwd\_fees field. Deprecated because of its confusing name, that is not the same with GraphQL API Transaction type's field.
* `total_account_fees`: *bigint* – Deprecated.\
  Contains the same data as account\_fees field
* `total_output`: *bigint* – Deprecated because it means total value sent in the transaction, which does not relate to any fees.
* `ext_in_msg_fee`: *bigint* – Fee for inbound external message import.
* `total_fwd_fees`: *bigint* – Total fees the account pays for message forwarding
* `account_fees`: *bigint* – Total account fees for the transaction execution. Compounds of storage\_fee + gas\_fee + ext\_in\_msg\_fee + total\_fwd\_fees

### ParamsOfRunExecutor

```ts
type ParamsOfRunExecutor = {
    message: string,
    account: AccountForExecutor,
    execution_options?: ExecutionOptions,
    abi?: Abi,
    skip_transaction_check?: boolean,
    boc_cache?: BocCacheType,
    return_updated_account?: boolean
}
```

* `message`: *string* – Input message BOC.\
  Must be encoded as base64.
* `account`: [*AccountForExecutor*](#accountforexecutor) – Account to run on executor
* `execution_options`?: [*ExecutionOptions*](#executionoptions) – Execution options.
* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `skip_transaction_check`?: *boolean* – Skip transaction check flag
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided
* `return_updated_account`?: *boolean* – Return updated account flag.\
  Empty string is returned if the flag is `false`

### ResultOfRunExecutor

```ts
type ResultOfRunExecutor = {
    transaction: any,
    out_messages: string[],
    decoded?: DecodedOutput,
    account: string,
    fees: TransactionFees
}
```

* `transaction`: *any* – Parsed transaction.\
  In addition to the regular transaction fields there is a\
  `boc` field encoded with `base64` which contains source\
  transaction BOC.
* `out_messages`: *string\[]* – List of output messages' BOCs.\
  Encoded as `base64`
* `decoded`?: [*DecodedOutput*](/ever-sdk/reference/types-and-methods/mod_processing#decodedoutput) – Optional decoded message bodies according to the optional `abi` parameter.
* `account`: *string* – Updated account state BOC.\
  Encoded as `base64`
* `fees`: [*TransactionFees*](#transactionfees) – Transaction fees

### ParamsOfRunTvm

```ts
type ParamsOfRunTvm = {
    message: string,
    account: string,
    execution_options?: ExecutionOptions,
    abi?: Abi,
    boc_cache?: BocCacheType,
    return_updated_account?: boolean
}
```

* `message`: *string* – Input message BOC.\
  Must be encoded as base64.
* `account`: *string* – Account BOC.\
  Must be encoded as base64.
* `execution_options`?: [*ExecutionOptions*](#executionoptions) – Execution options.
* `abi`?: [*Abi*](/ever-sdk/reference/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `boc_cache`?: [*BocCacheType*](/ever-sdk/reference/types-and-methods/mod_boc#boccachetype) – Cache type to put the result.\
  The BOC itself returned if no cache type provided
* `return_updated_account`?: *boolean* – Return updated account flag.\
  Empty string is returned if the flag is `false`

### ResultOfRunTvm

```ts
type ResultOfRunTvm = {
    out_messages: string[],
    decoded?: DecodedOutput,
    account: string
}
```

* `out_messages`: *string\[]* – List of output messages' BOCs.\
  Encoded as `base64`
* `decoded`?: [*DecodedOutput*](/ever-sdk/reference/types-and-methods/mod_processing#decodedoutput) – Optional decoded message bodies according to the optional `abi` parameter.
* `account`: *string* – Updated account state BOC.\
  Encoded as `base64`. Attention! Only `account_state.storage.state.data` part of the BOC is updated.

### ParamsOfRunGet

```ts
type ParamsOfRunGet = {
    account: string,
    function_name: string,
    input?: any,
    execution_options?: ExecutionOptions,
    tuple_list_as_array?: boolean
}
```

* `account`: *string* – Account BOC in `base64`
* `function_name`: *string* – Function name
* `input`?: *any* – Input parameters
* `execution_options`?: [*ExecutionOptions*](#executionoptions) – Execution options
* `tuple_list_as_array`?: *boolean* – Convert lists based on nested tuples in the **result** into plain arrays.\
  Default is `false`. Input parameters may use any of lists representations\
  If you receive this error on Web: "Runtime error. Unreachable code should not be executed...",\
  set this flag to true.\
  This may happen, for example, when elector contract contains too many participants

### ResultOfRunGet

```ts
type ResultOfRunGet = {
    output: any
}
```

* `output`: *any* – Values returned by get-method on stack


# Module utils

## Module utils

Misc utility Functions.

### Functions

[convert\_address](#convert_address) – Converts address from any TON format to any TON format

[get\_address\_type](#get_address_type) – Validates and returns the type of any TON address.

[calc\_storage\_fee](#calc_storage_fee) – Calculates storage fee for an account over a specified time period

[compress\_zstd](#compress_zstd) – Compresses data using Zstandard algorithm

[decompress\_zstd](#decompress_zstd) – Decompresses data using Zstandard algorithm

### Types

[AddressStringFormatAccountIdVariant](#addressstringformataccountidvariant)

[AddressStringFormatHexVariant](#addressstringformathexvariant)

[AddressStringFormatBase64Variant](#addressstringformatbase64variant)

[AddressStringFormat](#addressstringformat)

[AccountAddressType](#accountaddresstype)

[ParamsOfConvertAddress](#paramsofconvertaddress)

[ResultOfConvertAddress](#resultofconvertaddress)

[ParamsOfGetAddressType](#paramsofgetaddresstype)

[ResultOfGetAddressType](#resultofgetaddresstype)

[ParamsOfCalcStorageFee](#paramsofcalcstoragefee)

[ResultOfCalcStorageFee](#resultofcalcstoragefee)

[ParamsOfCompressZstd](#paramsofcompresszstd)

[ResultOfCompressZstd](#resultofcompresszstd)

[ParamsOfDecompressZstd](#paramsofdecompresszstd)

[ResultOfDecompressZstd](#resultofdecompresszstd)

## Functions

### convert\_address

Converts address from any TON format to any TON format

```ts
type ParamsOfConvertAddress = {
    address: string,
    output_format: AddressStringFormat
}

type ResultOfConvertAddress = {
    address: string
}

function convert_address(
    params: ParamsOfConvertAddress,
): Promise<ResultOfConvertAddress>;

function convert_address_sync(
    params: ParamsOfConvertAddress,
): ResultOfConvertAddress;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `address`: *string* – Account address in any TON format.
* `output_format`: [*AddressStringFormat*](#addressstringformat) – Specify the format to convert to.

#### Result

* `address`: *string* – Address in the specified format

### get\_address\_type

Validates and returns the type of any TON address.

Address types are the following

`0:919db8e740d50bf349df2eea03fa30c385d846b991ff5542e67098ee833fc7f7` - standard TON address most commonly used in all cases. Also called as hex address `919db8e740d50bf349df2eea03fa30c385d846b991ff5542e67098ee833fc7f7` - account ID. A part of full address. Identifies account inside particular workchain `EQCRnbjnQNUL80nfLuoD+jDDhdhGuZH/VULmcJjugz/H9wam` - base64 address. Also called "user-friendly". Was used at the beginning of TON. Now it is supported for compatibility

```ts
type ParamsOfGetAddressType = {
    address: string
}

type ResultOfGetAddressType = {
    address_type: AccountAddressType
}

function get_address_type(
    params: ParamsOfGetAddressType,
): Promise<ResultOfGetAddressType>;

function get_address_type_sync(
    params: ParamsOfGetAddressType,
): ResultOfGetAddressType;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `address`: *string* – Account address in any TON format.

#### Result

* `address_type`: [*AccountAddressType*](#accountaddresstype) – Account address type.

### calc\_storage\_fee

Calculates storage fee for an account over a specified time period

```ts
type ParamsOfCalcStorageFee = {
    account: string,
    period: number
}

type ResultOfCalcStorageFee = {
    fee: string
}

function calc_storage_fee(
    params: ParamsOfCalcStorageFee,
): Promise<ResultOfCalcStorageFee>;

function calc_storage_fee_sync(
    params: ParamsOfCalcStorageFee,
): ResultOfCalcStorageFee;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `account`: *string*
* `period`: *number*

#### Result

* `fee`: *string*

### compress\_zstd

Compresses data using Zstandard algorithm

```ts
type ParamsOfCompressZstd = {
    uncompressed: string,
    level?: number
}

type ResultOfCompressZstd = {
    compressed: string
}

function compress_zstd(
    params: ParamsOfCompressZstd,
): Promise<ResultOfCompressZstd>;

function compress_zstd_sync(
    params: ParamsOfCompressZstd,
): ResultOfCompressZstd;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `uncompressed`: *string* – Uncompressed data.\
  Must be encoded as base64.
* `level`?: *number* – Compression level, from 1 to 21. Where: 1 - lowest compression level (fastest compression); 21 - highest compression level (slowest compression). If level is omitted, the default compression level is used (currently `3`).

#### Result

* `compressed`: *string* – Compressed data.\
  Must be encoded as base64.

### decompress\_zstd

Decompresses data using Zstandard algorithm

```ts
type ParamsOfDecompressZstd = {
    compressed: string
}

type ResultOfDecompressZstd = {
    decompressed: string
}

function decompress_zstd(
    params: ParamsOfDecompressZstd,
): Promise<ResultOfDecompressZstd>;

function decompress_zstd_sync(
    params: ParamsOfDecompressZstd,
): ResultOfDecompressZstd;
```

NOTE: Sync version is available only for `lib-node` binding.

#### Parameters

* `compressed`: *string* – Compressed data.\
  Must be encoded as base64.

#### Result

* `decompressed`: *string* – Decompressed data.\
  Must be encoded as base64.

## Types

### AddressStringFormatAccountIdVariant

```ts
type AddressStringFormatAccountIdVariant = {

}
```

### AddressStringFormatHexVariant

```ts
type AddressStringFormatHexVariant = {

}
```

### AddressStringFormatBase64Variant

```ts
type AddressStringFormatBase64Variant = {
    url: boolean,
    test: boolean,
    bounce: boolean
}
```

* `url`: *boolean*
* `test`: *boolean*
* `bounce`: *boolean*

### AddressStringFormat

```ts
type AddressStringFormat = ({
    type: 'AccountId'
} & AddressStringFormatAccountIdVariant) | ({
    type: 'Hex'
} & AddressStringFormatHexVariant) | ({
    type: 'Base64'
} & AddressStringFormatBase64Variant)
```

Depends on value of the `type` field.

When *type* is *'AccountId'*

When *type* is *'Hex'*

When *type* is *'Base64'*

* `url`: *boolean*
* `test`: *boolean*
* `bounce`: *boolean*

Variant constructors:

```ts
function addressStringFormatAccountId(): AddressStringFormat;
function addressStringFormatHex(): AddressStringFormat;
function addressStringFormatBase64(url: boolean, test: boolean, bounce: boolean): AddressStringFormat;
```

### AccountAddressType

```ts
enum AccountAddressType {
    AccountId = "AccountId",
    Hex = "Hex",
    Base64 = "Base64"
}
```

One of the following value:

* `AccountId = "AccountId"`
* `Hex = "Hex"`
* `Base64 = "Base64"`

### ParamsOfConvertAddress

```ts
type ParamsOfConvertAddress = {
    address: string,
    output_format: AddressStringFormat
}
```

* `address`: *string* – Account address in any TON format.
* `output_format`: [*AddressStringFormat*](#addressstringformat) – Specify the format to convert to.

### ResultOfConvertAddress

```ts
type ResultOfConvertAddress = {
    address: string
}
```

* `address`: *string* – Address in the specified format

### ParamsOfGetAddressType

```ts
type ParamsOfGetAddressType = {
    address: string
}
```

* `address`: *string* – Account address in any TON format.

### ResultOfGetAddressType

```ts
type ResultOfGetAddressType = {
    address_type: AccountAddressType
}
```

* `address_type`: [*AccountAddressType*](#accountaddresstype) – Account address type.

### ParamsOfCalcStorageFee

```ts
type ParamsOfCalcStorageFee = {
    account: string,
    period: number
}
```

* `account`: *string*
* `period`: *number*

### ResultOfCalcStorageFee

```ts
type ResultOfCalcStorageFee = {
    fee: string
}
```

* `fee`: *string*

### ParamsOfCompressZstd

```ts
type ParamsOfCompressZstd = {
    uncompressed: string,
    level?: number
}
```

* `uncompressed`: *string* – Uncompressed data.\
  Must be encoded as base64.
* `level`?: *number* – Compression level, from 1 to 21. Where: 1 - lowest compression level (fastest compression); 21 - highest compression level (slowest compression). If level is omitted, the default compression level is used (currently `3`).

### ResultOfCompressZstd

```ts
type ResultOfCompressZstd = {
    compressed: string
}
```

* `compressed`: *string* – Compressed data.\
  Must be encoded as base64.

### ParamsOfDecompressZstd

```ts
type ParamsOfDecompressZstd = {
    compressed: string
}
```

* `compressed`: *string* – Compressed data.\
  Must be encoded as base64.

### ResultOfDecompressZstd

```ts
type ResultOfDecompressZstd = {
    decompressed: string
}
```

* `decompressed`: *string* – Decompressed data.\
  Must be encoded as base64.


# Error API

SDK Error API

* [TONClientError](#tonclienterror)
  * [Properties](#properties)
* [Types](#types)
  * [ErrorData](#errordata)
* [Error example](#error-example)

## TONClientError

### Properties

**code: number**

Unique error code

**message: string**

Error description

**data: ErrorData**

Additional data provided with error. All the fields in `ErrorData` are optional and their presence depends on the error code.

## Types

### ErrorData

All the fields in `ErrorData` are optional and their presence depends on the error code.

```
{
    message_id?: string,
    shard_block_id?: string
    core_version?: string,
    waiting_expiration_time?:string,
    block_time?: string,
    phase?: string
    exit_code
    exit_arg
    account_address?: string
    local_error: ErrorData
}
```

**message\_id**

Message id

**shard\_block\_id**

The last shardchain block of the account received before the error occurred.

**core\_version**

Core library binary version used

**waiting\_expiration\_time**

Message expiration time.

**block\_time**

Creation time of the last shardchain block of the account received before the error occurred.

**phase**

Transaction execution phase when contract execution was aborted

**exit\_code**

Exit code of exception thrown by the aborted contract execution

**exit\_arg**

Exit args provided along with exit code

**account\_address**

Address of the account

**local\_error: ErrorData**

Result of local transaction emulation performed after the message was not successfully delivered.

## Error example

Here you can see an error returned by process\_message function when message was not delivered to the blockchain and got expired (code 507).

In such cases SDK emulated the same transaction locally and here it got a local\_error with possible reason - wrong signature - exit code = 40.

```
{
  "code": 507,
  "message": "Message expired. Possible reason: Contract execution was terminated with error: Contract did not accept message, exit code: 40 (Invalid signature). Check sign keys. For more information about exit code check the contract source code or ask the contract developer",
  "data": {
    "message_id": "31ed01a8c91d06e526cef015b406273377c41710216cc160af9428e1bb263671",
    "shard_block_id": "c8c8020c4404b099ec3af2a38373875c1fb8128ff0e61ed3186e8d822533a99f",
    "core_version": "1.6.1",
    "waiting_expiration_time": "Thu, 04 Feb 2021 00:49:29 +0300 (1612388969)",
    "block_time": "Thu, 04 Feb 2021 00:49:30 +0300 (1612388970)",
    "local_error": {
      "code": 414,
      "message": "Contract execution was terminated with error: Contract did not accept message, exit code: 40 (Invalid signature). Check sign keys. For more information about exit code check the contract source code or ask the contract developer",
      "data": {
        "core_version": "1.6.1",
        "phase": "computeVm",
        "exit_code": 40,
        "exit_arg": "0",
        "account_address": "0:c6cfd0506f8d33891690b34fafe3f686873afc42653ef88a11d73e4866fda928",
        "description": "Invalid signature"
      }
    }
  }
}
```


# Error Codes

You can find error codes with descriptions on this page

* [SDK Errors](#sdk-errors)
* [Solidity Runtime Errors](#solidity-runtime-errors)
* [TON Virtual Machine Runtime Errors](#ton-virtual-machine-runtime-errors)
  * [Action phase errors](#action-phase-errors)

## SDK Errors

[Client Error codes (1-99)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_client#clienterrorcode)

[Crypto Error codes (100-199)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_crypto#cryptoerrorcode)

[Boc error codes(200-299)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_boc#bocerrorcode)

[Abi Error codes (300-399)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_abi#abierrorcode)

[TVM Error codes (400-499)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_tvm#tvmerrorcode)

[Processing Error codes (500-599)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_processing#processingerrorcode)

[Net Error Codes (600-699)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_net#neterrorcode)

[DeBot Error Codes (800-899)](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_debot#deboterrorcode)

## Solidity Runtime Errors

<https://github.com/everx-labs/TVM-Solidity-Compiler/blob/master/API.md#solidity-runtime-errors>

## TON Virtual Machine Runtime Errors

`0` TVM terminated successfully

`-2` TVM terminated successfully: alternative code

`-3` Stack underflow

`-4` Stack overflow

`-5` Integer overflow

`-6` Range check error

`-7` Invalid opcode

`-8` Type check error

`-9` Cell overflow

`-10` Cell underflow

`-11` Dictionary error

`-12` Unknown error

`-13` Fatal error

`-14` Out of gas: the contract is either low on gas, or its limit is exceeded

### Action phase errors

`32` Action list invalid

`33` Too many actions

`34` Unsupported action

`35` Invalid source address

`36` Invalid destination address

`37` Too low balance to send outbound message (37) at action

`38` Too low extra to send outbound message (38) at action

`39` Message does not fit in buffer

`40` Message too large

`41` Library not found

`42` Library delete error


# Installation

This section contains the following installation guides:

* [Add SDK to your App](/ever-sdk/guides/installation/add_sdk_to_your_app)


# Add SDK to your App

[Node.js](#nodejs) | [Web](#web)

## Node.js

> Our library is fully-annotated with `.d.ts` files so we recommend to write your applications in Typescript.

Let's start with a clean npm project.

```
mkdir hello
cd hello
npm init -y
```

Now lets install core package and bridge package for Node.js

```
npm i --save @eversdk/core
npm i --save @eversdk/lib-node
```

If you want to use high-level [AppKit](https://github.com/everx-labs/ever-appkit-js) package then install this package as well:

```
npm i --save @eversdk/appkit
```

You must initialize the library before the first use. The best place to do it is an initialization code of your application.

You need to attach the chosen binary module to the `TonClient` class. Create `index.js` file and add this code:

```
const {TonClient} = require("@eversdk/core");
const {libNode} = require("@eversdk/lib-node");

// Application initialization
TonClient.useBinaryLibrary(libNode)
```

That's it! Now you are ready to create and[ configure TONClient object!](/ever-sdk/guides/configuration/endpoint-configuration)

## Web

> Our library is fully-annotated with `.d.ts` files so we recommend to write your applications in Typescript.

Let's start with a clean project.

```
mkdir hello
cd hello
npm init -y
```

**Installation**

Now lets install core package and bridge package for Web

```
npm i --save @eversdk/core
npm i --save @eversdk/lib-web
```

**Important!** Each time you run `npm install` the new version of the `eversdk.wasm` and `index.js` is downloaded. So you have to always update the `eversdk.wasm` inside your web package before publishing (starting local web server, creating web bundle etc.). If you use Webpack the best way is to use CopyPlugin.

If you want to use high-level [AppKit](https://github.com/everx-labs/ever-appkit-js) package then install this package as well:

```
npm i --save @eversdk/appkit
```

You must initialize the library before the first use. The best place to do it is in initialization code of your application.

You need to attach the chosen binary module to the `TonClient` class:

```
import { TonClient } from '@eversdk/core';
import { libWeb } from '@eversdk/lib-web';

TonClient.useBinaryLibrary(libWeb);
```


# Configuration


# Endpoint Configuration

## Create TONClient

`TONClient` is the main class of Ever SDK Library. To start using library one needs to create and setup a TONClient instance.

The simplest initialization code can look like this: just specify the endpoint.

Other parameters are used by default. See the reference below for more info.

```javascript
const client = new TonClient({
network: { 
    endpoints: [
        'your-endpoint-here'
    ] 
    } 
});
```

## How to get my endpoint?

### Local node

If you want to work with [local blockchain Evernode-SE](https://github.com/everx-labs/evernode-se), specify <http://localhost> in the `endpoints`

```javascript
const client = new TonClient({
network: { 
    endpoints: [
        'http://localhost'
    ] 
    } 
});
```

### Evercloud

If you don't want to manage your own infrastructure - get your Evercloud endpoints **for free** to Mainnet and Devnet and configure security settings here <https://docs.everplatform.dev/products/evercloud/get-started>.

Check the full list of [supported networks](https://docs.everplatform.dev/reference/graphql-api/networks).

```javascript
const client = new TonClient({
network: { 
    endpoints: [
        'http://mainnet.evercloud.dev/your-project-id-here/graphql'
    ] 
    // access_key: "your-secret-here(optional, if you enabled "secret required" in your project)"
    } 
});
```

### Self-hosted dedicated node

If you want to run your own dedicated node yourself - see the[ Evernode-DS documentation ](https://docs.everplatform.dev/products/dapp-server-ds)how to run your dedicated node.

### Dedicated Evercloud

If you want your dedicated set of nodes to be run by Evernode Platform team, check this page <https://docs.everplatform.dev/products/dedicated-cloud-node>.

## Multiple endpoints configuration

If you have multiple endpoints in the same network, you can specify them all.

Library will automatically perform balancing based on endpoint health checks and availability.

```javascript
const client = new TonClient({
network: { 
    endpoints: [
        'ENDPOINT_URL1', 
        'ENDPOINT_URL2', 
        'ENDPOINT_URL3'
    ] 
    } 
});
```

You can also configure the message broadcast - how many nodes you want your message to be sent (it may improve delivery rate) like this.

```javascript
const client = new TonClient({
network: { 
    endpoints: [
        'ENDPOINT_URL1', 
        'ENDPOINT_URL2', 
        'ENDPOINT_URL3'
    ] 
    sending_endpoint_count: 3
    } 
});
```


# Message Expiration

Find out what 'message expired' means and get the understanding of 'retries' mechanism for reliable message delivery in Everscale Blockchain

## About message expiration

In Everscale blockchain, client-to-contract interaction is based on external messages. Yet, there is no guarantee for the successful reception of the message by design, and the time when the contract completes message processing is not determined.

Moreover, if, for some reason, a contract rejects a message (e.g., if it triggers replay protection), the message is not recorded to the blockchain, and the client has no means to find out the message processing result. In other words, there is neither exact timeout for message processing nor a tool to determine that it was rejected.

We implemented the message expiration mechanism to resolve the issue: when a client creates a message for a contract, a specific message expiration time is defined. Upon receiving this message, the contract checks whether the current time is earlier than the message expiration time. If it is, the contract execution continues. Otherwise, the contract aborts the transaction. Meanwhile, the client waits for any of the two: transaction corresponding to the original message or a new block with generation time later than the message expiration time. Thus, if a message is successfully processed, the client is notified about the transaction. In any of the following cases: the message is not delivered to the contract, delivered after expiration time, rejected by the contract, the client is informed of new block creation, meaning that the contract did not process the message. In this case, the client can create and send a new message for another attempt.

The feature must be supported by the contract itself to work properly. Let's use a simple Solidity contract as a sample.

```solidity
pragma solidity >=0.5.0;
pragma AbiHeader time;
pragma AbiHeader expire;

contract HelloTON {
uint32 timestamp;

// Modifier that allows public function to accept all external calls.
modifier alwaysAccept {
    tvm.accept();
    _;
    }

constructor() public {
    tvm.accept();
    timestamp = uint32(now);
    }
//Function setting set value to state variable timestamp
function touch() public alwaysAccept {
    timestamp = uint32(now);
    }
//Function returns value of state variable timestamp
function sayHello() public view returns (uint32) {
    return timestamp;
    }
}
```

The `pragma AbiHeader expire;` line initiates the message expiration option for the contract functions. TON Labs SDK automatically defines the expiration time according to the client default timeout specified in client config. We use the following formula to define the expiration time: `expire time = current time + timeout`. You can define the applied timeout at the SDK initialization via the `abi.message_expiration_timeout` parameter that takes the timeout value in ms. If no timeout is specified at initialization, the default value is 40 seconds.

```graphql
const client = new TonClient({
    network: {
        endpoints: [
            your-endpoint(s)-here
        ]
    },
    abi: {
        message_expiration_timeout: 120000,
    }
});
```

To define an expiration time for a separate message, the `expire` value has to be defined in header parameters of a contract function call (the `call_set.header` parameter in `process_message`, `encode_message`, functions.

> **Note**: the expire value is defined in **milliseconds**.

```javascript
// Encode the message with `touch` function call
const params = {
        abi= {
               type: 'Contract',
            value: Contract.abi
        },
        address,
        call_set: {
            function_name: 'touch',
            header: {
                      // timeout will be 30 seconds
                    expire: Math.floor(Date.now() / 1000) + 30 

            }
            input: {}
        },
        // There is no pubkey key check in the contract
        // so we can leave it empty. Never use this approach in production
        // because anyone can call this function
        signer: { type: 'None' }
}

// Create external inbound message with `touch` function call
const encode_touch_result = await client.abi.encode_message(params);
```

The expiration time is stored in the message structure and used when it is sent to determine the transaction wait for the timeout. If you need to send a delayed message, the delay length should also be considered when the expiration time is defined.

```javascript
// timeout will be delayTime + 30 seconds
header: {
expire: Math.floor(Date.now() / 1000) + delayTime + 30
},
```

The option can be used when an external device is used to sign transactions and the message for signing cannot be generated immediately before the signature generation (see item 2 below).

When an external device is used, two message creation options exist:

1. the device does not require user input for signing or user input is required before the data for signing is generated (e.g. a user unlocks the device to create a signature and then the data for signing is sent to the device with a separate command)
2. the device requires user input at the point when data for signing has to be generated (e.g. a command to provide a signature with the relevant data is sent to the device before the device prompts the user to unlock it)

In the first case default SDK timeout values can be used, as the interval between message creation and sending is supposed to be short.

In the second case the message expiration time takes into account an interval allocated to the user to sign a transaction. Note that a timer showing the available window for signing has to be displayed to the user.


# Message Retry

## Resending a Message

The process\_message function has the retry feature. If [message had expired](/ever-sdk/guides/configuration/message_expiration), it can be re-created and re-sent to the network. Five attempts are carried out by default. If all of them fail, `507` error is returned as well. Use the `network.message_retries_count` parameter to customize the number of attempts at SDK initialization. If set to `0`, no further attempts will be carried out.

It is a good practice to increase the timeout between retries, for instance, if they are caused by bad connection or network lags (for instance when shard is temporarily served by some slow validators). `abi.message_expiration_timeout_grow_factor` parameter defines proportion of timeout increase with each retry. The default value is 1.5.

In this example the number of retries will be decreased to 3 and expiration timeout will be increased by 1.3 times with each retry.

```graphql
const client = new TonClient({
    network: {
        endpoints: [
            your-endpoint(s)-here
        ],
        message_retries_count: 3
    },
    abi: {
        message_expiration_timeout: 120000,
        message_expiration_timeout_grow_factor: 1.3
    }
});
```

When you use separate functions to create (`encoded_message`) and to send a message (`send_message`), re-creating and re-sending should be carried out separately.

> **Note that only `507` error code from `process_message` or `wait_for_transaction` (if you specified the correct block id that you fetched before the message was sent) guarantees that the message is expired and will not be processed by the contract.**

## When to retry with 507 error

Normally, `process_message` and `wait_for_transaction` perform local emulation of transaction in case of expired message error and attach the results to the error object of `507` error ([ErrorData.exit\_code](/ever-sdk/reference/error_api)). It will give you a possible reason why the message was not executed on-chain (check exit code meaning in contract source code).

**If you see there is no `exit_code`, then do the retry. Also retry can be executed in case of replay protection `exit_code`.** Sometimes when a network undergoes high loads, this may happen.


# Config Reference

## [TONClient.config reference](/ever-sdk/reference/types-and-methods/mod_client#clientconfig)


# Work with contracts

This section contains the following guides on working with contracts:

* [Add Contract to your App](/ever-sdk/guides/work_with_contracts/add_contract_to_your_app)
* [Using custom Giver](/ever-sdk/guides/work_with_contracts/custom_giver)
* [Deploy](/ever-sdk/guides/work_with_contracts/deploy)
* [Run on-chain](/ever-sdk/guides/work_with_contracts/run_onchain)
* [Run ABI Get Method](/ever-sdk/guides/work_with_contracts/run_abi_get_method)
* [Run Fift Get Method](/ever-sdk/guides/work_with_contracts/run_fift_get_method)
* [Message Expiration](/ever-sdk/guides/configuration/message_expiration)
* [Work with Events](/ever-sdk/guides/work_with_contracts/work_with_events)
* [Retry Message](/ever-sdk/guides/configuration/retry_message)
* [External Signing](/ever-sdk/guides/work_with_contracts/external_signing)
* [Emulate Transaction](/ever-sdk/guides/work_with_contracts/emulate_transaction)
* [Decode Message](/ever-sdk/guides/work_with_contracts/decode_message)
* [Estimate Fees](/ever-sdk/guides/work_with_contracts/estimate_fees)
* [Validate address, convert address](/ever-sdk/guides/work_with_contracts/validate_address_convert_address)
* [Trace message processing with REMP](/ever-sdk/guides/work_with_contracts/trace-message-processing-with-remp)


# Add Contract to your App

Define a contract in your application to start working with it

* [About contract artifacts](#about-contract-artifacts)
* [Create contract wrapper](#create-contract-wrapper)

## About contract artifacts

Make sure your [added SDK to your app](/ever-sdk/guides/installation/add_sdk_to_your_app) and [configured your Client](/ever-sdk/guides/configuration/configure_sdk) before proceeding.

If you need to work with a previously deployed contract, you will need only its ABI and address. Get it in public repositories or ask the contract developer for it.

If you need to deploy a contract, then you will also need its tvc file. This file, along with ABI, is an artifact of contract compilation. Ask contract developer for this file.

If you plan to develop and compile the contracts yourself then these docs will help you:

* [Compiling contract with one command with everdev](https://docs.everos.dev/everdev/command-line-interface/solidity#compile)
* [Solidity Compiler](https://github.com/everx-labs/TVM-Solidity-Compiler)
* [Public repository with contracts](https://github.com/everx-labs/ton-labs-contracts)

## Create contract wrapper

Use EVERDEV tool to [generate contract wrapper](https://docs.everos.dev/everdev/command-line-interface/sdk#create-contract-js-wrapper) that will have the following structure:

```javascript
export type Contract = {
/**
 * ABI of smart contract
 */
abi: AbiContract,
/**
 * Compiled artifact of the smart contract converted to base64.
 * This field contains BOC with code and initial data (init state).
 * If it is missing, then application can't deploy account of this contracts.
 */
tvc?: string,
}
```

If you have tvc file, `EVERDEV` will convert it into base64 that is suitable for SDK. If you don't have tvc, then this wrapper will be only useful for interaction with an already deployed contract.

Run this command:

```
everdev js wrap contractName.abi.json
```

The result name of the wrapper will be "ContractName||"Contract".js".

The result file will look like this:

```javascript
module.exports = {
HelloContract: {
    abi: {
        "ABI version": 2,
        "header": ["time", "expire"],
        "functions": [
            {
                "name": "constructor",
                "inputs": [],
                "outputs": [],
            },
            {
                "name": "touch",
                "inputs": [],
                "outputs": [],
            },
            {
                "name": "getTimestamp",
                "inputs": [],
                "outputs": [
                    {
                        "name": "value0",
                        "type": "uint256",
                    },
                ],
            },
        ],
        "data": [],
        "events": [],
    },
    tvc: "te6ccgECEgEAAisAAgE0AwEBAcACAEPQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAib/APSkICLAAZL0oOGK7VNYMPShCAQBCvSkIPShBQIDzsAHBgAv12omhp/+mf6YBrhf/8NT/8MPwzfDH8MUAC/3whZGX//CHnhZ/8I2eFgHwlAOX/5PaqQCASALCQH+/38h7UTQINdJwgGOFNP/0z/TANcL//hqf/hh+Gb4Y/hijhv0BXD4anABgED0DvK91wv/+GJw+GNw+GZ/+GHi0wABn4ECANcYIPkBWPhC+RDyqN7TPwGOHvhDIbkgnzAg+COBA+iogggbd0Cgud6S+GPggDTyNNjTHwH4I7zyuQoAONMfIcEDIoIQ/////byxkvI84AHwAfhHbpLyPN4CASANDACzvUWq+f/CC3Rx52omgQa6ThAMcKaf/pn+mAa4X//DU//DD8M3wx/DFHDfoCuHw1OADAIHoHeV7rhf/8MTh8Mbh8Mz/8MPFvfCN5Obj8M2j8AHwR/DV4Ab/8M8AgEgDw4AL7tzEuRfhBbpLwBN7R+AD4I/hq8AN/+GeAIBIBEQAIO586yQfwgt0l4Am9o/CUQ4H/HEZHoaYD9IBgY5GfDkGdAMGegZ8DnwOfJPzrJBxDnhf/kuP2Abxhgf8l4Ae8//DPAAatxwItDWAjHSADDcIccAkOAh1w0fkvI84VMRkOHBAyKCEP////28sZLyPOAB8AH4R26S8jze",
}
};
```

**You're all done!**

Find out how to [deploy](/ever-sdk/guides/work_with_contracts/deploy) and [run](/ever-sdk/guides/work_with_contracts/run_onchain) your contract in the next sections.


# Use your own Giver

Working with DevNet is similar to working with SE except you usually don't have any predeployed giver in DevNet. So you need to fund your contracts manually or deploy your own giver, which you will be able to use the same way as in SE. Deploying your own giver can be useful, if you need to deploy many contracts or need to frequently redeploy and test contract after subsequent modification.

You can find how to deploy your own Giver [here](https://docs.everos.dev/everdev/guides/work-with-devnet).

In this guide we will show you how you can use your own Giver in the core SDK.

First of all, let's initialize giver's address, keys and ABI. All the data in this example are used from Evernode SE giver, substitute them by your Giver's data.

```javascript
// Giver address Evernode SE
const giverAddress = '0:b5e9240fc2d2f1ff8cbb1d1dee7fb7cae155e5f6320e585fcc685698994a19a5';
// Giver keys on Evernode SE
const giverSigner = signerKeys({
    "public": "2ada2e65ab8eeab09490e3521415f45b6e42df9c760a639bcf53957550b25a16",
    "secret": "172af540e43a524763dd53b26a066d472a97c4de37d5498170564510608250c3"
});
// Giver ABI on Evernode SE
const giverAbi = abiContract({
    'ABI version': 2,
    header: ['time', 'expire'],
    functions: [
        {
            name: 'sendTransaction',
            inputs: [
                { 'name': 'dest', 'type': 'address' },
                { 'name': 'value', 'type': 'uint128' },
                { 'name': 'bounce', 'type': 'bool' }
            ],
            outputs: []
        },
        {
            name: 'getMessages',
            inputs: [],
            outputs: [
                {
                    components: [
                        { name: 'hash', type: 'uint256' },
                        { name: 'expireAt', type: 'uint64' }
                    ],
                    name: 'messages',
                    type: 'tuple[]'
                }
            ]
        },
        {
            name: 'upgrade',
            inputs: [
                { name: 'newcode', type: 'cell' }
            ],
            outputs: []
        },
        {
            name: 'constructor',
            inputs: [],
            outputs: []
        }
    ],
    data: [],
    events: []
});
```

Next, implement a function to request tokens from the Giver:

```javascript
// Requesting test tokens from the Giver
async function getTokensFromGiver(client, account, amount) {
    // Execute method `sendTransaction` of the Evernode SE Giver v2 contract:
    const processingResult = await client.processing.process_message({
        send_events: false,
        message_encode_params: {
            address: giverAddress,
            abi: giverAbi,
            call_set: {
                function_name: 'sendTransaction',
                input: {
                    dest: account,
                    value: amount,
                    bounce: false
                }
            },
            signer: giverSigner,
        },
    });

    // Wait until all messages have been produced:
    const transactionTree = await client.net.query_transaction_tree({
        in_msg: processingResult.transaction.in_msg,
    });

    // Make additional checks to ensure success:
    if (transactionTree.transactions.length !== 2) {
        throw `Something went wrong during requesting funds from the Giver: there must be 2 transactions, but actual count is ${transactionTree.transactions.length}`;
    }

    if (transactionTree.transactions[1].account_addr !== account) {
        throw "Something went wrong during requesting funds from the Giver: 2nd transaction's account address must be " + account;
    }
}
```

Now you can use your new function for funding your contracts before deployment:

```javascript
async function main(client) {
    // Define contract ABI in the Application 
    // See more info about ABI type here https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_abi.md#abi
    const abi = {
        type: 'Contract',
        value: HelloWallet.abi
    }
    // Generate an ed25519 key pair
    const helloKeys = await client.crypto.generate_random_sign_keys();
    
    // Prepare parameters for deploy message encoding
    // See more info about `encode_message` method parameters here https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_abi.md#encode_message
    const deployOptions = {
        abi,
        deploy_set: {
            tvc: HelloWallet.tvc,
            initial_data: {}
        },
        call_set: {
            function_name: 'constructor',
            input: {}
        },
        signer: {
            type: 'Keys',
            keys: helloKeys
        }
    }

    // Encode deploy message
    // Get future `Hello` contract address from `encode_message` result
    // to sponsor it with tokens before deploy
    const { address } = await client.abi.encode_message(deployOptions);
    console.log(`Future address of the contract will be: ${address}`);

    // Request contract deployment funds form the Giver
    await getTokensFromGiver(client, address, 1_000_000_000);
    console.log(`Tokens were transfered from giver to ${address}`);

    // Deploy `hello` contract
    // See more info about `process_message` here  
    // https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_processing.md#process_message
    await client.processing.process_message({
        send_events: false,
        message_encode_params: deployOptions
    });

    console.log(`Hello contract was deployed at address: ${address}`);
}
```

## Sample Source Code

Full sample: <https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/custom-giver/>


# Deploy

Find out how to deploy a contract to Everscale Blockchain with SDK

* [About deploy](#about-deploy)
* [Deploy steps](#deploy-steps)
* [Observe deploy parameters](#observe-deploy-parameters)
* [Prepare a pair of keys](#prepare-a-pair-of-keys)
* [\[Optional\] Prepare initial contract data](#optional-prepare-initial-contract-data)
* [Specify constructor](#specify-constructor)
* [Calculate the future contract address](#calculate-the-future-contract-address)
* [Transfer funds to the future address](#transfer-funds-to-the-future-address)
* [Deploy](#deploy-1)
  * [Pattern 1. Deploy in 1 step: `process_message` method](#pattern-1-deploy-in-1-step-process_message-method)
  * [Pattern 2. Deploy in 3 steps: `encode_message` -> `send_message` -> `wait_for_transaction`](#pattern-2-deploy-in-3-steps-encode_message----send_message---wait_for_transaction)
* [Deploy a contract from another contract](#deploy-a-contract-from-another-contract)
* [Sample Source Code](#sample-source-code)

> [See the API reference](/ever-sdk/reference/types-and-methods/modules).

Core api is more flexible than [AppKit](https://github.com/everx-labs/ever-appkit-js), and you can perform a lot of complex logic using it. But you will need to write more code with it as well:)

You need to define the contract in your node.js application before deploy.

See the "[Add Contract to your App](/ever-sdk/guides/work_with_contracts/add_contract_to_your_app)" guide to find out how to do it.

## About deploy

Deploy operation means that you upload contract code and initial data to the blockchain.

The address of the contract can be calculated before deploy and it depends on code and data.

To deploy a contract you need to sponsor its address, so that deploy fee will be paid out of these funds.

## Deploy steps

Below is the sequence of steps you need to complete:

1. Observe deploy parameters
2. Prepare a pair of keys
3. \[optional] Prepare Initial contract data
4. Calculate future address of the contract
5. Transfer funds to the future address
6. Deploy

Let's take a look at every step.

## Observe deploy parameters

Here is the structure, that is used to prepare initial contract state for deploy. It will define the future contract address.

`tvc` - As we discussed at the [previous step](/ever-sdk/guides/work_with_contracts/add_contract_to_your_app), contract compilation artifact, converted into base64.

`workchain_is` - Target workchain where the contract will be deployed. By default is 0.

`initial_data` - structure that contains public contract data fields with assigned values that need to be included into the initial state.

`initial_pubkey` - owner pubkey. If not specified, pubkey is taken from `Signer`. If you manage to specify contract owner directly in `tvc`, then it will have priority above both `initial_pubkey` and `Signer`.

```javascript
type DeploySet = {
    tvc: string,
    workchain_id?: number,
    initial_data?: any,
    initial_pubkey?: string
}
```

## Prepare a pair of keys

To deploy you will need a pair of keys to sign the deployment message. The keys are used during address generation, so the future contract address depends partially on the key as well.

In fact, keys are optional for deploy, but, if you want to be the contract owner then specify Signer object for that. [Read more about Signer object in Reference](/ever-sdk/reference/types-and-methods/mod_abi#Signer).

If you want to make another person owner of the contract then specify their pubkey via `DeploySet.initial_pubkey`.

In this guide we will use `crypto.generate_random_sign_keys` function to generate a key pair.

```javascript
const helloKeys = await client.crypto.generate_random_sign_keys();
```

> **Note**: Please store these keys in a secure environment as you will need them to calculate the future address and deploy the contract. You might also need it to call contract functions in the future.

## \[Optional] Prepare initial contract data

Placing data into storage always affects the future contract address.

This is useful for scenarios when you need to deploy several contracts with identical contract code (e.g. wallets) to different addresses.

If each contract is deployed with its own unique pair of keys, you do not need to use `DeploySet.initial_data` as the addresses will be generated using the corresponding key pair each time.

If, however, all the contracts need to have the same contract code and have to be deployed with the same pair of keys but to different addresses, you may use placing data into storage through `DeploySet.initial_data` to vary the addresses during [address calculation](#calculate-the-future-contract-address).

To be used as `initParams` variables must be declared as `static` in the contract.

## Specify constructor

Constructor - is any contract function that will be called upon deploy. It will not influence contract address.

It, together with its parameters, is specified in the [CallSet](/ever-sdk/reference/types-and-methods/mod_abi#callset) structure:

```javascript
type CallSet = {
    function_name: string,
    header?: FunctionHeader,
    input?: any
}
```

`function_name` - function name that will be called upon deploy. Usually, it is called `constructor`.

`header` - optional, can be specified for some complex use cases. [Read more here](/ever-sdk/guides/configuration/message_expiration).

`input` - object with function parameters.

## Calculate the future contract address

Everscale blockchain requires every contract to have a positive token balance before deployment. The contract pays for the initial deployment message reducing account balance.

We will create deploy message and get future contract address from it.

You can either specify or not specify call\_set here, it will not influence the address.

```javascript
const abi = {
    type: 'Contract',
    value: contract.abi
}
// Generate an ed25519 key pair
const helloKeys = await client.crypto.generate_random_sign_keys();

// Prepare parameters for deploy message encoding
// See more info about `encode_message` method parameters here https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_abi.md#encode_message
const deployOptions = {
    abi,
    deploy_set: {
        tvc: contractPackage.tvcInBase64,
        initial_data: {}
    },
      // can be ommited here for address calculation
    call_set: { 
        function_name: 'constructor',
        input: {}
    },
    signer: {
        type: 'Keys',
        keys: helloKeys
    }
}

// Encode deploy message
// Get future `Hello` contract address from `encode_message` result
// to sponsor it with tokens before deploy
const { address } = await client.abi.encode_message(deployOptions);
console.log(`Future address of the contract will be: ${address}`);
```

> **Note**: Deployment requires the same pair of keys used for address calculation.
>
> **Note**: `constructorParams` do not affect the address. Only `initParams` and the keys do. If you only plan to calculate address, you can omit this parameter.

## Transfer funds to the future address

Now that you know the address, you need to transfer the initial funds to it from your wallet or the Giver.

> **Note**: Evernode SE offers a pre-deployed giver. When in real networks, you need to use your wallet for this or deploy your own giver. We have separated guides of [deployment](https://docs.everos.dev/everdev/guides/work-with-devnet) and [usage](/ever-sdk/guides/work_with_contracts/custom_giver) of your own giver.

```javascript
// Request contract deployment funds form a local Evernode SE giver
// not suitable for other networks
await get_tokens_from_giver(client, address);
console.log(`Tokens were transfered from giver to ${address}`);
```

## Deploy

At this point, you're all set for deployment.

> **Note**: Insufficient balance will result in a failed deployment.
>
> **Note**: Everscale Blockchain does not guarantee a 100% external inbound messages success rate. There is a possibility that deployment will fail. To ensure success, please check for a completed transaction.

### Pattern 1. Deploy in 1 step: `process_message` method

This is an easy to implement pattern to deploy for server-side development and tests, but we do not recommend to use it in web and mobile applications because of network inconsistency and application crash probability. For more reliable approach - use the Pattern 2.

Method \`process\_message performs all the deploy steps sequentially in one method: create message, send it, wait for transaction and decode external outbound message generated by contract RETURN operator. The time limit can be set up in Client configuration. The default time setting is 40 seconds. You can learn more [here](/ever-sdk/guides/configuration/message_expiration).

```javascript
// Deploy `hello` contract
// See more info about `process_message` here  
// https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_processing.md#process_message
await client.processing.process_message({
    send_events: false,
    message_encode_params: deployOptions
});

console.log(`Hello contract was deployed at address: ${address}`);
```

See the full example in sdk samples repository:

<https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/hello-wallet/index.js>

Check out how to run contract's methods in the next [section](/ever-sdk/guides/work_with_contracts/run_onchain).

### Pattern 2. Deploy in 3 steps: `encode_message` -> `send_message` -> `wait_for_transaction`

Any interaction with and within the Everscale blockchain is implemented via messages.

To deploy a contract, first you need to create a deploy message that will include all the initial data:

```javascript
// Prepare parameters for deploy message encoding
// See more info about `encode_message` method parameters here https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_abi.md#encode_message
const deployOptions = {
    abi: {
        type: 'Contract',
        value: contract.abi
    },
    deploy_set: {
        tvc: contractPackage.tvcInBase64,
        initial_data: {}
    },
    call_set: {
        function_name: 'constructor',
        input: {}
    },
    signer: {
        type: 'Keys',
        keys: helloKeys
    }
}

// Encode deploy message
// Get future `Hello` contract address from `encode_message` result
// to sponsor it with tokens before deploy
const encode_deploy_result = await client.abi.encode_message(deployOptions);
```

Now the message should be sent. `send_message` method returns the the last block created in the shard before the message was sent.

`send_events: false` flag specifies that we will not monitor message delivery events. Soon there will be a guide about message processing monitoring.

```javascript
// Send deploy message to the network
// See more info about `send_message` here  
// https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_processing.md#send_message
var shard_block_id;
shard_block_id = (await client.processing.send_message({
    message: encode_deploy_result.message,
    send_events: false
    },
)).shard_block_id;
console.log(`Deploy message was sent.`);
```

After the message was sent we need to wait for the transaction:

```javascript
// Monitor message delivery. 
// See more info about `wait_for_transaction` here  
// https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_processing.md#wait_for_transaction
const deploy_processing_result = await client.processing.wait_for_transaction({
  abi: {
        type: 'Contract',
        value: contract.abi
    },
    message: encode_deploy_result.message,
    shard_block_id: shard_block_id,
    send_events:false // we do not want to monitor processing events
    }
)
console.log(`Deploy transaction: ${JSON.stringify(deploy_processing_result.transaction,null,2)}`);
console.log(`Deploy fees: ${JSON.stringify(deploy_processing_result.fees,null,2)}`);
console.log(`Hello contract was deployed at address: ${address}`);
```

If `wait_for_transaction` fails with 507 error - you can perform a retry. In all other cases retry may end up with double spends.

See the full example in sdk samples repository:

<https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/hello-wallet/index_pattern2.js>

Check out how to run contract's methods in the next [section](/ever-sdk/guides/work_with_contracts/run_onchain).

## Deploy a contract from another contract

Often developers need to deploy one contract from another contract and try to pass `tvc` file as a cell parameter for contract to use.

This is not a correct way.

**To be able to deploy a contract from another contract you need to pass the contract's code as a cell parameter.**

You can get it several ways:

* You can use SDK function [get\_code\_from\_tvc](/ever-sdk/reference/types-and-methods/mod_boc#get_code_from_tvc) of `boc` module and retrieve the code's boc from tvc file.
* You can download another account with the same `code_hash`'s `boc` from graphql, using [blockchain API](https://docs.everplatform.dev/samples/graphql-samples/accounts#get-account-info) and retrieve the 'code' from the result `boc` field.

## Sample Source Code

Full sample: <https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/hello-wallet/>

Check out [AppKit documentation](https://docs.everos.dev/appkit-js/guides/deploy) for this use case.


# Run on-chain

Learn how to run methods of a contract on-chain

* [About run](#about-run)
* [Run on-chain](#run-on-chain-1)
  * [Pattern 1. Run in 1 step: `process_message` method](#pattern-1-run-in-1-step-process_message-method)
  * [Pattern 2. Run in 3 steps: `encode_message` -> `send_message` -> `wait_for_transaction`](#pattern-2--run-in-3-steps-encode_message----send_message---wait_for_transaction)

> [See the API reference](/ever-sdk/reference/types-and-methods/modules).

Core api is more flexible than [AppKit](https://github.com/everx-labs/ever-appkit-js) and you can perform a lot of complex logic using it. But you will need to write more code with it as well :)

You need to [define the contract in your node.js](/ever-sdk/guides/work_with_contracts/add_contract_to_your_app) application before running its methods.

Full sample: <https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/hello-wallet>

## About run

Run operation consists of few steps:

1. Creating a message;
2. Sending a message;
3. Receiving the message completion transaction;
4. Receiving external messages created by `return` function;
5. Decoding the messages bodies according to the ABI.

## Run on-chain

### Pattern 1. Run in 1 step: `process_message` method

The [process\_message](/ever-sdk/reference/types-and-methods/mod_processing#process_message) method runs ABI-compatible contract method on-chain and returns the result transaction along with the external messages bocs, and decoded external messages bodies.

`process_message` performs all the run operation steps inside.

> **Note**: This is an easy to implement pattern to run, but we do not recommend to use it because of network inconsistency and application crash probability. For more reliable approach - use the Pattern 2.

For example, a contract has such method:

```javascript
// Function setting set value to state variable timestamp and returning it
function touchMe() public alwaysAccept returns (uint32) {
    timestamp = uint32(now);
    return timestamp;
}
```

Client method call:

```javascript
// Encode the message with `touch` function call
const params = {
    send_events: false,
    message_encode_params: {
        address,
        abi,
        call_set: {
            function_name: 'touch',
            input: {}
        },
        // There is no pubkey key check in the contract
        // so we can leave it empty. Never use this approach in production
        // because anyone can call this function
        signer: { type: 'None' }
    }
}
// Call `touch` function
let response = await client.processing.process_message(params);
console.log(`Сontract run transaction with output ${response.decoded.output}, ${response.transaction.id}`);
```

See the full sample in the repository with sdk samples:

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/hello-wallet>

### Pattern 2. Run in 3 steps: `encode_message` -> `send_message` -> `wait_for_transaction`

To run a contract method, first you need to create a run message:

```javascript
// Encode the message with `touch` function call
const params = {
        abi = {
            type: 'Contract',
            value: contract.abi
        },
        address,
        call_set: {
            function_name: 'touch',
            input: {}
        },
        // There is no pubkey key check in the contract
        // so we can leave it empty. Never use this approach in production
        // because anyone can call this function
        signer: { type: 'None' }
}

// Create external inbound message with `touch` function call
const encode_touch_result = await client.abi.encode_message(params);
```

Now the message should be sent. `sendMessage` method returns the the last block created in the shard before the message was sent.

```javascript
// Send `touch` call message to the network
// See more info about `send_message` here  
// https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_processing.md#send_message
shard_block_id = (await client.processing.send_message({
    message: encode_touch_result.message,
    send_events: true
    },logEvents
)).shard_block_id;
console.log(`Touch message was sent.`);
```

After the message was sent we need to wait for the transaction starting from the last shard block:

```javascript
// Monitor message delivery. 
// See more info about `wait_for_transaction` here  
// https://github.com/everx-labs/ever-sdk/blob/master/docs/mod_processing.md#wait_for_transaction
const touch_processing_result = await client.processing.wait_for_transaction({
    abi = {
        type: 'Contract',
        value: contract.abi
    },
    message: encode_touch_result.message,
    shard_block_id: shard_block_id,
    send_events:true
    },
    logEvents
)
console.log(`Touch transaction: ${JSON.stringify(touch_processing_result.transaction,null,2)}`);
console.log(`Touch fees: ${JSON.stringify(touch_processing_result.fees,null,2)}`);
```

## Calculate account fees

Retrieve `result.fees` object of `process_message` or `wait_for_transaction`. You need **`result.fees.account_fees`** for total account fees value.

### Fees object detailed explanation

Here is the structure of fees object.

* `storage_fee`: *bigint* – Fee for account storage
* `gas_fee`: *bigint* – Fee for processing
* `in_msg_fwd_fee`: *bigint* – Deprecated. Left for backward compatibility.
* `ext_in_msg_fee`: *bigint* – Fee for inbound external message import.
* `total_fwd_fees`: *bigint* – Total fees the account pays for message forwarding
* **`account_fees`: \_bigint**\_\*\* – Total account fees for the transaction execution. Compounds of storage\_fee + gas\_fee + ext\_in\_msg\_fee + total\_fwd\_fees\*\*

#### Deprecated fields. Left for backward compatibility.

* `out_msgs_fwd_fee`: *bigint* – Deprecated. Left for backward compatibility.
* `total_account_fees`: *bigint* – Deprecated. Left for backward compatibility.\
  This is the field that is named as `total_fees` in GraphQL API Transaction type. `total_account_fees` name is misleading, because it does not mean account fees, instead it means validators total fees received for the transaction execution. It does not include some forward fees that account actually pays now, but validators will receive later during value delivery to another account (not even in the receiving transaction but along the way of a chain of transactions processing).\
  Because of all of this, this field is not interesting for those who want to understand\
  the real account fees, this is why it is deprecated and left for backward compatibility.
* `total_output`: *bigint* – Deprecated. Left for backward compatibility.

```graphql
type TransactionFees = {
    in_msg_fwd_fee: bigint,
    storage_fee: bigint,
    gas_fee: bigint,
    out_msgs_fwd_fee: bigint,
    total_account_fees: bigint,
    total_output: bigint,
    ext_in_msg_fee: bigint,
    total_fwd_fees: bigint,
    account_fees: bigint
}
```

See the full example in sdk samples repository: <https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/hello-wallet/index_pattern2.js>

Check out [AppKit documentation](https://docs.everos.dev/appkit-js/guides/run_onchain) for this use case.


# Run ABI Get Method

Run ABI compatible get methods

* [Run get method](#run-get-method)
* [Source code](#source-code)

## Run get method

With low level SDK get method is executed in 3 steps:

1. Download the latest Account State (BOC)
2. Encode message that calls the method
3. Execute the message locally on the downloaded state:

Here is the sample that executes the get method `getTimestamp` on the latest account's state.

1. account boc is downloaded with `blockchain` API
2. message that calls contract's function `getTimestamp` is encoded with `encode_message` function
3. message is executed on local TVM with `run_tvm` method

```javascript
 async function getAccount(address) {

    // `boc` or bag of cells - native blockchain data layout. Account's boc contains full account state (code and data) that
    // we will  need to execute get methods.
    const query = `
        query {
          blockchain {
            account(
              address: "${address}"
            ) {
               info {
                balance(format: DEC)
                boc
              }
            }
          }
        }`
    const {result}  = await client.net.query({query})
    const info = result.data.blockchain.account.info
    return info
}
async function runGetMethod(methodName, address, accountState) {
    // Execute the get method `getTimestamp` on the latest account's state
    // This can be managed in 3 steps:
    // 1. Download the latest Account State (BOC) 
    // 2. Encode message
    // 3. Execute the message locally on the downloaded state

    // Encode the message with `getTimestamp` call
    const { message } = await client.abi.encode_message({
        // Define contract ABI in the Application
        // See more info about ABI type here:
        // https://github.com/everx-labs/ever-sdk/blob/master/docs/reference/types-and-methods/mod_abi.md#abi
        abi: {
            type: 'Contract',
            value: HelloWallet.abi,
        },
        address,
        call_set: {
            function_name: methodName,
            input: {},
        },
        signer: { type: 'None' },
    });

    // Execute `getTimestamp` get method  (execute the message locally on TVM)
    // See more info about run_tvm method here:
    // https://github.com/everx-labs/ever-sdk/blob/master/docs/reference/types-and-methods/mod_tvm.md#run_tvm
    console.log('Run `getTimestamp` get method');
    const response = await client.tvm.run_tvm({
        message,
        account: accountState,
        abi: {
            type: 'Contract',
            value: HelloWallet.abi,
        },
    });
    return response.decoded.output
}
```

## Source code

<https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/hello-wallet/index.js>

Check out [AppKit documentation](https://docs.everos.dev/appkit-js/guides/run_abi_get_method) for this use case.


# Run Fift Get Method

Learn how to run FIFT methods

## About Fift get methods

There are contracts written in Fift. They have other rules for running get methods.

This is why we have a separate method for that in tvm module - [run\_get](/ever-sdk/reference/types-and-methods/mod_tvm#run_get).

## Sample source code

Check this sample, demonstrating how to run get methods of elector contract:

<https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/run_get/index.js>


# Query/Subscribe for messages(events)

How to work with contract event

How to work with contract events

* [About messages](#about-messages)
* [Query/subscribe to messages](#query-subscribe-to-messages)
* [Usage](#usage)
  * [Query](#query)
  * [Subscribe](#subscribe)
  * [Decode](#decode)

## About messages

Account messages are of 3 types:

* External inbound (`msg_type`=1 or `ExtIn` ). It is for example, deploy message or run message.
* Internal message(`msg_type`=0). It is when one contract calls another contract it sends an internal message. These messages are constructed with target contract ABI. Can be of 2 subtypes:
  * Internal inbound (`IntIn`)
  * Internal outbound (`IntOut`)
* External outbound messages(`msg_type`=2 or `ExtOut`). These can be of 2 subtypes:
  * Events - these are also specified in contract ABI. [Read more about working with events here](/ever-sdk/guides/work_with_contracts/work_with_events).
  * Return - these are generated by contract function's return.

## Query/subscribe to messages

You can fetch events of you contract like this:

```graphql
query{
  blockchain{
    account(address:"-1:67f4bf95722e1bd6df845fca7991e5e7128ce4a6d25f6d4ef027d139a11a7964"){
      messages(msg_type:[ExtOut, ExtIn, IntIn, IntOut],first:2){
        edges{
          node{
            hash
            body
            created_at_string
          }
          cursor
        }
        pageInfo{
          hasNextPage
        }
      }
    }
  }
}
```

Or subscribe to them:

```graphql
subscription{
messages(
      filter:{ 
      src:{
        eq:"-1:67f4bf95722e1bd6df845fca7991e5e7128ce4a6d25f6d4ef027d139a11a7964"
      }
      msg_type:{
        in:[0,1,2]
      }
    }
)
{
   id
  body
}
}
```

## Usage

### Query

See the full sample here <https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/pagination>

Read about used API here -> [Account messages pagination](https://docs.everplatform.dev/samples/graphql-samples/accounts#get-messages-within-block-range).

```javascript
result = await client.net.query({
  query: `query MyQuery($address: String!, $cursor: String, $count: Int, $start_seq_no: Int, end_seq_no: Int) {
    blockchain {
        account(address: $address){
            messages(
                master_seq_no_range: { start: $start_seq_no, end: $end_seq_no }
                first: $count,
                msg_type: [ExtOut, ExtIn, IntIn, IntOut],
                after: $cursor
            ) {
                edges {
                    node { id, created_at }
                }
                pageInfo {
                    endCursor
                    hasNextPage
                }
            }
        }
    }
}`,
       variables:{address, cursor, count, start_seq_no, end_seq_no}
}); 
```

### Subscribe

See the full sample here <https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/subscribe-and-decode>

To subscribe to all this. Don't forget to specify your own callback.

```javascript
const messageSubscription = await TonClient.default.net.subscribe_collection({
    collection: "messages",
    filter: {
        dst: { eq: your-contract-address },
        msg_type:{ in: [0,1,2] }
    },
    result: "boc"
}, <callback function>
});
```

### Decode

See the full sample here <https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/subscribe-and-decode>

```javascript
const decoded = (await TonClient.default.abi.decode_message({
                    abi: abiContract(your-contract-abi),
                    message: message_boc,
                }));
switch (decoded.body_type) {
                case MessageBodyType.Input:
                    console.log(`External inbound message, function "${decoded.name}", parameters: `, JSON.stringify(decoded.value));
                    break;
                case MessageBodyType.Output:
                    console.log(`External outbound message, function "${decoded.name}", result`, JSON.stringify(decoded.value));
                    break;
                case MessageBodyType.Event:
                    console.log(`External outbound message, event "${decoded.name}", parameters`, JSON.stringify(decoded.value));
                    break;
                }
```

Check out [AppKit documentation](https://docs.everos.dev/appkit-js/guides/work_with_events) for this use case.


# Decode Messages(Event)

How to decode messages with ABI

SDK can decode ABI-compatible External Inbound, External Outbound and Internal messages.

## Types of messages

ABI-compatible contracts generate abi-compatible messages, or, to be exact, abi-compatible message bodies :)

So, if you have ABI on hands, you can decode these messages.

You can use both full message boc for decoding and only message body for decoding.

## Let's decode!

Core SDK provides

* `decode_message` method for full boc of message decoding
* `decode_message_body` method for only message body decoding.

## Usage

```javascript
const decoded = (await client.abi.decode_message({
        abi: abiContract(HelloEventsContract.abi),
        message: boc,
    }));
switch (decoded.body_type) {
case MessageBodyType.Input:
    log_.push(`External inbound message, function "${decoded.name}", fields: ${JSON.stringify(decoded.value)}` );
    break;
case MessageBodyType.Output:
    log_.push(`External outbound message (return) of function "${decoded.name}", fields: ${JSON.stringify(decoded.value)}`);
    break;
case MessageBodyType.Event:
    log_.push(`External outbound message (event) "${decoded.name}", fields: ${JSON.stringify(decoded.value)}`);
    break;
}
```

## Sample source code

**Core**

<https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/subscribe-and-decode/index.js>

**AppKit**

<https://github.com/everx-labs/sdk-samples/tree/master/appkit-examples/listen-and-decode>


# External Signing

How to perform deploy and run scenarios without disclosing the private key

* [When you may need it?](#when-you-may-need-it)
  * [Patterns](#patterns)
* [Use signingBox interface](#use-signingbox-interface)
  * [Sample source code](#sample-source-code)
* [Sign message outside sdk](#sign-message-outside-sdk)
  * [Sample source code](#sample-source-code-1)

## When you may need it?

Sometimes there is no access to the private key - for instance if an application signs data using HSM module or NFC card that does not disclose the private key but provides some API for signing.

### Patterns

There are 2 patterns to implement such scenario:

* use `signingBox` interface to sign message. It will allow you to invoke an API of your signing device during message creation.
* sign message separately - this approach will allow you to separate message creation into 3 steps: create unsigned message, sign it, and attach signature.

Read below for more details.

## Use signingBox interface

Developer needs to create an implementation of this interface in their project and pass it to SDK.

The implementation may incapsulate invoking of some external API, such as HSM of NFC Card.

```javascript
export interface AppSigningBox {
    get_public_key(): Promise<ResultOfAppSigningBoxGetPublicKey>,
    sign(params: ParamsOfAppSigningBoxSign): Promise<ResultOfAppSigningBoxSign>,
}
```

where

```javascript
type ResultOfAppSigningBoxGetPublicKey = {
    public_key: string
}

type ParamsOfAppSigningBoxSign = {
    unsigned: string
}

type ResultOfAppSigningBoxSign = {
    signature: string
}
```

All the methods that create messages - `encode_message`, `process_message` can take [Signer of type SigningBox object](/ever-sdk/reference/types-and-methods/mod_abi#signer), implementing this interface, instead of a key pair.

### Sample source code

**Core sample**

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/signingBox>

**AppKit sample**

<https://github.com/everx-labs/sdk-samples/tree/master/appkit-examples/signing-box>

## Sign message outside sdk

In this case you may create an unsigned message with `encode_message` function, specifying Signer of type `External` . After that you sign it somewhere outside and attach signature with [attach\_signature](/ever-sdk/reference/types-and-methods/mod_abi#attach_signature) function.

### Sample source code

We will upload a sample with it later. If you need it in your work, please write in [SDK telegram channel](https://t.me/ever_sdk).


# Emulate Transaction

Emulate transaction execution locally to understand why it fails

## When you may need it?

If you want to test your contract locally and find out will your operation work on the real network or not, you can emulate it locally.

## Lets debug!

Core SDK provides [run\_executor](/ever-sdk/reference/types-and-methods/mod_tvm#run_executor) method of `tvm` module for it.

[AppKit](https://github.com/everx-labs/ever-appkit-js) provides `localDeploy` and `localRun` functions for it.

### How to emulate contract deploy?

To emulate deploy you need to create a deploy message and execute it locally.

If you plan to emulate local execution afterwards, then retrieve account state (BOC) from deploy emulation result and pass it into the next local execution.

See the JavaScript samples below to understand how to emulate contract deploy.

### How to emulate contract local execution?

To emulate local execution you need to take the current contract state (boc), create a run message and execute it locally on the current account state.

If you emulated deploy before run, then you need to get the account state from the result of the deploy emulation.

For the subsequent call emulations, use account state retrieved from the previous local execution emulation.

See the JavaScript samples below to understand how to emulate contract deploy.

## Sample source code

**Core**

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/run_executor>

**AppKit**

<https://github.com/everx-labs/sdk-samples/tree/master/appkit-examples/run_executor>


# Estimate Fees

Find out how to estimate fees before executing contracts on-chain

## When you may need to estimate fees?

* Before deploy to find out how much it will cost
* Before contract execution to find out how much will it cost
* To calculate how much will it cost to store a contract for a period of time

## Estimate deploy and run fees

The steps you need to complete to estimate fees of deploy and run:

1. Encode a message you will locally execute with [encode\_message](/ever-sdk/reference/types-and-methods/mod_abi#encode_message)
2. Download account boc the same way you did in [Run ABI Get method](/ever-sdk/guides/work_with_contracts/run_abi_get_method)
3. Run the message on the downloaded state with [run\_executor](/ever-sdk/reference/types-and-methods/mod_tvm#run_executor) function
4. Retrieve `result.fees` object. You need **`result.fees.account_fees`** for total account fees value.

## Fees object detailed explanation

Here is the structure of fees object.

* `storage_fee`: *bigint* – Fee for account storage
* `gas_fee`: *bigint* – Fee for processing
* `in_msg_fwd_fee`: *bigint* – Deprecated. Left for backward compatibility.
* `ext_in_msg_fee`: *bigint* – Fee for inbound external message import.
* `total_fwd_fees`: *bigint* – Total fees the account pays for message forwarding
* **`account_fees`: \_bigint**\_\*\* – Total account fees for the transaction execution. Compounds of storage\_fee + gas\_fee + ext\_in\_msg\_fee + total\_fwd\_fees\*\*

#### Deprecated fields. Left for backward compatibility.

* `out_msgs_fwd_fee`: *bigint* – Deprecated. Left for backward compatibility.
* `total_account_fees`: *bigint* – Deprecated. Left for backward compatibility.\
  This is the field that is named as `total_fees` in GraphQL API Transaction type. `total_account_fees` name is misleading, because it does not mean account fees, instead it means validators total fees received for the transaction execution. It does not include some forward fees that account actually pays now, but validators will receive later during value delivery to another account (not even in the receiving transaction but along the way of a chain of transactions processing).\
  Because of all of this, this field is not interesting for those who want to understand\
  the real account fees, this is why it is deprecated and left for backward compatibility.
* `total_output`: *bigint* – Deprecated. Left for backward compatibility.

```graphql
type TransactionFees = {
    in_msg_fwd_fee: bigint,
    storage_fee: bigint,
    gas_fee: bigint,
    out_msgs_fwd_fee: bigint,
    total_account_fees: bigint,
    total_output: bigint,
    ext_in_msg_fee: bigint,
    total_fwd_fees: bigint,
    account_fees: bigint
}
```

## Estimate storage fee

Use [calc\_storage\_fee](/ever-sdk/reference/types-and-methods/mod_utils#calc_storage_fee) method.

## Sample source code

**Core**

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/run_executor>

**AppKit**

<https://github.com/everx-labs/sdk-samples/blob/master/appkit-examples/fee-calculation/index.js>


# Validate address, convert address

Validate and convert address to different formats

## When you may need it?

If you want to validate an address and/or convert address to bounceable/non-bounceable base64/base64url formats and back. These types of address are sometimes used in some clients so may be useful for integration.

## Get address type

{% code overflow="wrap" %}

```javascript
let initialAddressType = await client.utils.get_address_type({address});
console.log(`Address type is ${JSON.stringify(initialAddressType)}`);
```

{% endcode %}

## Convert

Use `utils.convert_address` function for that.

```javascript
let convertedAddress = (await client.utils.convert_address({
    address,
    output_format: {
        type: "Hex"
    },
})).address;
console.log(`Address in raw format: ${convertedAddress}`);
```

### Validate

If address is incorrect the function `utils.convert_address` will fail with an error.

## Sample source code

<https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/utils.convert_address/index.js>


# Monitor Messages

## When you may need message monitor?

The **Message Monitor object** is based on the [GraphQL API extension of the same name](https://docs.everplatform.dev/reference/graphql-api/message-monitor-api). It was developed to solve the problem of batch external message processing.

## About Message Monitor

`Message Monitor` caches the transactions of the last block to provide all users with shard block walking on the backend side, giving batch results, and removing the need to send multiple queries for every message in a batch to discover their status.

Also it ensures a transaction error trace is received on the backend if the transaction was not executed onchain within the specified timeout.

`Message Monitor` allows to:

* subscribe for the statuses of a batch of messages via websocket
* query the status of a batch of messages with 1 query
* monitor object in SDK provides additional capabilities that allow to process messages using a special queue.

Message Monitor Specifications are available here: [**Message Monitor**](/ever-sdk/reference/types-and-methods/mod_processing#monitor_messages)**.**

## Usage

Let’s look at the following Javascript SDK sample, that offers two use cases:

1. I want to send 100 messages at 10 messages per second and get their processing status AS SOON as possible.
2. I want to send 100 messages at 10 messages per second and only get their status when ALL messages have been processed.

The relevant part of the first use case is below:

```json
const TOTAL_NUMBER_OF_MESSAGES = 100
const SEND_INTERVAL_SECONDS = 1
const BATCH_SIZE = 10

// The message is valid (can be processed by validators) no longer that 90 seconds after creation.
const EXP_TIMEOUT_SECONDS = 90

async function main(client: TonClient) {
    log("Starting use case #1")
    let queueName = "queue_1"

    await sendMessages(queueName) // We are waiting for sending only the first batch of messages.

    let resultsCounter = 0
    while (resultsCounter < TOTAL_NUMBER_OF_MESSAGES) {
        const result = await client.processing.fetch_next_monitor_results({
            queue: queueName,
            wait_mode: MonitorFetchWaitMode.AtLeastOne,
        })

        for (const elem of result.results) {
            resultsCounter++
            const processTime = Date.now() - elem.user_data.timestamp
            log(
                `Result: message processed in ${processTime} ms.`,
                elem.error || `Status: ${elem.status}`,
            )
        }
        /* If you're interested, you can call the `get_monitor_info` function, which
         * returns how many messages in a queue do not have final status yet ("unresolved")
         * When `wait_mode = MonitorFetchWaitMode.AtLeastOne`, property "resolved" is always equals to 0
         */
        const monitorInfo = await client.processing.get_monitor_info({
            queue: queueName,
        })
        log("monitor_info", monitorInfo)
    }
    log("End of use case #1, all results received\\n")
```

Here `wait_mode` is set to `MonitorFetchWaitMode.AtLeastOne`, making sure Monitor will deliver message processing results as they come in.

Compare to the second use case, where `wait_mode` is set to `MonitorFetchWaitMode.All`, making monitor wait for all results of the queue to be received:

```json
log("Starting use case #2")

    queueName = "queue_2"
    await sendMessages(queueName) // We are waiting for sending only the first batch of messages.

    const result = await client.processing.fetch_next_monitor_results({
        queue: queueName,
        wait_mode: MonitorFetchWaitMode.All,
    })

    for (const elem of result.results) {
        const processTime = Date.now() - elem.user_data.timestamp
        log(
            `Result: message processed in ${processTime} ms.`,
            elem.error || `Status: ${elem.status}`,
        )
    }
    log(
        result.results.length === TOTAL_NUMBER_OF_MESSAGES
            ? `End of use case #2, all results received`
            : `Error occured, expected ${TOTAL_NUMBER_OF_MESSAGES}, received ${result.results.length}`,
    )
}
```

## Sample source code

* Javascript:

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/message-monitor>

* Rust:

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/rust/message-monitoring>


# Trace message processing with REMP

## Introduction

REMP (Reliable External Messaging Protocol) is a set of protocols and data structures that are designed to keep trace of incoming external messages and predict with a high probability whether a message will be processed successfully.

REMP adds some additional guarantees/features for external messages processing:

**1. Replay protection**

If a message is processed and added into an accepted block, then the same message **(that is, the message with the same hash)** will not be collated for some time period. If the message has some expiration time (corresponding to the time period), then this effectively makes efficient replay protection.

**2. No messages are lost**

You only need to send the message once. If there will be a possibility to accept it and add it to a block, then it will be done. Message loss may occur only for blockchain overloading reasons.

**3. One can trace the message processing.**

There are several checkpoints on the message processing path (when validators received the message, when message was added to a block, when the block was finalized, etc). Upon reaching certain checkpoints one can predict that the message will be successfully processed with a high accuracy - most messages can be considered to be processed when validators acknowledge that they were received (this happens in 100-200 ms; after that it’s highly unlikely that the message is declined). Thus, depending on the message importance one may trade efficiency for reliability in the software, choosing not to trace further processing results. On the other hand, if a transaction is really important, then you can wait till the block with the transaction result is issued.

During validation, as the message passes through various stages (that is, changes some statuses), validator sends receipts about each.

This guide teaches to work with REMP and REMP receipts in EVER SDK.

## Prerequisites

* Create a project on [dashboard.evercloud.dev](https://dashboard.evercloud.dev) if you don't have one.
* Remember its Development Network HTTPS endpoint.
* Pass this endpoint as a parameter when running the example.

## Working with REMP statuses

The sample sends a message to a predeployed test contract.

```javascript
(async () => {
    try {
        console.log('Sending messsage and waiting for REMP events.');
        const { transaction } = await client.processing.process_message(
            {
                send_events: true,
                message_encode_params: {
                    address: CONTRACT_ADDRESS,
                    abi: abiContract(CONTRACT_ABI),
                    call_set: {
                        function_name: 'touch',
                    },
                    signer: signerNone(),
                },
            },
            responseHandler,
        );

        console.log(
            [
                `The message has been processed.`,
                `${rempEventCnt} REMP events received`,
                `Transaction id: ${transaction.id}, status ${transaction.status_name}`,
            ].join('\n'),
        );
        client.close();
    } catch (error) {
        if (error.code === 504) {
            console.error('Network is inaccessible.');
        } else {
            console.error(error);
        }
        process.exit(1);
    }

```

After the message is sent all REMP events related to the message are received and printed, tracing the message processing by validators.

**Note**: By REMP events one can predict with a high probability that the message will be processed successfully, before the processing is complete. Depending on message importance, you can choose to consider it processed as soon as the corresponding receipt arrives and not spend time and resources waiting for further status receipts.

```javascript
function responseHandler(params, responseType) {
    // Tip: Always wrap the logic inside responseHandler in a try-catch block
    // or you will be surprised by non-informative errors due to the context
    // in which the handler is executed
    try {
        if (responseType === 100 /* GraphQL data received */) {
            const { type, json, error } = params;

            assert.ok(type, 'Event always has type');

            if (type.startsWith('Remp')) {
                rempEventCnt++;
                // All REMP event types starts with `Remp`
                // https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_processing#processingevent
                assert.ok(json || error, 'All REMP event has `json` or `error` property');
                if (json) {
                    // We print all REMP events.
                    console.log(`\tREMP event type: ${type}, kind: ${json.kind}`);

                    // but you can pay attention to only a few kinds of events:
                    if (json.kind === 'IncludedIntoBlock') {
                        console.log('\t^^^ this message is probably to be processed successfully');
                    }
                    if (json.kind === 'IncludedIntoAcceptedBlock') {
                        console.log(
                            '\t^^^ this message is highly likely to be processed successfully',
                        );
                    }
                }
                if (error) {
                    // Errors here indicate that there was a problem processing the REMP.
                    // This does not mean that the message cannot be processed successfully,
                    // it only means that the SDK just didn't get the next status at the expected time, see
                    // TonClient config params: `first_remp_status_timeout`, `next_remp_status_timeout`
                    // https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_client#networkconfig
                    //
                    // In this case, the SDK switches to the scenario of waiting for a standby transaction (sequential block reading).
                    console.log(
                        `\tREMP event type: ${type}, code: ${error.code}, message: ${error.message}`,
                    );
                }
            } else {
                // In this example we are interested only in REMP events, so we skip
                // other events like `WillFetchFirstBlock`, `WillSend`, `DidSend`.
                // console.log(`Basic event ${type}`);
            }
        } else {
            // See full list of error codes here:
            // https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_net#neterrorcode
            console.log('ERROR', params, responseType);
        }
    } catch (err) {
        console.log(err);
    }
```

See the full example in sdk samples repository:

<https://github.com/everx-labs/sdk-samples/blob/master/core-examples/node-js/remp/index.js>

## Expected output

```
node index.js https://devnet.evercloud.dev/your-project-id/graphql

Sending messsage and waiting for REMP events.
	REMP event type: RempOther, kind: PutIntoQueue
	REMP event type: RempOther, kind: PutIntoQueue
	REMP event type: RempOther, kind: PutIntoQueue
	REMP event type: RempOther, kind: PutIntoQueue
	REMP event type: RempOther, kind: PutIntoQueue
	REMP event type: RempOther, kind: PutIntoQueue
	REMP event type: RempIncludedIntoBlock, kind: IncludedIntoBlock
	^^^ this message is probably to be processed successfully
	REMP event type: RempOther, kind: Duplicate
	REMP event type: RempOther, kind: Duplicate
	REMP event type: RempOther, kind: Duplicate
	REMP event type: RempOther, kind: Duplicate
	REMP event type: RempOther, kind: Duplicate
	REMP event type: RempIncludedIntoAcceptedBlock, kind: IncludedIntoAcceptedBlock
	^^^ this message is highly likely to be processed successfully
The message has been processed.
13 REMP events received
Transaction id: effed4849898e08d1fe5759532d34f23dbec061c5fd666604f817be82732cfb9, status finalized
```

## Sample Source code

Full sample: <https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/remp>

## See also

Guides for working with REMP in GraphQL API:

{% embed url="<https://docs.everplatform.dev/samples/graphql-samples/subscribe-for-remp-receipts>" %}

{% embed url="<https://docs.everplatform.dev/samples/graphql-samples/send-message>" %}

REMP Architecture documentation:

{% embed url="<https://docs.everscale.network/arch/remp>" %}


# Crypto

This section contains the following cryptographic guides:

* [Mnemonics and keys](/ever-sdk/guides/crypto/mnemonics_and_keys)


# Mnemonics and Keys

This section explains how to generate mnemonics, derive keys and get a key pair

* [Mnemonic generation](#mnemonic-generation)
* [Key pair generation from mnemonic](#key-pair-generation-from-mnemonic)
* [Key pair generation without mnemonic](#key-pair-generation-without-mnemonic)
* [Keys derivation](#keys-derivation)
  * [Master (root) key](#master-root-key)
  * [Derived key](#derived-key)
  * [Generate keys for signature](#generate-keys-for-signature)

> Check [crypto module](/ever-sdk/reference/types-and-methods/mod_crypto) reference for more info:

## Mnemonic generation

To generate a random mnemonic, use `mnemonic_from_random` function. Specify the dictionary, and a number of words (12 or 24).

```javascript
const SEED_PHRASE_WORD_COUNT = 12; //Mnemonic word count
const SEED_PHRASE_DICTIONARY_ENGLISH = 1; //Dictionary identifier

const { phrase } = await client.crypto.mnemonic_from_random({
    dictionary: SEED_PHRASE_DICTIONARY_ENGLISH,
    word_count: SEED_PHRASE_WORD_COUNT,
});
console.log(`Generated seed phrase "${phrase}"`);
```

Result:

```
Generated seed phrase: "garden wedding range mixed during left powder grid modify safe recycle cup"
```

## Key pair generation from mnemonic

Here is the fast way to generate a key pair for a signature from a specified mnemonic and path with `mnemonic_derive_sign_keys` method. The specified path, dictionary and word count is compatible with Surf and Everdev CLI:

```javascript
const HD_PATH = "m/44'/396'/0'/0/0";

const keyPair = await client.crypto.mnemonic_derive_sign_keys({
    phrase,
    path: HD_PATH,
    dictionary: SEED_PHRASE_DICTIONARY_ENGLISH,
    word_count: SEED_PHRASE_WORD_COUNT,
});
console.log(`Generated key pair:`);
console.log(keyPair);
```

Result:

```
Generated key pair:
{
  public: '4085d11b6d607c44ef0e8ddc535786af1a4b1f971e758206cd222ed3eba47d8b',
  secret: 'e90866b307ea6a72c216a34786762e648e9b382779fdfb88cf7b1e900a6bf0e2'
}
```

See the [Keys derivation](#keys-derivation) section for more information about the algorithm that is used in `mnemonic_derive_sign_keys`.

## Key pair generation without mnemonic

Sometimes there is no need for mnemonic.

For example, if you generate a key pair for a server that does not need a readable form. Then you can easily generate such a pair with `generate_random_sign_keys` function:

```javascript
const simpleKeys = await client.crypto.generate_random_sign_keys();
console.log(`key pair not from mnemonic:`);
console.log(simpleKeys);
```

Result:

```
key pair not from mnemonic:
{
  public: 'de996e3004e2bc73b47e8a4fce665847194e2245ddbfc30d9ec2014913249f50',
  secret: 'a761156ff1ad497d4d52a32e32720cc3ef8b0d7c259f6d91b9f236d6288e12a3'
}
```

Great! Now you can use this key pair in methods of contracts module, such as `abi.encode_message`, `abi.encode_message_body`, etc.

## Keys derivation

### Master (root) key

To derive a key within a specified path, first, you need to generate a seed from the given mnemonic and then get the extended master private key that will be the root for all the derived keys.

Both these operations can be performed with `hdkey_xprv_from_mnemonic` method:

```javascript
const hdk_root = await client.crypto.hdkey_xprv_from_mnemonic({
        dictionary: SEED_PHRASE_DICTIONARY_ENGLISH, // 1
        wordCount: SEED_PHRASE_WORD_COUNT, // 12
        phrase: seedPhrase
    });
console.log(`\nSerialized extended master private key: \n${hdk_root}`);
```

Result:

```
Serialized extended master private key: 
xprv9s21ZrQH143K45hXeaopM1rAUJDszLAcwFkxrZ4njANoGhFPYFsB7rzspWC8wAnWoZ2bPia7covh3mVVboC2nEswu18iEHs5LjVknSWMR2w
```

### Derived key

Now you can derive the key within the specified path with `hdkey_derive_from_xprv_path` method. The result will be an extended derived private key.

```javascript
const HD_PATH = "m/44'/396'/0'/0/0";
const extended_prkey = await client.crypto.hdkey_derive_from_xprv_path({
    xprv: hdk_root,
    path: HD_PATH,
});
console.log(`Serialized derived extended private key: \n${extended_prkey}`);
```

Result:

```
Serialized derived extended private key: 
xprvA45BBKdrZKobCbeFvC316LZ6AVDXbDn8Sa3btCMCcgTRM4CRxX4Tg3fk7sNNXPza9aMiS6mBMp7wfHdmT23bri6YgwHbTJgXqKnJNNHAw98
```

Now lets extract the private key itself from the extended key with function:

```javascript
const secret = await сlient.crypto.hdkey_secret_from_xprv(extended_prkey);
console.log(`Derived private key: \n${secret}`);
```

Result:

```
Derived private key: 
e90866b307ea6a72c216a34786762e648e9b382779fdfb88cf7b1e900a6bf0e2
```

### Generate keys for signature

After we've got the derived private key we can generate a ed25519 key pair for signature:

```javascript
let tonosKeyPair2 = await сlient.crypto.nacl_sign_keypair_from_secret_key({ secret })

if (tonosKeyPair2.secret.length > tonosKeyPair2.public.length) {
tonosKeyPair2.secret = tonosKeyPair2.secret.substring(0, tonosKeyPair2.public.length);
}
console.log(`Key pair for signature:`);
console.log(tonosKeyPair2);
```

Result:

```
Key pair for signature:
{
  public: '4085d11b6d607c44ef0e8ddc535786af1a4b1f971e758206cd222ed3eba47d8b',
  secret: 'e90866b307ea6a72c216a34786762e648e9b382779fdfb88cf7b1e900a6bf0e2'
}
```

Great! Now you can use this key pair in methods of contracts module, such as `abi.encode_message`, `abi.encode_message_body`, etc.


# Queries and subscriptions

This section contains the following guides on working with queries and subscriptions


# Use-cases

What data can you get from GraphQL API?

* Get API data
* Subscribe to data updates
* Easily paginate such data as blocks, transactions

[See the full API use-cases here.](https://docs.everplatform.dev/reference/graphql-api#use-cases)


# How to work with net module

To get API data with the help of SDK, just wrap the GraphQL query inside net.query function.

[GraphQL samples. ](https://docs.everplatform.dev/samples/graphql-samples/accounts)

See the next page how to do it.&#x20;


# net.query syntax

Write your graphql query in playground, copy it and insert into SDK's net.query function.  Define variables and execute it.

## About `net.query` function

Whenever you need to poll realtime data from GraphQL API with SDK - use [net.query](/ever-sdk/reference/types-and-methods/mod_net#query) function.

Write your graphql query in playground, copy it and insert into SDK's net.query function. Define variables and execute it.

See All the functions available in API here

## Usage

### Pass parameters via `variables` object

You can pass variables via a separate parameter (graphql-style). You just copy the query from playground and replace the param values with $param\_name and then pass parameters via additional object like this:

{% hint style="success" %}
If you use variables object, you need to wrap your query in\
query MyQuery(params){$param1: Param1Type}.
{% endhint %}

{% hint style="danger" %}
If the parameter is mandatory you must specify its type with exclamation mark on the end like this:\
query MyQuery(params){$param1: Param1Type!}
{% endhint %}

```javascript
await client.net.query({
    query: `query MyQuery($utime: Int){
    blockchain {
        master_seq_no_range(time_end: $utime) { end }
    }
}`,
    variables: { utime },
})
```

### Pass parameters inline

```javascript
await client.net.query({
    query: `
    blockchain {
        master_seq_no_range(time_end: ${utime}) { end }
    }`
})
```

See this sample to understand how to pass variables to the queries

{% embed url="<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/pagination>" %}


# Data pagination

How to use cursor based pagination of Everscale blocks, transactions and messages

Read about each entity type pagination API:

* [Blocks](https://docs.everplatform.dev/samples/graphql-samples/blocks#blocks-pagination)
* [Transactions](https://docs.everplatform.dev/samples/graphql-samples/transactions#paginate-blockchain-transactions)
* [Account transactions](https://docs.everplatform.dev/samples/graphql-samples/accounts#get-transactions-within-block-seqno-range)
* [Account messages](https://docs.everplatform.dev/samples/graphql-samples/accounts#get-messages-within-block-range)

Look at the sample how to implement these entities pagination with JS SDK:

{% embed url="<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/pagination>" %}


# Subscribe to Updates

Subscribe to any updates in blockchain database, including contract events.

## When you may need it?

Whenever you need to improve UI responsiveness or want to receive updates on your backend as they appear - you may use websocket subscriptions.

## Usage

### Account updates

```javascript
const accountSubscription = await TonClient.default.net.subscribe_collection({
    collection: "accounts",
    filter: { id: { eq: address } },
    result: "balance",
}, (params, responseType) => {
    if (responseType === ResponseType.Custom) {
        console.log("Account has updated. Current balance is ", parseInt(params.result.balance));
    }
});
```

### Account messages

```javascript
const messageSubscription = await TonClient.default.net.subscribe_collection({
    collection: "messages",
    filter: {
        src: { eq: address },
        OR: {
            dst: { eq: address },
        }
    },
    result: "boc",
}, async (params, responseType) => {
    try {
        if (responseType === ResponseType.Custom) {
            const decoded = (await TonClient.default.abi.decode_message({
                abi: abiContract(your-contract-abi),
                message: params.result.boc,
            }));
            switch (decoded.body_type) {
            case MessageBodyType.Input:
                console.log(`External inbound message, function "${decoded.name}", parameters: `, JSON.stringify(decoded.value));
                break;
            case MessageBodyType.Output:
                console.log(`External outbound message, function "${decoded.name}", result`, JSON.stringify(decoded.value));
                break;
            case MessageBodyType.Event:
                console.log(`External outbound message, event "${decoded.name}", parameters`, JSON.stringify(decoded.value));
                break;
            }
        }
    } catch (err) {
        console.log('>>>', err);
    }
});
```

See this sample to understand how to use [subscribe\_collection](/ever-sdk/reference/types-and-methods/mod_net#subscribe_collection) function:

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/listen-and-decode>


# Query Collection

{% hint style="warning" %} <mark style="color:red;">**Collections is an analytics API (not real-time, though it may look like one).**</mark>

<mark style="color:red;">**Not all filters and sortings are working now. Data is provided only for the past 7 days.**</mark>
{% endhint %}

## When you may need collections?

If you want to apply some custom filters and sortings on the data.

## About collections

There are a few collections with blockchain data:

* *accounts*: blockchain account data;
* *transactions*: transactions related to accounts;
* *messages*: input and output messages related to transactions;
* *blocks*: blockchain blocks.
* *block\_signatures* : validator block signatures

[Use `query_collection` method to query data that can be filtered and sorted](/ever-sdk/reference/types-and-methods/mod_net#query_collection).

## Usage

```javascript
await client.net.query_collection({
    collection: 'accounts',
    filter: {
        id: {
            eq: wallet1Address
        }
    },
    result: 'balance'
})
```

## Sample source code

**Core**

<https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/query>

**AppKit**

<https://github.com/everx-labs/sdk-samples/tree/master/appkit-examples/query>


# Aggregate Collection

{% hint style="warning" %} <mark style="color:red;">**Collections is an analytics API (not real-time, though it may look like one).**</mark>

<mark style="color:red;">**Not all filters and sortings are working now. Data is provided only for the past 7 days.**</mark>
{% endhint %}

## When you may need aggregate of collections?

If you want to apply some aggregators like COUNT, MAX, MIN, SUM, AVERAGE on some blockchain data.

## Usage

```javascript
const aggregationFunctionsResults = result = 
        (await client.net.aggregate_collection({
        collection: 'accounts',
        fields: [
            {
                field: "balance",
                fn: "MIN"
            },
            {
                field: "balance",
                fn: "MAX"
            }, {
                field: "balance",
                fn: "AVERAGE"
            }, {
                field: "balance",
                fn: "SUM"
            },
            {
                field: "balance",
                fn: "COUNT"
            }
        ]
    })).values;
console.log("Minimum account balance: " + aggregationFunctionsResults[0]);
console.log("Maximum account balance: " + aggregationFunctionsResults[1]);
console.log("Average balance: " + aggregationFunctionsResults[2]);
console.log("Total balance of all accounts: " + aggregationFunctionsResults[3]);
console.log("Number of accounts: " + aggregationFunctionsResults[4] + '\n');
```

## About collections

There are a few collections with blockchain data:

* *accounts*: blockchain account data;
* *transactions*: transactions related to accounts;
* *messages*: input and output messages related to transactions;
* *blocks*: blockchain blocks.
* *block\_signatures* : validator block signatures

[Reference](/ever-sdk/reference/types-and-methods/mod_net#aggregate_collection)

Sample: <https://github.com/everx-labs/sdk-samples/tree/master/core-examples/node-js/query>


# How to work with Application Objects in binding generators

Binding generator must detect functions that accept application objects.

Application object interaction protocol and functions that accept app objects have the following signatures in core:

```rust
/// Methods of the Foo interface with parameters
enum ParamsOfAppFoo {
    CallWithParamsAndResult { a: String, b: String },
    CallWithParams { a: String, b: String },
    CallWithResult,
    CallWithoutParamsAndResult,
    NotifyWithParams { a: String, b: String },
    NotifyWithoutParams
}

/// Method results of the Foo interface
enum ResultOfAppFoo {
    CallWithParamsAndResult { c: String },
    CallWithParams,
    CallWithResult { c: String },
    CallWithoutParamsAndResult,
}

/// API function that accepts an application object as a parameter
async fn foo(
		context: Arc<ClientContext>,
		params: ParamsOfFoo,
		obj: AppObject<ParamsOfAppFoo, ResultOfAppFoo>,
) -> ClientResult<()> {}
```

It means when a function accepts an application-implemented object, from that point library will have access to the methods of this object.

### How to detect

Function contains parameter with generic type `AppObject<foo_module.ParamsOfAppFoo, foo_module.ResultOfAppFoo>`.

### Generated code

Generator must produce:

* interface declaration;
* interface dispatcher;
* function that accept application object.

### Interface declaration

```tsx
export type ParamsOfAppFooCallWithParamsAndResult {
    a: string,
    b: string,
}

export type ResultOfAppFooCallWithParamsAndResult {
    c: string,
}

export type ParamsOfAppFooCallWithParams {
    a: string,
    b: string,
}

export type ResultOfAppFooCallWithResult {
    c: string,
}

export type ParamsOfAppFooNotifyWithParams {
    a: string,
    b: string,
}

export interface AppFoo {
    call_with_params_and_result(params: ParamsOfFooWithParamsAndResult): Promise<ResultOfFooWithParamsAndResult>,
    call_with_params(params: ParamsOfFooWithParams): Promise<void>,
    call_with_result(): Promise<ResultOfFooWithResult>,
    notify_with_params(params: ParamsoOfFooNotifyWithParams),
    notify_without_params(),
}
```

* Interface `Foo` is extracted from the name of the first generic arg of the `AppObject<foo_module.ParamsOfAppFoo, foo_module.ResultOfAppFoo>`. Note that a generic arg name is a fully qualified name so you must remove the module name first. In the example above the first arg name is `foo_module.ParamsOfAppFoo.` After removing module name we have `ParamsOfAppFoo`. Then we must remove the prefix `ParamsOf`. The rest of the name contains the interface name `Foo`.
* To collect a list of interface methods we must collect variant names from enum `foo_module.ParamsOfAppFoo`. Each variant of `ParamsOfAppFoo` represents the interface method. Respectively each variant of `ResultOfAppFoo` represents the result of the interface method. If interface method has no `ResultOfAppFoo` then such method is a notify method – no waiting for the response is needed.
* The name of the interface method is constructed from the name of the variant by using a simple rule `PascalStyleName` → `snake_style_name`. So the variant `CallWithParamsAndResult` will be converted to `call_with_params_and_result`.
* If a function has a result then this function must return `Promise` and perform asynchronous execution.

### Interface dispatcher

The implementation of the wrapper method is more difficult than regular. It must pass dispatching `responseHandler` to the library. Library will call this handler every time when it requires to call the application object. Two response types are used for calling application objects: `3` for calling methods which return result and `4` for notifiyng without awaiting any result. When response type `4` is passed, data contains enum `ParamsOfAppFoo`. When `3` is passed, data contains struct `ParamsOfAppRequest` where `request_data` field contains `ParamsOfAppFoo`

```tsx
type ParamsOfAppRequest {
		app_request_id: number,
		request_data: any,
}
```

Generator must define special dispatch helper for application object invocation:

```tsx
async function dispatchFoo(obj: Foo, params: ParamsOfAppFoo, app_request_id: number | null, client: TonClient) {
    try {
        let result = undefined;
		    switch (params.type) {
		    case 'CallWithParamsAndResult':
		        result = await obj.call_with_params_and_result(params);
		        break;
		    case 'CallWithParams':
		        await obj.call_with_params(params);
		        break;
		    case 'CallWithResult':
		        result = await obj.call_with_result();
		        break;
		    case 'CallWithoutParamsAndResult':
		        await obj.call_with_result();
		        break;
		    case 'NotifyWithParams':
		        obj.notify_with_params(params);
		        break;
		    case 'NotifyWithoutParams':
		        obj.notify_without_params();
		        break;
				}
				if (app_request_id) {
            client.resolve_app_request({ app_request_id, result: { type: 'Ok', result: { type: params.type, ...result }}});
        }
    }
    catch (error) {
        if (app_request_id) {
            client.resolve_app_request({ app_request_id, result: { type: 'Error', text: error.message }});
        }
    }
}
```

### Functions with application object

The `obj` parameter must be declared instead of the source `obj: AppObject<ParamsOfAppFoo, ResultOfAppFoo>`.

Wrapper implementation with dispatcher must be generated as:

```tsx
type ParamsOfFoo {
		...
}

export class AppFoo {
    foo(params: ParamsOfFoo, obj: Foo): Promise<ResultOfFoo> {
        return this.client.request('foo', params, (params, responseType) => {
            if (responseType === 3) {
                 dispatchFoo(obj, params.request_data, params.app_request_id, this);
            } else if (responseType === 4) {
                 dispatchFoo(obj, params, null, this);
            }
        }
    }
}
```


# JSON Interface to Ton Client

## JSON Interface to Ton Client

In addition to the native rust interface the core library has an alternative JSON RPC like interface.

The interaction with library is performed using an asynchronous request/response calls.

The library provides the `request` function to receive requests. And the application provides `response_handler` to receive responses from library related to requests.

This interface is offered for *bindings* – a small wrapping libraries which purpose is to directly use the ton client library in languages others than *Rust*.

Counterparts:

* *Application* – uses native language interface, provided by *binding* library.
* *Binding* – provides native language interface to ton client library. Uses JSON Interface to directly call ton client library.
* *Library (or Core)* – provides JSON Interface to all ton client functionality.

### Strings

Many library functions operates with strings. So there are a responsibility for string ownership and lifetimes.

There are two types related to strings:

```c
typedef struct {
    const char* content;
    uint32_t len;
} tc_string_data_t;

typedef struct tc_string_handle_t tc_string_handle_t;

```

* `tc_string_handle_t` – internal Rust string representation. Application or binding can't use this memory directly. There is the `tc_read_string` function for this purpose. Application responsible for the releasing of string with `rc_destroy_string` function.
* `tc_string_data_t` – temporarily access string internal data. `content` field points to the `utf8` encoded content of the string and the `len` field contains the content size in bytes. Note that content **IS NOT NULL TERMINATED**.

String manipulation functions:

```c
tc_string_data_t tc_read_string(const tc_string_handle_t* string);
void tc_destroy_string(const tc_string_handle_t* string);
```

* `tc_read_string` – read string content provided by the `string` pointer. Returned value is the internal string data. Note that this data will be invalid after the string will be destroyed.
* `tc_destroy_string` – destroys rust string provided by `string` pointer.

### Contexts

All library functions requires *context* – the main library object that encapsulates configuration and state data.

Application can create many contexts and use them all together. For example – creates two contexts that configured to work with different blockchain networks.

Context related functions:

```c
tc_string_handle_t* tc_create_context(tc_string_data_t config);
void tc_destroy_context(uint32_t context);
```

* `tc_create_context` – create context using provided `config` with configuration json. Returned string is a JSON with the result or the error. Result is returned in form of `{ "result": context }` where `context` is a number with context handle. Error is returned in form `{ "error": { error fields } }`. **Note**: `tc_create_context` doesn't store pointer passed in `config` parameter. So it is safe to free this memory after the function returns.\
  **Important**: application is responsible for freeing of the receiving string. Example:

  ```c
  tc_string_data config = {"{}", 2};
  tc_string_handle_t* json_ptr = tc_create_context(config);
  tc_string_data json = tc_read_string(json_ptr);
  uint32_t context = parse_create_context_json(json.content, json.len);
  tc_free_string(json_ptr);
  ```

  Config contains optional `binding` section with information about binding. It is good practice to provide this information into core library because core library includes this information into logs, errors etc. Providing binding information will help users and binding authors to determine possible error reason. The best way is to merge users config with binding information before calling `tc_create_config`. Typical code snippet to merge binding info:

  ```typescript
  function createContext(config: ClientConfig): number {
      const configWithBindingInfo = {
          ...config,
          binding: {
              library: "your-library-name",
              version: "1.0.0",
          },
      };
      return tc_create_context(JSON.stringify(configWithBindingInfo)));
  }
  ```
* `tc_destroy_context` – closes and releases all recourses that was allocated and opened by library during serving functions related to provided context.

### Request

When application requires to invoke some ton client function it sends a function request to the library.

```c
void tc_request(
    uint32_t context,
    tc_string_data_t function_name,
    tc_string_data_t function_params_json,
    uint32_t request_id,
    tc_response_handler_t response_handler);

void tc_request_ptr(
    uint32_t context,
    tc_string_data_t function_name,
    tc_string_data_t function_params_json,
    void* request_ptr,
    tc_response_handler_ptr_t response_handler);
```

Where:

* `function_name` – function name requested.
* `function_params_json` – function parameters encoded as a JSON string. If a function hasn't parameters then en empty string must be passed.
* `request_id` or `request_ptr` – application (or binding) defined request identifier or pointer. Usually binding allocates and stores some additional data with every request. This data will help in the future to properly route responses to the application.
* `response_handler` – function that will receive responses related to this request.

This function returns nothing. The function execution result will be sent to the `response_handler`.

**Note**: `response_handler` can be called before the function returns.

**Note**: `tc_request` doesn't store pointers passed in `function_name` and `function_params_json` parameters. So it is safe to free this memory after the function returns.

#### Request Id versus Request Pointer

Ton Client Library has two version of request context representation:

* `id` – Each request is identified by `u32` integer value defined by application. In this case the application or binding usually uses global hash map to associate additional response dispatch information.
* `pointer` – Each request is identified by `void*` pointer defined by application. In this case the application or binding uses pointers to native objects with additional response dispatch information. For example a pointer to closure. Note, that library doesn't use this pointer and memory pointed to. It just stores this pointer and provides it back to application when library calls response handler.

**Note** `pointer` supports is UNSTABLE feature yet and can be refined.

### Responses

Application (or binding) defines function `response_handler` that will receive the request responses.

The response includes the mandatory function result or error and optional additional data responses.

```c
enum tc_response_types_t {
    tc_response_success = 0,
    tc_response_error = 1,
    tc_response_nop = 2,
    tc_response_app_request = 3,
    tc_response_app_notify = 4,
    tc_response_custom >= 100,
};

typedef void (*tc_response_handler_t)(
    uint32_t request_id,
    tc_string_data_t params_json,
    uint32_t response_type,
    bool finished);

typedef void (*tc_response_handler_ptr_t)(
    void* request_ptr,
    tc_string_data_t params_json,
    uint32_t response_type,
    bool finished);
```

`response_handler` – handles responses from the library. Note that an application can receive an unlimited count of responses related to single request. Parameters:

* `request_id` or `request_ptr` – the request to which this response is addressed.
* `params_json` – response parameters encoded into JSON string.
* `response_type` – type of this response:
  * `RESULT = 0`, function result.
  * `ERROR = 1`, function execution error.
  * `NOP = 2`, no operation. In combination with `finished = true` signals that the request handling was finished.
  * `APP_REQUEST = 3`, request some data from application. See [Application objects](#Application-objects)
  * `APP_NOTIFY = 4`, notify application with some data. See [Application objects](#Application-objects)
  * `RESERVED = 5..99` – reserved for protocol internal purposes. Application (or binding) must ignore this response. Nevertheless the binding must check the `finished` flag to release data, associated with request.
  * `CUSTOM >= 100` - additional function data related to request handling. Depends on the function.
* `finished` – is a signal to release all additional data associated with the request. It is last response for specified request\_id.

**Important**:

* Application MUST NOT store pointers passed in `params_json` and use it after `response_handler` has been returned, if an application requires this data after returning then it must creates an own copy.
* Application MUST NOT free memory of pointers passed in `params_json`.
* Response handler can be called before the `tc_request` returns. In this case the response handler will be called on the calling thread.
* Responses can be called on background thread created by library to serve asynchronous tasks. All responses, related to the same request will be called from the same thread in right sequence.

## Bindings

Here we are look to the typical binding structure. In this example we will use the *Type Script*.

Declare high level function wrapper:

```ts
async function getVersion(context: number): Promise<string>;
```

Define additional data allocated for each request:

```ts
type Request = {
    resolve: (result: any) => void,
    reject: (error: Error) => void,
    responseHandler?: (params: any) => void,
}

const requests = new Map<number, Request>();
let nextRequestId = 1;

```

Map library responses to high level handlers:

```ts
function libraryResponseHandler(
    requestId: number, 
    paramsJson: string, 
    responseType: number,
    finished: bool
) {
    const request = requests.get(requestId);
    if (!request) {
        return;
    }
    if (finished) {
        requests.delete(requestId);
    }
    const params = paramsJson !== '' ? JSON.parse(paramsJson) : undefined;
    switch (responseType) {
        case 0: // RESULT
            request.resolve(params);
            break;
        case 1: // ERROR
            request.reject(params);
            break;
        default: // DATA
            if (responseType >= 100 && request.responseHandler) {
                request.responseHandler(params);
            }
            break;
    }
}

```

Map high level call to library request / response chain:

```ts
function requestLibrary(
    context: number,
    functionName: string, 
    functionParams: any, 
    responseHandler?: (params: any) => any,
): Promise<any> {
    return new Promise((resolve, reject) => {
        const requestId = nextRequestId;
        nextRequestId += 1;
        requests.set(requestId, { resolve, reject, responseHandler });
        tc_request(context, functionName, functionParams, requestId, libraryResponseHandler);
    });
}

```

Implement high level function:

```ts
async function getVersion(context: number): Promise<string> {
    const response = await requestLibrary(context, "client.version", "");
    return response.version;
}
```

### Application objects

SDK has some features that require interaction with client applications. Such features are for example, external signing interface - so-called "signing box", and debot. We call them `Application objects`. Such an object can be represented as a set of functions which either return execution result (requests) or not (notifications).

Application object is implemented using a callback passed into `tc_request`. For such case two response types are used: `APP_REQUEST = 3` for requests that require some response from application and `APP_NOTIFY = 4` for notifications with no response needed. When response type is `3`, `params_json` parameter contains serialized structure `ParamsOfAppRequest`

```tsx
type ParamsOfAppRequest {
		app_request_id: number,
		request_data: any,
}
```

Here `request_data` is some data describing the request and `app_request_id` is ID of the request, which should be used for request result resolving. After the request is processed application should call `client.resolve_app_request` function passing `app_request_id` used in the request and result of processing.

In case if response type is `4`, `params_json` contains serialized notification data without any wrappers. Application processes notification in the way it needs. No response is needed for SDK.

#### How to work with Application Objects in binding generators

Find out how to work with Application Objects in binding generators in this [specification](/ever-sdk/for-binding-developers/app_objects).


