# Dapp ID Full Guide: creation, fees, centralized replenishment

## **What will you learn from this guide?** <a href="#prerequisites" id="prerequisites"></a>

* How to create your [Dapp ID](https://docs.ackinacki.com/glossary#dapp-id)
* How to interact with contracts inside a Dapp
* How to interact with contracts of other Dapps
* How to use the centralized replenishment mechanism for the Dapp ID contracts

## **Prerequisites** <a href="#prerequisites" id="prerequisites"></a>

* [TVM-Solidity-Compiler](https://github.com/gosh-sh/TVM-Solidity-Compiler)
* [TVM-CLI and Multisig Wallet](/how-to-deploy-a-multisig-wallet)

## Configure CLI tool

In this guide, we will use the test network at [`shellnet.ackinacki.org`](https://shellnet.ackinacki.org).\
We need to specify the blockchain endpoint for deployment:

```
tvm-cli config -g --url shellnet.ackinacki.org
```

## Create your first Dapp ID

You create a new Dapp ID when you deploy a contract using an external message. The address of this contract becomes the Dapp ID of your system.

If your Dapp consists of multiple contracts, you need to implement your system so that all the contracts are deployed either from the root contract or its children.

In this guide, we will use the [`helloWorld`](https://github.com/tvmlabs/sdk-examples/blob/main/contracts/helloWorld/helloWorld.sol) contract to demonstrate the features of a Dapp ID.

```solidity
pragma tvm-solidity >=0.76.1;
pragma AbiHeader expire;

interface IHelloWorld {
    function touch() external;
}


// This is class that describes you smart contract.
contract helloWorld {
    // Contract can have an instance variables.
    // In this example instance variable `timestamp` is used to store the time of `constructor` or `touch`
    // function call
    uint32 public timestamp;

    // The contract can have a `constructor` – a function that is called when the contract is deployed to the blockchain.
    // Parameter `value` represents the number of SHELL tokens to be converted to VMSHELL to pay the transaction fee.
    // In this example, the constructor stores the current timestamp in an instance variable.
    // All contracts need to call `tvm.accept()` for a successful deployment.
    constructor(uint64 value) {
        // Call the VM command to convert SHELL tokens to VMSHELL tokens to pay the transaction fee.
        gosh.cnvrtshellq(value);

        // Ensure that the contract's public key is set.
        require(tvm.pubkey() != 0, 101);

        // The current smart contract agrees to buy some gas to complete the
        // current transaction. This action is required to process external
        // messages, which carry no value (and therefore no gas).
        tvm.accept();

        // Set the instance variable to the current block timestamp.
        timestamp = block.timestamp;
    }

    // Converts SHELL to VMSHELL for payment of transaction fees
    // Parameter `value`- the amount of SHELL tokens that will be exchanged 1-to-1 into VMSHELL tokens.
    function exchangeToken(uint64 value) public pure {
        tvm.accept();
        getTokens();
        gosh.cnvrtshellq(value);
    }

    // Returns a static message, "helloWorld".
    // This function serves as a basic example of returning a fixed string in Solidity.
    function renderHelloWorld () public pure returns (string) {
        return 'helloWorld';
    }

    // Updates the `timestamp` variable with the current blockchain time.
    // We will use this function to modify the data in the contract.
    // Сalled by an external message.
    function touch() external {
        // Informs the TVM that we accept this message.
        tvm.accept();
        getTokens();
        // Update the timestamp variable with the current block timestamp.
        timestamp = block.timestamp;
    }

    // Used to call the touch method of a contract via an internal message.
    // Parameter 'addr' - the address of the contract where the 'touch' will be invoked.
    function callExtTouch(address addr) public view {
        // Each function that accepts an external message must check that
        // the message is correctly signed.
        require(msg.pubkey() == tvm.pubkey(), 102);
        tvm.accept();
        getTokens();
        IHelloWorld(addr).touch();
    }

    // Sends VMSHELL to another contract with the same Dapp ID.
    // Parameter `dest` - the target address within the same Dapp ID to receive the transfer.
    // Parameter `value`- the amount of VMSHELL tokens to transfer.
    // Parameter `bounce` - Bounce flag. Set true if need to transfer funds to existing account;
    // set false to create new account.
    function sendVMShell(address dest, uint128 amount, bool bounce) public view {
        require(msg.pubkey() == tvm.pubkey(), 102);
        tvm.accept();
        getTokens();
        // Enables a transfer with arbitrary settings
        dest.transfer(varuint16(amount), bounce, 0);
    }

    // Allows transferring SHELL tokens within the same Dapp ID and to other Dapp IDs.
    // Parameter `dest` - the target address to receive the transfer.
    // Parameter `value`- the amount of SHELL tokens to transfer.
    function sendShell(address dest, uint128 value) public view {
        require(msg.pubkey() == tvm.pubkey(), 102);
        tvm.accept();
        getTokens();

        TvmCell payload;
        mapping(uint32 => varuint32) cc;
        cc[2] = varuint32(value);
        // Executes transfer to target address
        dest.transfer(0, true, 1, payload, cc);
    }

    // Deploys a new contract within its Dapp.
    // The address of the new contract is calculated as a hash of its initial state.
    // The owner's public key is part of the initial state.
    // Parameter `stateInit` - the contract code plus data.
    // Parameter `initialBalance` - the amount of funds to transfer. 
    // Parameter `payload` - a tree of cells used as the body of the outbound internal message.
    function deployNewContract(
        TvmCell stateInit,
        uint128 initialBalance,
        TvmCell payload
    )
        public pure
    {
        // Runtime function to deploy contract with prepared msg body for constructor call.
        tvm.accept();
        getTokens();
        address addr = address.makeAddrStd(0, tvm.hash(stateInit));
        addr.transfer({stateInit: stateInit, body: payload, value: varuint16(initialBalance)});
    }
    
    // Checks the contract balance
    // and if it is below the specified limit, mints VMSHELL.
    // The amounts are specified in nanotokens.
    // Used to enable automatic balance replenishment.
    function getTokens() private pure {
        if (address(this).balance > 100000000000) {     // 100 VMSHELL
            return; 
        }
        gosh.mintshell(100000000000);                   // 100 VMSHELL
    }

}


```

### **Prepare contract source code**

Let's create a folder for our project and clone the [repository](https://github.com/tvmlabs/sdk-examples/tree/main) with examples into it:

<pre><code>cd ~
mkdir helloWorld
<strong>cd helloWorld
</strong>git clone https://github.com/tvmlabs/sdk-examples.git

</code></pre>

and copy the `contracts` folder from there:

```
cp -r sdk-examples/contracts .
cd contracts/helloWorld
```

### **Compile**

Compile the contract `helloWorld` using [TVM Solidity compiler](https://github.com/gosh-sh/TVM-Solidity-Compiler/releases/tag/gosh_0.79.3):

```
sold --tvm-version gosh helloWorld.sol
```

The compiler produces `helloWorld.tvc` and `helloWorld.abi.json` to be used in the next steps.

TVM binary code of your contract is stored into `helloWorld.tvc` file.

### **Top up with Shell**

To deploy a contract, its balance must be funded with SHELL tokens.

To do this, we first need to determine its address. Let's start by generating a **seed phrase** and **keys** for your contract:

<pre><code><strong>tvm-cli genphrase --dump helloWorld.keys.json
</strong></code></pre>

{% hint style="info" %}
**Seed phrase** is printed to stdout.\
**Key pair** will be generated and saved to the file **`helloWorld.keys.json`**.
{% endhint %}

<figure><img src="/files/FeMMLeo4D7hUh5I50yZM" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
**Write your Seed Phrase down and store it somewhere safe, and never share it with anyone. Avoid storing it in plain text or screenshots, or any other non-secure way. If you lose it, you will not be able to recover it from your Key Pair. If you lose both Seed Phrase and Key Pair you lose access to your assets. Anyone who gets it, gets full access to your assets.**\
**Also, save the file with a pair of keys in a safe place.**
{% endhint %}

Now let's generate the **contract address** using the keys obtained earlier:

```
tvm-cli genaddr helloWorld.tvc --save --setkey helloWorld.keys.json
```

{% hint style="info" %}
After this step, the `.tvc` file will be overwritten with the specified keys.
{% endhint %}

Address of your contract in the blockchain is located after `Raw address:`

<figure><img src="/files/zyn7dneLBF7Yy0G0T9FG" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**Save `Raw address` value** - you will need it to deploy your contract and to work with it.\
We will refer to it as **`<YourAddress>`** below.
{% endhint %}

To top up the balance (approx. 10 SHELL) of the `helloWorld` contract, [use your Multisig Wallet](/how-to-deploy-a-multisig-wallet#how-to-use-a-sponsor-wallet)

and apply the following method `sendTransaction`:

```
sendTransaction(address dest, uint128 value, mapping(uint32 => varuint32) cc, bool bounce, uint8 flags, TvmCell payload)
```

* `dest` - the transfer target address;
* `value` - the amount of funds (nanoVMSHELL) used to pay fees (it must not be `0`);
* `cc` - the type of ECC token (SHELL has index 2) and amount (specified in nanotokens) to transfer;
* `bounce` - [bounce flag](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer): (should be `false`);
* `flags-`[sendmsg flags](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer) (should be `1`);
* `payload` - [tree of cells used as body](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer) of the outbound internal message (should be an empty string).

For example: you can use the command:

<pre><code><strong>tvm-cli call 0:90c1fe4ab3a86a112e72a587fa14b89ecb2836da0b4ec465543dc0bb62df1430 sendTransaction '{"dest":"0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e", "value":0, "bounce":false, "cc": {"2": 1000000000}, "flags": 1, "payload": ""}' --abi multisig.abi.json --sign multisig.keys.json
</strong>
</code></pre>

{% hint style="info" %}
Within Dapp ID, you can transfer both ECC tokens (e.x.SHELL) and VMSHELL.\
**For contracts of other Dapp IDs, only ECC tokens can be transferred.**
{% endhint %}

Check the state of the pre-deployed contract. It should be `Uninit`:

```
tvm-cli account <YourAddress>
```

You will see something similar to the following:

<figure><img src="/files/LXLaPNXtPhz9IhQnR9LW" alt=""><figcaption></figcaption></figure>

### Deploy

When you deploy a contract with external message contract must exchange some amount of [SHELL](https://docs.ackinacki.com/glossary#shell) into [VMSHELL](https://docs.ackinacki.com/glossary#vmshell) during the contract deployment. To do this, the contract’s constructor must call the VM command `gosh.cnvrtshellq(uint64 value).`

{% hint style="warning" %}
**CNVRTSHELLQ converts SHELL to VMSHELL at a 1:1 ratio**

Q in the end stands for ‘quiet’ which means that if there is not enough Shell, it will not throw an exception.

If the account balance does not have the required number of tokens, the exchange will be made for the entire available amount. That is, MIN(available\_tokens, want\_to\_convert\_amount).
{% endhint %}

Go back now and check the constructor code of `helloWallet` - you will find this command.

Lets deploy `helloWorld` and create our first Dapp ID with this command:

```
tvm-cli deploy --abi helloWorld.abi.json --sign helloWorld.keys.json helloWorld.tvc '{"value":10000000000}'
```

<figure><img src="/files/6VKHpkZggu9boky7Nd9I" alt=""><figcaption></figcaption></figure>

6. Check the contract state again. This time, it is should be `Active`.

<figure><img src="/files/pYiMB6NgkJBE8pIMWDgB" alt=""><figcaption></figcaption></figure>

**View contract information with Explorer**

Go to [testnet Acki Nacki explorer](https://shellnet.ackinacki.org) and search for in search bar.\
Open your account page. You will need it later to see its transactions and messages, that we will produce in the next steps.

<figure><img src="/files/GPUAhwU0l4EjB7bFv1QB" alt=""><figcaption></figcaption></figure>

**Explore contract information with GraphQL**

Go to [GraphQL playground](https://shellnet.ackinacki.org/graphql).

Enter the information in the left pane and click the "Run" button (replace the contract's address with the one you obtained in the previous steps).

```
query {
  accounts(
    filter: {
      id: {
        eq: "<YourAddress>"
      }
    }
  ) {
    acc_type_name
    dapp_id
    balance
    code
    code_hash
    data
  }
}
```

{% hint style="info" %}
The `dapp_id` field will contain the identifier of your decentralized contract system on the Acki Nacki blockchain.
{% endhint %}

You will see something that looks similar following:

<figure><img src="/files/s96DxNL3KRTCCpNrKGrU" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**You can specify any other fields in the result section that are available in GraphQL Schema.**\
Click the icon <img src="/files/YH94kaBwuyoMvnQamWFd" alt="" data-size="line"> in the upper-left corner of the screen to view the API documentation.
{% endhint %}

## **Run a getter**

The `helloWorld` contract features a get-method: `timestamp`. Let's call it and check the result:

```
tvm-cli run <YourAddress> timestamp {} --abi helloWorld.abi.json
```

result:

<figure><img src="/files/b7lQj3N4dFyJ7eevs86J" alt="" width="423"><figcaption></figcaption></figure>

## Call a method on-chain

The helloWorld contract has a `touch` method. Let’s run it on-chain using the `call` command:

```
tvm-cli call <YourAddress> touch {} --abi helloWorld.abi.json --sign helloWorld.keys.json
```

<figure><img src="/files/IW7G2rQhp0ymBSncUyj1" alt=""><figcaption></figcaption></figure>

Call the get-method `timestamp` again to verify that the timestamp has been updated:

<figure><img src="/files/rLfYnjwDX9ZXUGN4VQgI" alt=""><figcaption></figcaption></figure>

## Add another contract to your Dapp ID

{% hint style="warning" %}
To add a contract to the Dapp ID system, it must be deployed via an internal message through the root contract of the Dapp ID, which in our case is `helloworld`.
{% endhint %}

In our case, this can be done using the following function:

```
function deployNewContract(
        TvmCell stateInit,
        uint128 initialBalance,
        TvmCell payload
    )
```

* `stateInit` - the contract code plus data (tvc in base64);
* `initialBalance` - the amount of funds to transfer;
* `payload` - a tree of cells used as the body of the outbound internal message;

Let’s add another contract to our Dapp ID. For this, we’ll use a copy of the `helloWorld` contract and name it `helloUniverse:`

```
cp helloWorld.tvc helloUniverse.tvc
cp helloWorld.abi.json helloUniverse.abi.json
```

Now, let’s calculate the address of the `helloUniverse` contract using the existing key pair.

```
tvm-cli genaddr helloUniverse.tvc --save --setkey helloWorld.keys.json
```

And we get the same address as the `helloWorld` contract.

<figure><img src="/files/jF6mKjnJhDm85fWrKnQZ" alt=""><figcaption></figcaption></figure>

To avoid this, it’s essential to use a different key pair.\
Let’s generate a new seed phrase with a fresh pair of keys:

```
tvm-cli genphrase --dump helloUniverse.keys.json
```

<figure><img src="/files/DULPPQR9bpKYxinsyj9t" alt=""><figcaption></figcaption></figure>

Let’s calculate the address and prepare the TVC file for the new contract:

```
tvm-cli genaddr helloUniverse.tvc --save --setkey helloUniverse.keys.json
```

<figure><img src="/files/ECbqTidvfVlBhgFMocbH" alt=""><figcaption></figcaption></figure>

To deploy a new contract, you need to prepare its `stateInit` and a deployment message body.

To obtain the `stateInit`, execute the following command:

Since the result can be quite large, let’s save this value in a variable: `HW_STATE_INIT`.

```
HW_STATE_INIT=$(base64 -w 0 helloUniverse.tvc)
```

Let’s generate the message body with a constructor call for the internal deployment of the contract from another contract.:

```
tvm-cli body --abi helloUniverse.abi.json constructor '{"value": 10000000000}'
```

<figure><img src="/files/4CqfMXfjw6zHtGPzPVdL" alt=""><figcaption></figcaption></figure>

We’ll need to place the `Message body` field value into the deployment payload.

Now we can call `deployNewContract` function.

In our case, the command will be as follows:

```
tvm-cli call 0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e deployNewContract '{"stateInit":"'$HW_STATE_INIT'", "initialBalance":10000000000, "payload":"te6ccgEBAQEADgAAGHA94s8AAAACVAvkAA=="}' --abi helloWorld.abi.json 
```

This way, the new contract within the DAPP ID will be deployed through an internal message.

Check the contract state:

<figure><img src="/files/m0z5sJibHZGGlSVsOQUk" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
Note that the `helloUniverse` contract shares **the same DAPP ID** as the `helloWorld` contract.
{% endhint %}

## Call a contract inside Dapp ID

To transfer SHELL, within the same DAPP ID, use the function `sendShell`

```
function sendShell(address dest, uint128 value)
```

* `dest` - the target address to receive the transfer;
* `value` - the amount of SHELL tokens to transfer.

To transfer VMSHELL, within the same DAPP ID, use the function `sendVMShell`

```
function sendVMShell(address dest, uint128 amount, bool bounce)
```

* `dest` - the target address to receive the transfer;
* `amount` - the amount of VMSHELL tokens to transfer.
* `bounce` - [bounce flag](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer): (should be `false`);

Let's call the `touch` function in `helloUniverse` through the `helloWorld` contract.\
But first, let's check the value of the `timestamp` variable in the `helloUniverse` contract.

```
tvm-cli run <Address_helloUniverse> timestamp {} --abi helloUniverse.abi.json
```

result:

<figure><img src="/files/OwOHRAoy972zPWuLHpds" alt=""><figcaption></figcaption></figure>

To call the `touch` function in `helloUniverse`, we’ll invoke the `callExtTouch` method in `helloWorld`.

```
function callExtTouch(address addr)
```

* `addr` - is the address of the contract in which the method is called.

In our case, the command will be as follows:

```
tvm-cli call 0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e callExtTouch '{"addr": "0:4d5639cd88ee726492b767db774b5a2fe8573c46fd598a75febb5525dc12f918"}' --abi helloWorld.abi.json --sign helloWorld.keys.json
```

<figure><img src="/files/3kcVWdTgvsXdBxUjuFPz" alt=""><figcaption></figcaption></figure>

Then, let's check if the `timestamp` has changed in the `helloUniverse` contract:

<figure><img src="/files/W2UNMFHuxSaYoec6mgZs" alt=""><figcaption></figcaption></figure>

Output: The timestamp has changed.

{% hint style="info" %}
The fee distribution for message transfers within a single DAPP ID is described in the "[Fees](#fees)" section.
{% endhint %}

## Call a contract from another Dapp ID

Let's deploy the `helloWorld2` contract the same way as `helloWorld`.

The `helloWorld` and `helloWorld2` contracts are deployed with different Dapp IDs.

<div><figure><img src="/files/c9yzZ7j4C01Oz2iCAkBK" alt=""><figcaption><p>helloWorld</p></figcaption></figure> <figure><img src="/files/wtUYu7zW1pW9RNceqe9I" alt=""><figcaption><p>helloWorld2</p></figcaption></figure></div>

Let’s check the current `timestamp` in the `helloWorld2` contract:

```
tvm-cli run <YourAddress> timestamp {} --abi helloWorld2.abi.json
```

result:

<figure><img src="/files/86Mja4F8gxYskHnPzC0j" alt=""><figcaption></figcaption></figure>

To call the `touch` function in `helloWorld2`, we’ll invoke the `callExtTouch` method in `helloWorld`.

```
function callExtTouch(address addr)
```

* `addr` - is the address of the contract in which the method is called.

In our case, the command will be as follows:

```
tvm-cli call 0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e callExtTouch '{"addr": "0:f2fe666ad8126ca78f8190305bdf6436971236c477699b3c34e90c5ed6b0691e"}' --abi helloWorld.abi.json --sign helloWorld.keys.json

```

{% hint style="info" %}
If the message is sent to a different Dapp ID, all VMSHELL tokens (in `msg_value)` are set to zero.
{% endhint %}

<figure><img src="/files/ujbB8IeqV0Y9ytyVjAN1" alt=""><figcaption></figcaption></figure>

Then, let's check if the `timestamp` has changed in the `helloWorld2` contract:

<figure><img src="/files/dA9B3Z1gyuAwzQhTzwcL" alt=""><figcaption></figcaption></figure>

Output: The timestamp has changed.

{% hint style="info" %}
The fee distribution for message transfers between different DAPP IDs is described in the "[Fees](#fees)" section.
{% endhint %}

## Centralized replenishment of contracts within a Dapp ID

In the Acki Nacki network, developers can implement a mechanism that allows contracts, grouped under a single Dapp ID, to replenish their balances directly from the shared balance of the entire Dapp ID. This is achieved using the TVM instruction `gosh.mintshell`, enabling seamless internal allocation of resources across the contracts within a single Dapp.

How it works:

During the block assembly, the Block Keeper (BK) collects information about all calls to the TVM instruction `gosh.mintshell` in the transactions included in the block. For each instruction call, the Dapp ID of the contract is determined, and the presence of a `DappConfig` contract for that Dapp ID is verified. The total amount of tokens specified in the instruction calls is then debited from the balance of the `DappConfig` contract. Correspondingly, the appropriate amount of `VMSHELL` tokens is credited to the balances of the contracts for which this instruction was invoked.

To ensure the system functions correctly and resources are managed automatically, follow these steps:

#### **Step 1: Deploying the DappConfig contract**

The `DappConfig` contract is an informational contract that holds data about the amount of VMSHELL available for a specific Dapp ID. It is deployed **once per Dapp ID**. `DappConfig` contracts do not have an owner, and anyone can fund them.

**Actions to Perform:**

1. To deploy the `DappConfig` contract, you need to know the Dapp ID. You can obtain it as follows:

```
tvm-cli account <CONTRACT_ADDRESS>
```

For example, our HelloWorld contract will have the following Dapp ID:

<figure><img src="/files/usQDVYZ6PoLQPzHBoiye" alt=""><figcaption></figcaption></figure>

2. To deploy a `DappConfig` contract, you need to call the `deployNewConfigCustom` function via an internal message from a contract within the Dapp where you want to deploy the `DappConfig` contract.

   The function call must be performed via a `payload` passed into a function such as `sendTransaction` (similar to how deploying a new contract in your Dapp is described [here](#add-another-contract-to-your-dapp-id)).

   That is, you first need to generate the message body by running the following command:<br>

   ```
   tvm-cli body --abi contracts/0.79.3_compiled/dappconfig/DappConfig.abi.json deployNewConfigCustom '{"authorityAddress": null}'

   ```

   \
   \* abi [DappConfig](https://github.com/ackinacki/ackinacki/blob/main/contracts/0.79.3_compiled/dappconfig/DappConfig.abi.json)\
   \
   As a result, you will get:<br>

   ```
   Input arguments:
     method: deployNewConfigCustom
     params: {"authorityAddress": null}
        abi: contracts/0.79.3_compiled/dappconfig/DappRoot.abi.json
     output: None
   Message body: te6ccgEBAQEABwAACVumOBNA
   ```

   \
   We need to place the **Message body** field value into the payload of the `sendTransaction` function in our main contract (in our case, the HelloWorld contract), and set the recipient to the [DappRoot contract](https://github.com/ackinacki/ackinacki/tree/main/contracts/dappconfig).

   Specify the amount of SHELL tokens that will be converted into VMSHELL during deployment and credited to the DappConfig balance.

{% hint style="info" %}
`DappRoot` is a system contract that manages `DappConfig` contracts, including their deployment and the calculation of the `DappConfig` address for a given Dapp ID.\
The address of the `DappRoot` contract is: `0:9999999999999999999999999999999999999999999999999999999999999999`
{% endhint %}

Example command:

```
tvm-cli call 0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e sendTransaction '{"dest":"0:9999999999999999999999999999999999999999999999999999999999999999", "value":10000000, "bounce":false, "cc": {"2": 100000000000}, "flags": 1, "payload": "te6ccgEBAQEABwAACVumOBNA"}' --abi helloWorld.abi.json.abi.json --sign helloWorld.keys.json

```

{% hint style="info" %}
Upon deployment, the contract's balance is credited with **100 VMSHELL tokens**.
{% endhint %}

3. Use the getConfigAddr method to retrieve the address of the deployed `DappConfig` contract:

```
getConfigAddr(uint256 dapp_id)
```

* `dapp_id` - the indentifier of your Dapp

Example command to get the address of the DappConfig contract:

```
tvm-cli -u shellnet.ackinacki.org -j run 0:9999999999999999999999999999999999999999999999999999999999999999 getConfigAddr '{"dapp_id":"0xcf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e"}' --abi acki-nacki/contracts/0.79.3_compiled/dappconfig/DappRoot.abi.json

```

result:

```
{
"config": "0:45744296d4bb46028e6693f586c6d158f02041e51ed48b62debac71a38bd415d",
"state_timestamp": 1774094007991
}
```

To enable the auto-replenishment system, you need to fund the balance with SHELL tokens.

To fund the balance of the `DappConfig` contract, you can call the `sendTransaction` method in the Multisig contract [as described earlier](#top-up-with-shell).

Example command to transfer 10 SHELL from the balance of the Multisig contract to the balance of the `DappConfig` contract:

```

tvm-cli call 0:90c1fe4ab3a86a112e72a587fa14b89ecb2836da0b4ec465543dc0bb62df1430 sendTransaction '{"dest":"0:45744296d4bb46028e6693f586c6d158f02041e51ed48b62debac71a38bd415d","value": 1000000000,"bounce":false, "cc": {"2":10000000000}, "flags": 1, "payload": ""}' --abi multisig.abi.json --sign multisig.keys.json

```

#### **Step 2: Enabling Automatic Replenishment**

To automate the funding process, add balance check and token minting logic to your DAPP ID contracts.\
Use the TVM instruction `gosh.mintshell` which mints some VMSHELL tokens, allowed by the available credit in the DappConfig contract for this Dapp ID:

```
gosh.mintshell(value)
```

* `value` - amount of nanoVMSHELL to mint<br>

For example, let's use the `getTokens()` function in the HelloWorld contract:

```solidity
function getTokens() private pure {
    if (address(this).balance > 100000000000) {     // 100 VMSHELL
        return; 
    }
    gosh.mintshell(100000000000);                   // 100 VMSHELL
}
```

This function mints 100 VMSHELL tokens automatically if the balance falls below the specified threshold.

Let's try:

Check the balance of the HelloWorld contract:

```
tvm-cli -j account 0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e
```

Result: the balance is 0.465631997 VMSHELL tokens.

<figure><img src="/files/9b7GdbVWNlso7v8PQwcM" alt=""><figcaption></figcaption></figure>

Using the `getDetails()` method, you can view the available balance of the DappConfig contract.

```
tvm-cli -j run 0:020473650f8bf0d3df871aadf28a40315ce6ae6d7fffe63e5e557198e0c68b5d getDetails {} --abi dappConfig/DappConfig.abi.json
```

Result: the balance is 500.

<figure><img src="/files/kyRnyOJ2E1JzDpnoBBFq" alt=""><figcaption></figcaption></figure>

Thus, when using the `touch()` method, the `getTokens()` function will be called. This function will check the balance of the HelloWorld contract, and since it is less than 100 VMSHELL, it will trigger a replenishment:

<figure><img src="/files/oMDkcoOu9UjhbNRSHQdX" alt=""><figcaption></figcaption></figure>

Call the `touch()` function:

```
tvm-cli call 0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e touch {} --abi helloWorld.abi.json
```

and check the contract balance:

```
tvm-cli -j account 0:cf95b9366a9f02b0dcab35ba6b8ff800dc3ea9f7a1f19897f045836175f4663e
```

As a result, we see that the balance has been replenished by 100 VMSHELL and now amounts to 100.460237956 VMSHELL.

<figure><img src="/files/GhYXTet2hrzCn844025P" alt=""><figcaption></figcaption></figure>

And checking the available balance of the DappConfig contract will also show that it has decreased by 100 tokens:

<figure><img src="/files/86YUMifY7dVtnLHVsBdV" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
When calling `getDetails()`, you retrieve the available balance in SHELL tokens.\
In contrast, when checking the account data, the `ecc` field will show the cumulative amount of tokens ever transferred to this balance.\
**This behavior is relevant only for the** `DappConfig` **contract.**
{% endhint %}

<figure><img src="/files/iU9qLXgjBOzfTEEM5xEn" alt="" width="563"><figcaption></figcaption></figure>

## Fees

When transferring messages between contracts under the same Dapp ID, fees are distributed as follows:

* To create an outgoing message, payment is deducted from the sender’s balance.
* For relaying a message, payment is taken either from the sender's balance or deducted from the message balance (`msg.value`). The specific behavior depends on the flags set during transmission, as described [here](https://github.com/gosh-sh/TVM-Solidity-Compiler/blob/master/API.md#addresstransfer).
* Processing an incoming message is paid from the message balance (`msg.value`) and, if `tvm.accept()` is used, from the recipient’s balance.

When transferring messages between contracts under different Dapp IDs, the entire amount of tokens specified in `msg.value` (VMSHELL) is nullified. In this case, the recipient contract must assume responsibility for executing the initiated transaction by calling `tvm.accept()` within the invoked function. Otherwise, the transaction will fail with the error `Not enough funds`.

## Troubleshooting

### Error 621: `The account doesn't have a state` during contract deployment

#### Description

When running the deploy command, you may encounter the following error:

```
Input arguments:
     tvc: UpdateCustodianMultisigWallet.tvc
  params: {"owners_pubkey":["0x7111b817f126522ead42c315ed1d908110bb7caf033fb1c4428537d0dc82cf4b"], "owners_address": [], "reqConfirms":1, "reqConfirmsData": 1, "value":0}
     abi: UpdateCustodianMultisigWallet.abi.json
    keys: UpdateCustodianMultisigWallet.keys.json
  opt_wc: 0
   alias: None
Connecting to:
        Url: shellnet.ackinacki.org
        Endpoints: ["shellnet.ackinacki.org"]

Deploying...
Processing...
Error: {
  "code": 621,
  "message": "The account doesn't have a state",
  "data": {
    "core_version": "2.24.9",
    "node_error": {
      "extensions": {
        "code": "COMPUTE_SKIPPED",
        "message": "The account doesn't have a state",
        "details": {
          "producers": [
            "shellnet-2.testbk.ackinacki.org:8600"
          ],
          "message_hash": "ab499e8388cd69f72bcf985f059c2f4cfe43f9aa4aaf1455dd44656bc388f3ea",
          "exit_code": 0,
          "current_time": "1771864434272",
          "thread_id": "00000000000000000000000000000000000000000000000000000000000000000000",
          "address": "0:ceb8919b1100367905c8e052e22deeca9f5f1c0f39c126a0fad03a78b4a8d32c"
        }
      }
    },
    "ext_message_token": {
      "unsigned": "1771864464272",
      "signature": "f5d3c7ad18d1bdfd9748fc2f5e841f272642a4ab0e5f0c6238794c9c310a592177140e725c4d109eb1ab13aa90404641a4bda7fa202de148bd7bbbe70095b800",
      "issuer": {
        "bm": "d09e10f63d84f8c89b5ad48e0497756bacf0749437ad84210824fb582d23a396"
      }
    }
  }
}
```

#### Cause

This error means that the target account does not have an initialized state on the network.

### ✅ Solution

{% hint style="warning" %}
**Before deploying the contract, you must fund the future contract address with `VMSHELL` tokens.**
{% endhint %}

This can be done by calling the `sendTransaction` method with **flag `16`**.

In this case, you transfer **SHELL** tokens, which are automatically converted into **VMSHELL** tokens and credited to the balance of the account you intend to deploy.

#### Example Command

```bash
tvm-cli call <MSIG_ADDR> sendTransaction \
'{
  "dest":"0:ceb8919b1100367905c8e052e22deeca9f5f1c0f39c126a0fad03a78b4a8d32c",
  "value":1000000000,
  "cc":{"2":5000000000},
  "bounce":false,
  "flags":16,
  "payload":""
}' \
--abi <WALLET_ABI.json> \
--sign <WALLET_KEYS.json>
```

As a result, the account balance will be credited with **5 VMSHELL**\
After the transaction is confirmed, you can safely run the deploy command again.


# Get Test Tokens in Shellnet

This guide explains how to top up an address with test tokens in the \`Shellnet\` network

{% hint style="danger" %}
**For the `Shellnet` network only**
{% endhint %}

{% hint style="warning" %}
**Please update `tvm-cli v3+` and use the new extended address format:**

`<dapp_id>::<account_id>`
{% endhint %}

You can receive test tokens in two ways:\
\* by using the giver \
\* by requesting them from us through our [Telegram channel](https://t.me/tvmlabs)

### Requirements

Before you start, make sure you have:

* [`tvm-cli` installed](https://github.com/tvmlabs/tvm-sdk/releases)
* [`GiverV3` ABI file](https://github.com/ackinacki/ackinacki/blob/main/contracts/giver/GiverV3.abi.json)
* Recipient wallet or contract address

{% hint style="info" %}
Right now, in enabled `DEV mode`, you will see the address of your Multifactor contract
{% endhint %}

`GiverV3` contract artifacts are available in the repository Acki Nacki

{% embed url="<https://github.com/ackinacki/ackinacki>" %}

### Test Tokens

Token amounts in `ecc` are specified in the smallest units.

<table><thead><tr><th width="95.13330078125">Token</th><th width="123.699951171875">`ecc` key</th><th width="110.29998779296875">Decimals</th><th>Example</th></tr></thead><tbody><tr><td><code>NACKL</code></td><td>1</td><td><code>9</code></td><td><code>100 NACKL</code> = <code>100,000,000,000</code></td></tr><tr><td><code>SHELL</code></td><td>2</td><td><code>9</code></td><td><code>100 SHELL</code> = <code>100,000,000,000</code></td></tr><tr><td>ecc<code>USDC</code></td><td>3</td><td><code>6</code></td><td><code>100 eccUSDC</code> = <code>100,000,000</code></td></tr></tbody></table>

{% hint style="warning" %}

* Make sure the recipient address is correct before running the command
* Keep the `value` parameter set to `1000000000`
  {% endhint %}

### Get SHELL

Replace `0:348c....66bf` with the recipient address.

The command below sends `1000 SHELL`.

```bash
tvm-cli -j -u shellnet.ackinacki.org callx \
  --abi acki-nacki/contracts/giver/GiverV3.abi.json \
  --addr 0000000000000000000000000000000000000000000000000000000000000000::1111111111111111111111111111111111111111111111111111111111111111 \
  -m sendCurrency \
  '{"dest":"0:348c....66bf","value":1000000000,"ecc":{"2":1000000000000}}'
```

### Get NACKL

Replace `0:348c....66bf` with the recipient address.

The command below sends `100 NACKL`.

```bash
tvm-cli -j -u shellnet.ackinacki.org callx \
  --abi acki-nacki/contracts/giver/GiverV3.abi.json \
  --addr 0000000000000000000000000000000000000000000000000000000000000000::1111111111111111111111111111111111111111111111111111111111111111 \
  -m sendCurrency \
  '{"dest":"0:348c....66bf","value":1000000000,"ecc":{"1":100000000000}}'
```

### Get eccUSDC

Replace `0:348c....66bf` with the recipient address.

The command below sends `5000 eccUSDC`.

```bash
tvm-cli -j -u shellnet.ackinacki.org callx \
  --abi acki-nacki/contracts/giver/GiverV3.abi.json \
  --addr 0000000000000000000000000000000000000000000000000000000000000000::1111111111111111111111111111111111111111111111111111111111111111 \
  -m sendCurrency \
  '{"dest":"0:348c....66bf","value":1000000000,"ecc":{"3":5000000000}}'
```

### Get multiple tokens

You can request several test tokens in one command by adding multiple keys to `ecc`.

The command below sends `1000 NACKL`, `50000 SHELL`, and `5000 eccUSDC`.

```bash
tvm-cli -j -u shellnet.ackinacki.org callx \
  --abi acki-nacki/contracts/giver/GiverV3.abi.json \
  --addr 0000000000000000000000000000000000000000000000000000000000000000::1111111111111111111111111111111111111111111111111111111111111111 \
  -m sendCurrency \
  '{"dest":"0:348c....66bf","value":1000000000,"ecc":{"1":1000000000000,"2":50000000000000,"3":5000000000}}'
```

### Get VMSHELL to a Precomputed Address

Use this option to send test SHELL tokens to an address where the contract has not yet been deployed.

{% hint style="info" %}
The SHELL tokens will be converted into VMSHELL at the destination address.
{% endhint %}

These tokens will be used to pay for the deployment of that contract.

Replace `0:348c....66bf` with the recipient address.

The command below sends `1000 SHELL`, which will be credited as `1000 VMSHELL`.

```bash
tvm-cli -j -u shellnet.ackinacki.org callx \
  --abi acki-nacki/contracts/giver/GiverV3.abi.json \
  --addr 0000000000000000000000000000000000000000000000000000000000000000::1111111111111111111111111111111111111111111111111111111111111111 \
  -m sendCurrencyWithFlag \
  '{"dest":"0:348c....66bf","value":1000000000,"ecc":{"2":1000000000000},"flag":16}'
```


# Migration to 3.0 SDK and 1.0 GQL API

TVM SDK v3.0 and updated Acki Nacki service APIs introduce **Dapp ID** support in address format. The migration affects SDK calls, `tvm-cli` tool, GraphQL queries, and Block Keeper / Block Manager REST APIs.

## What changed

Account address is now represented by two raw 64-character hex values:

```
<dapp_id>::<account_id>
```

For self-rooted contracts, `dapp_id` equals `account_id`. Legacy `0:<account_id>` values are not enough for Dapp ID-aware routing and must be converted before they are passed to SDK, CLI, GraphQL, or REST APIs.

## SDK changes

SDK consumers must pass Dapp ID  explicitly in message processing parameters.

Key changes:

* `account.get_account` returns account BOC, optional `dapp_id`, and `state_timestamp`.
* `ParamsOfSendMessage` includes `thread_id` and a required `dapp_id`.
* `ParamsOfProcessMessage` includes a required `dapp_id`.
* `ResultOfSendMessage` returns `message_hash`, `block_hash`, `tx_hash`, execution result fields, `thread_id`, producers list, and response time.

Pass `dapp_id` as a raw 64-character hex string without the `0:` prefix.

## CLI changes

Commands that take an address argument require the extended address format:

```
<dapp_id>::<account_id>
```

`call`, `callx`, and proposal commands derive destination `dapp_id` from extended addresses. `deploy` and `deployx` always require `--dst-dapp-id`. Scripts and aliases that still pass `0:<account_id>` must be updated before using SDK/CLI 3.0.

## Detailed SDK migration guide

{% hint style="info" %}
This page is an overview. Use the detailed [MIGRATION-3.0.md](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/MIGRATION-3.0.md) guide for exact API changes, CLI examples, known errors, and the migration checklist.
{% endhint %}

Before upgrading, review the guide and plan updates for SDK calls, CLI scripts, stored addresses, deployment outputs, and language bindings that expose the TVM SDK JSON API. Stored legacy `0:<account>` values must be converted before they are passed to current `tvm-cli` commands. The same applies to hard-coded GraphQL queries and REST URLs: strip the `0:` prefix and supply a separate `dapp_id`.

## GraphQL API changes

Use `blockchain.account` with separate `account_id` and `dapp_id` arguments.

Before:

```graphql
query {
  blockchain {
    account(address: "0:abcdef...") {
      info { boc }
    }
  }
}
```

After:

```graphql
query {
  blockchain {
    account(
      account_id: "abcdef..."
      dapp_id: "cba987..."
    ) {
      info { boc }
    }
  }
}
```

## REST API changes

### `GET /v2/account`

The endpoint now requires `account_id` and `dapp_id` query parameters and rejects `address=0:...`.

Before:

```http
GET /v2/account?address=0:abcdef...
```

After:

```http
GET /v2/account?account_id=<64hex>&dapp_id=<64hex>
```

Validation behavior:

| Condition                     | Response                                                         |
| ----------------------------- | ---------------------------------------------------------------- |
| Missing `account_id`          | `400 account_id parameter required`                              |
| Missing `dapp_id`             | `400 dapp_id parameter required`                                 |
| Prefixed (`0:`) or not 64 hex | `400 Invalid <field>: expected 64 hex characters without prefix` |
| Account not found             | `404`                                                            |

Success response:

```json
{ "boc": "...", "account_id": "<hex>", "dapp_id": "<hex>", "state_timestamp": 1710000000000 }
```

### `POST /v2/messages`

Each external message must include both `account_id` and `dapp_id`:

```json
[
  {
    "id": "...",
    "body": "...",
    "account_id": "<64hex>",
    "dapp_id": "<64hex>",
    "thread_id": "..."
  }
]
```

Requests missing `account_id` or `dapp_id` are rejected with `400`. Response `result` and `error.data` objects also carry `account_id` and `dapp_id`.

## Compatibility window

Support for these migration-related changes must be implemented before the release of the new node version with v0.16.3 release.

Until that release, integrations should support both:

* Legacy nodes with `GraphQL info.version < "1.0.0"`
* Dapp ID-aware nodes with `GraphQL info.version >= "1.0.0"`

Treat nodes reporting `GraphQL info.version >= "1.0.0"` as requiring separate `account_id` and `dapp_id` fields across SDK, GraphQL, and REST flows.


# Developer Portal Overview


# How to deploy a Multisig Wallet

Create a Multisig wallet  with TVM CLI

## Prerequisites <a href="#create-a-wallet" id="create-a-wallet"></a>

* [tvm-cli](https://github.com/tvmlabs/tvm-sdk/releases)

## **Prepare wallet binary and ABI** <a href="#create-a-wallet" id="create-a-wallet"></a>

Create a folder:

```
cd ~
mkdir wallet
cd wallet
```

Download the [UpdateCustodianMultisigWallet.abi.json](https://raw.githubusercontent.com/ackinacki/ackinacki/blob/main/contracts/0.79.3_compiled/updatecustodianmultisigwallet/UpdateCustodianMultisigWallet.abi.json) and [UpdateCustodianMultisigWallet.tvc](https://raw.githubusercontent.com/ackinacki/ackinacki/blob/main/contracts/0.79.3_compiled/updatecustodianmultisigwallet/UpdateCustodianMultisigWallet.tvc) files for your wallet from the `updatecustodianmultisigwallet` [repository](https://github.com/ackinacki/ackinacki/tree/main/contracts/0.79.3_compiled/updatecustodianmultisigwallet) and place them in this folder.

{% hint style="info" %}
The contract code can be downloaded from [here](https://github.com/ackinacki/ackinacki/blob/main/contracts/updatecustodianmultisigwallet/UpdateCustodianMultisigWallet.sol)
{% endhint %}

## Configure CLI tool

In this guide, we will use the test network at [`shellnet.ackinacki.org`](https://shellnet.ackinacki.org).\
We need to specify the blockchain endpoint for deployment:

```
tvm-cli config -g --url shellnet.ackinacki.org
```

## Generate seed phrase, keys and address

In Acki Nacki blockchain, the Multisig wallet address depends on its binary code and initial data, which includes the owner's public key.

You can generate everything with one command:

```

tvm-cli genaddr UpdateCustodianMultisigWallet.tvc --save --genkey UpdateCustodianMultisigWallet.keys.json
```

{% hint style="danger" %}
**Write down your `seed phrase` and store it in a secure location. Never share it with anyone. Avoid storing it in plain text, screenshots, or any other insecure method. If you lose it, you lose access to your assets. Anyone who obtains it will have full access to your assets.**

**Additionally, ensure the file containing the `key pair` is saved in a safe place.**
{% endhint %}

{% hint style="info" %}
After this step, the `.tvc` file will be overwritten with the specified keys.
{% endhint %}

The `Raw address` is the future Multisig wallet address. Keys are saved to `updateCustodianMultisigWallet.keys.`

Be sure to copy your seed phrase if you need it.

<figure><img src="/files/cus3XrvPnvifyPCr8A7l" alt=""><figcaption></figcaption></figure>

## **Request Test tokens** <a href="#request-test-tokens-for-future-use" id="request-test-tokens-for-future-use"></a>

[VMSHELL](https://docs.ackinacki.com/glossary#vmshell) tokens are used to pay network fees and are derived from [SHELL](https://docs.ackinacki.com/glossary#shell) tokens.\
On the Mainnet, SHELL tokens are purchased via a special pool and then converted into VMSHELL tokens.

On the test network, you can request test tokens to be sent to your address. Please contact us on [Telegram](https://t.me/+1tWNH2okaPthMWU0) to receive them.

{% hint style="info" %}
If you plan to test your smart contract systems, you can use the provided Multisig wallet to top up contract balances in order to cover gas fees.
{% endhint %}

## Deploy your Multisig wallet

Once you receive the test tokens, check the state of the pre-deployed contract. It should be **`Uninit`**:

```
tvm-cli account <YourAddress>
```

{% hint style="success" %}
The received **VMSHELL** tokens will be displayed in the `balance` field.\
VMSHELL tokens are transferred and stored in (*in* [*nanotokens*](https://github.com/gosh-sh/TVM-Solidity-Compiler/blob/master/API.md#tvm-units)) units.\
\
The received **SHELL** tokens will be displayed in the `ecc` field under index **2**
{% endhint %}

<figure><img src="/files/5UQ5eJBKoMTgN7pr7Hn3" alt=""><figcaption></figcaption></figure>

Now you are ready to deploy your Multisig wallet using the following command:

```

tvm-cli deploy --abi UpdateCustodianMultisigWallet.abi.json --sign UpdateCustodianMultisigWallet.keys.json UpdateCustodianMultisigWallet.tvc '{"owners_pubkey":[<PubKeyList>], "owners_address": [], "reqConfirms":<ConfirmsNum>, "reqConfirmsData": <NumConfirms>, "value":<NumTokens>}'
```

The arguments for the constructor must be enclosed in curly brackets: `{<constructor arguments>}`

* **`owners_pubkey`** — an array of custodians’ public keys. Each key must include the **`0x` prefix**
* **`owners_address`** — an array of custodian contract addresses.
* **`reqConfirms`** — the number of signatures required to approve a transaction.
* **`reqConfirmsData`** — the number of confirmations required to approve a change of custodians.
* **`value`** — the amount (*in* [*nanotokens*](https://github.com/gosh-sh/TVM-Solidity-Compiler/blob/master/API.md#tvm-units)) of **SHELL** tokens you want to exchange for **VMSHELL**.\
  If the exchange is not required, set the parameter `value` to **0**.

In our example, the command will be as follows:

```

tvm-cli deploy --abi UpdateCustodianMultisigWallet.abi.json --sign UpdateCustodianMultisigWallet.keys.json UpdateCustodianMultisigWallet.tvc '{"owners_pubkey":["0x92658a2dee35923cc628b7f5f09e014eeeb7f492dd4dfd2f65cd304a73d2d2f4"], "owners_address": [], "reqConfirms":1, "reqConfirmsData": 1, "value":10000000000}'
```

<figure><img src="/files/WcHyNBE4vlesBOQe536i" alt=""><figcaption></figcaption></figure>

Check the contract state again. This time, it should be `Active`

{% hint style="info" %}
The contract deployment fee was deducted from the VMSHELL balance.
{% endhint %}

<figure><img src="/files/PyL1uoMfFmIw95iwFMIQ" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
During contract deployment, **10** **SHELL** tokens were converted into **10** **VMSHELL** (values are specified in nanotokens).
{% endhint %}

## Multisig Wallet API

In the examples below:

* `<MSIG_ADDR>` — Multisig Wallet address (e.g. `0:7a55...dd45`)
* ABI file: [`UpdateCustodianMultisigWallet.abi.json`](https://raw.githubusercontent.com/ackinacki/ackinacki/blob/main/contracts/0.79.3_compiled/updatecustodianmultisigwallet/UpdateCustodianMultisigWallet.abi.json)
* Signer keys (one of the custodians): `UpdateCustodianMultisigWallet.keys.json` , generated in the [previous step](#generate-seed-phrase-keys-and-address)

{% hint style="info" %}
The transaction **expiration time** is **1 hour**.
{% endhint %}

{% hint style="warning" %}
`VMSHELL`s attached to the message will be credited to the recipient’s balance minus fees, provided the message is sent between contracts **with the same** DAPP ID.\
If the DAPP IDs **are different**, the `VMSHELL`s will be burned
{% endhint %}

### How to Send Tokens From Multisig Wallet

* **If the required number of confirmations for transactions is 1,**\
  tokens can be sent using the function `sendTransaction`:

```solidity

sendTransaction(
        address dest,
        uint128 value,
        mapping(uint32 => varuint32) cc,
        bool bounce,
        uint8 flags,
        TvmCell payload)
```

**Parameters**

* `dest` - the transfer target address;
* `value` - the amount of funds (VMSHELL) used to pay fees (it must not be `0`);
* `cc` - a mapping of ECC token types to the token amounts to be transferred;
* `bounce` - [bounce flag](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer): (should be `false`);
* `flags`- [send message flags](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer) (should be `1`);
* `payload` - [tree of cells used as the body](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer) of the outbound internal message (should be an empty string).

{% hint style="warning" %}
In this case, the transaction is executed immediately, without creating a request or requiring additional confirmations.
{% endhint %}

Example command:

```solidity
tvm-cli call <MSIG_ADDR> sendTransaction '{
  "dest":"0:2672bb98816f2f9088d027f99681b65e05843b19367fe690cb4b5130d04eccf1",
  "value":1000000000,
  "cc":{"2":5000000000},
  "bounce":false,
  "flags":1,
  "payload":""
}' --abi UpdateCustodianMultisigWallet.abi.json  --sign UpdateCustodianMultisigWallet.keys.json
```

* **If you need to fund an account that has not yet been deployed,**\
  you should use the `sendTransaction` method with **flag 16**.

  \
  In this case, you transfer **SHELL** tokens, which are automatically converted into **VMSHELL** tokens and credited to the balance of the account you intend to deploy.\
  \
  **Example command:**

```solidity
tvm-cli call <MSIG_ADDR> sendTransaction \
'{
  "dest":"0:ceb8.....8d32c",
  "value":1000000000,
  "cc":{"2":5000000000},
  "bounce":false,
  "flags":16,
  "payload":""
}' \
--abi UpdateCustodianMultisigWallet.abi.json  --sign UpdateCustodianMultisigWallet.keys.json
```

As a result, the account balance will be credited with **5 VMSHELL**\
After the transaction is confirmed, you can safely run the deploy command again.<br>

* **If confirmation from multiple custodians is required**,\
  use the function `submitTransaction`:

```solidity
submitTransaction(
        address dest,
        uint128 value,
        mapping(uint32 => varuint32) cc,
        bool bounce,
        uint8 flag,
        TvmCell payload)
```

**Parameters**

* `dest` — the transfer target address;
* `value` — the amount of funds (VMSHELL) used to pay fees (it must not be `0`);
* `cc` — a mapping of ECC token types to the token amounts to be transferred;
* `bounce` — [bounce flag](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer): (should be `false`);
* `flags` — [send message flags](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer) (usually `1`);
* `payload` — [tree of cells used as the body](https://github.com/gosh-sh/TON-Solidity-Compiler/blob/master/API.md#addresstransfer) of the outbound internal message (usually an empty string).

**Return value**

* `transactionId` — identifier of the created multisig transaction.\
  This id is later used in [`confirmTransaction`](#how-to-confirm-an-already-created-transaction).

{% hint style="warning" %}
The transaction will be executed only after the required number of confirmations is collected.
{% endhint %}

Example command:

```bash
tvm-cli call <MSIG_ADDR> submitTransaction '{
  "dest":"0:2672bb98816f2f9088d027f99681b65e05843b19367fe690cb4b5130d04eccf1",
  "value":1000000000,
  "cc":{"2":5000000000},   # 5 SHELL
  "bounce":false,
  "flags":1,
  "payload":""
}' --abi UpdateCustodianMultisigWallet.abi.json --sign UpdateCustodianMultisigWallet.keys.json
```

{% hint style="info" %}
If the required number of confirmations for transactions is `1`, `submitTransaction` behaves like `sendTransaction` and executes immediately.
{% endhint %}

### How to Confirm a Transaction

To do this, use the function `confirmTransaction`

```solidity
confirmTransaction(uint64 transactionId)
```

**Parameters**

* `transactionId` — identifier of the transaction to confirm.\
  You receive it as a result of calling [`submitTransaction`](#how-to-send-tokens-from-multisig-wallet)

{% hint style="info" %}
If the transaction has already expired, it will be deleted.
{% endhint %}

Example command:

```bash
tvm-cli call <MSIG_ADDR> confirmTransaction '{"transactionId":123456789}' --abi UpdateCustodianMultisigWallet.abi.json  --sign UpdateCustodianMultisigWallet.keys.json
​
```

### How to create a request to update Multisig data

To change the list of custodians and the required number of confirmations, use the function `submitDataUpdate`

```solidity
submitDataUpdate(
        uint256[] owners_pubkey,
        address[] owners_address, 
        uint8 reqConfirms,
        uint8 reqConfirmsData)
```

**Parameters**

* `owners_pubkey` — array of custodian public keys;
* `owners_address` — array of custodian addresses;
* `reqConfirms` — required confirmations for regular transactions;
* `reqConfirmsData` — required confirmations for data update operations;

**Return value**

* `dataUpdateId`— identifier of the created multisig transaction.\
  This id is later used in [confirmDataUpdate](#how-to-create-a-request-to-update-multisig-data)

Example command:

```bash
tvm-cli call <MSIG_ADDR> submitDataUpdate '{
  "owners_pubkey":[
    "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
  ],
  "owners_address":[
    "0:2672bb98816f2f9088d027f99681b65e05843b19367fe690cb4b5130d04eccf1"
  ],
  "reqConfirms":2,
  "reqConfirmsData":2
}' --abi UpdateCustodianMultisigWallet.abi.json  --sign UpdateCustodianMultisigWallet.keys.json
```

### How to confirm a request to update the Multisig data

To do this, use the function confirmDataUpdate

```solidity
confirmDataUpdate(uint64 dataUpdateId)
```

**Parameters**

* `dataUpdateId` — identifier of the data update request.\
  You receive it as a result of calling [`submitDataUpdate`](#how-to-create-a-request-to-update-multisig-data)

{% hint style="info" %}
If the request is expired, it will be removed
{% endhint %}

Example command:

```bash
tvm-cli call <MSIG_ADDR> confirmDataUpdate '{"dataUpdateId":987654321}' --abi UpdateCustodianMultisigWallet.abi.json  --sign UpdateCustodianMultisigWallet.keys.json

```


# Add Acki Nacki to your backend

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


# Smart Contract Interfaces


# Nullifier

(Work in progress) Nullifier Contract Interface Documentation

{% file src="/files/wbKUbXeHLONHPWuCAe27" %}

## Overview

`Nullifier` is a contract that stores a **static nullifier hash** and provides a method to retrieve the contract version.

During deployment, the constructor verifies that the deployer is the `RootPN` contract and transfers a small amount of funds to a specified address.

## View Function

### **`getVersion`**

Returns the contract version identifier.

```solidity
function getVersion() external pure returns (string, string)
```

**Returns:**

* semantic version string
* Contract name: `"Nullifier"`


# RootPN

(Work in progress) RootPrivateNote Contract Interface Documentation

{% file src="/files/E855iZ6e3ArXQ8mowbhS" %}

## Overview

`RootPN` is the system root contract responsible for deploying and managing `PrivateNote` contracts.\
It also stores and manages the canonical contract code for related system components, including Pari Mutuel Pool, Oracles, and Nullifiers.

The contract acts as a trusted entry point for:

* zero-knowledge–verified deposits
* deterministic deployment of `PrivateNote`
* system-wide code upgrades

***

## Events

### vaucherGenerated

Emitted when a new voucher is generated.

```solidity
event vaucherGenerated(uint256 sk_u_commit, uint vaucher_nominal, uint32 token_type);
```

* `sk_u_commit` — Commitment of the user secret key
* `vaucher_nominal` — Voucher nominal value
* `token_type` — Token type associated with the voucher

### PrivateNoteDeployed

Emitted when a new `PrivateNote` contract is deployed.

```solidity
event PrivateNoteDeployed(
    uint256 depositIdentifierHash,
    address noteAddress,
    uint128 initialBalance
);
```

* `depositIdentifierHash` — Deposit identifier hash
* `noteAddress` — Deployed `PrivateNote` address
* `initialBalance` — Initial token balance

***

### NullifierDeployed

Emitted when a `Nullifier` contract is deployed.

```solidity
event NullifierDeployed(
    address nullifierAddress,
    uint64 value
)
```

* `nullifierAddress` — Address associated with the deployment
* `value` — Value linked to the nullifier

**Meaning:**

* A nullifier was created to prevent double-spending
* Funds were transferred to the associated `PrivateNote`

***

## Public & External Interface

### **`sendEccShellToPrivateNote`**

Verifies a zero-knowledge proof and deploys a `Nullifier` contract associated with a deterministic `PrivateNote` address.

```solidity
function sendEccShellToPrivateNote(
    bytes proof,
    uint256 nullifier_hash,
    uint256 deposit_identifier_hash,
    uint64 value
) public;
```

**Parameters:**

* `proof` — zero-knowledge proof validating the deposit
* `nullifier_hash` — unique nullifier preventing double spend
* `deposit_identifier_hash` — deposit identifier hash
* `value` — amount of ECC Shell tokens to mint and transfer

**Behavior:**

* Verifies the proof using `zkhalo2verify`
* Mints ECC Shell tokens
* Deploys a `Nullifier` contract
* Forwards minted tokens to the corresponding `PrivateNote`
* Emits `NullifierDeployed`

***

### **`deployPrivateNote`**

Deploys a new `PrivateNote` contract after ZK verification.

```solidity
function deployPrivateNote(
    bytes zkproof,
    uint256 deposit_identifier_hash,
    uint256 ethemeral_pubkey,
    uint64 value,
    uint32 token_type
) public;
```

**Parameters:**

* `zkproof` — zero-knowledge proof of deposit validity
* `deposit_identifier_hash` — unique deposit identifier
* `ethemeral_pubkey` — public key for the note
* `value` — initial token balance
* `token_type` — token type identifier

**Behavior:**

* Ensures the root contract has sufficient native balance
* Builds ZK public inputs from:
  * fixed zero padding
  * `value` (encoded into 8 bytes)
  * more zero padding
  * `token_type` (encoded into 8 bytes)
  * `deposit_identifier_hash` (encoded into 32 bytes)
* Verifies the proof using `gosh.zkhalo2verify(pub_inputs, zkproof)`
* Deploys the `PrivateNote` contract deterministically from `deposit_identifier_hash`
* Emits `PrivateNoteDeployed`

***

### **`privateNoteDeployed`**

Records the deployment of a `PrivateNote`.

```solidity
function privateNoteDeployed(
    uint256 deposit_identifier_hash,
    uint32 token_type,
    uint128 deployed_value
) public;
```

**Access Control:**

* Callable only by the corresponding `PrivateNote` contract

**Behavior:**

* Updates internal accounting of deployed values by token type

***

## View Functions

### **`getPrivateNoteCode`**

Returns the salted `PrivateNote` contract code.

```solidity
function getPrivateNoteCode()
    external
    view
    returns (TvmCell privateNoteCode, uint256 privateNoteHash);
```

**Returns:**

* `privateNoteCode` — salted code cell
* `privateNoteHash` — hash of the salted code

***

### **`getPrivateNoteAddress`**

Returns the deterministic address of a `PrivateNote` contract for a given deposit identifier hash.

```solidity
function getPrivateNoteAddress(uint256 deposit_identifier_hash)
external
view
returns(address privateNoteAddress);
```

**Parameters:**

* `deposit_identifier_hash` — unique deposit identifier hash used to derive the PN address

**Returns:**

* `privateNoteAddress` — deterministic `PrivateNote` address for this deposit identifier

**Notes:**

* The address is computed deterministically and can be obtained even if the `PrivateNote` is not deployed yet.
* Intended for off-chain tooling, indexers, and integrations.

### `getPMPAddress`

Returns the deterministic address of a `PMP` contract for the given event, token type, and oracle name set.

```solidity
function getPMPAddress(
    uint256 event_id,
    string[] names,
    uint32 token_type
) external view
returns(address pmpAddress);
```

**Parameters:**

* `event_id` — event identifier used by the PMP (e.g., hash of the pool name)
* `names` — list of oracle names participating in the pool; used to build the oracle list hash
* `token_type` — token type used by the PMP

**Returns:**

* `pmpAddress` — deterministic PMP address computed from the provided inputs

**Notes:**

* The oracle list hash is computed from the set of oracle name hashes.
* The returned address matches the address used when deploying PMP from `PrivateNote`.

### **`getDetails`**

Returns core RootPN state information.

```solidity
function getDetails()
    external
    view
    returns (
        uint256 pmpCodeHash,
        uint256 privateNoteCodeHash,
        uint256 ownerPubkey,
        uint128 balance
    );
```

**Returns:**

* hash of PMP code
* hash of PrivateNote code
* root owner public key
* current contract balance

***

### **`getVersion()`**

Returns version information for the `RootPN` contract.

```solidity
function getVersion() external pure returns (string, string);
```

**Returns:**

* semantic version string
* contract identifier: `"RootPN"`


# PrivateNote

(Work in progress) PrivateNote Contract Interface Documentation

{% file src="/files/a2uvdQvn7pPYSJz9UN06" %}

## Overview

**PrivateNote** is a non-custodial wallet contract that stores balances, manages stakes, and interacts with **Pari Mutuel Pool (PMP)** contracts (deployment, staking, cancellation, claiming).\
It also supports coupons and withdrawals via `RootPN` contract — all while preserving privacy guarantees.<br>

Each `PrivateNote`:

* **Owner-authorized** actions are controlled by an **ephemeral public key** (`_ethemeral_pubkey`).
* The contract uses a **busy state** (`_busy`) to prevent concurrent PMP interactions.
* Stakes are processed in **two phases**: *candidate* → confirmed/reverted via PMP callbacks.
* Some operations require **`debt == 0`** and **no active stakes**.

***

## Events

### OwnerChanged

Emitted when the owner public key is updated.

```solidity
event OwnerChanged(uint256 oldPubkey, uint256 newPubkey);
```

* `oldPubkey` - Previous public key
* `newPubkey` - New public key

***

### StakeConfirmed

Emitted after a stake is successfully accepted by a PMP.

```solidity
event StakeConfirmed(
    address stakeController,
    uint32 outcome,
    uint128 amount,
    uint8 bet_type
);
```

* `stakeController` - Address of the PMP contract that accepted the stake
* `outcome` - Outcome identifier the stake was placed on
* `amount` - Amount of tokens added to the stake
* `bet_type` — bet type
  * `0` — clean bet (from balance)
  * `1` — debt bet
  * `2` — coupon bet

***

### StakeCancelled

Emitted after a stake is cancelled and refunded.

```solidity
event StakeCancelled(address stakeController, uint128 value);
```

* `stakeController` - Address of the PMP contract that cancelled the stake
* `amount` - Amount of tokens returned

***

### FullSetStakeConfirmed

Emitted when a **full-set stake** is confirmed by PMP

```solidity
event FullSetStakeConfirmed(address stakeController, uint128[] amount);
```

* `stakeController` — PMP address
* `amount` — Confirmed stake amounts per outcome

***

### FullSetStakeCancelled

Emitted when a full-set stake is cancelled and funds returned

```solidity
event FullSetStakeCancelled(address stakeController, uint128 value);
```

* `stakeController` — PMP address
* `value` — Total returned token value to balance

***

### ClaimAccepted

Emitted when a claim is resolved and payout is credited.

```solidity
event ClaimAccepted(address stakeController, optional(uint32) outcome, uint128 payout);
```

* `stakeController` - Address of the PMP contract
* `outcome` - Final resolved outcome. Empty if the event is not yet resolved
* `payout` - Amount of tokens paid to the wallet

***

### PMPDeployed

Emitted when a new PMP contract is deployed.

```solidity
event PMPDeployed(
    uint256 event_id,
    uint32 token_type,
    address pmpAddress,
    address[] oracleEventLists,
    uint128[] oracleFee
);
```

* `event_id` - Identifier of the PMP event
* `token_type` - Token type used for staking
* `pmpAddress` - Address of the deployed PMP contract
* `oracleEventLists` - Oracle event list contract addresses
* `oracleFee` - Oracle fee values corresponding to each oracle

***

## Public & External Interface

### **`changeOwner`**

Changes the (ephemeral) public key controlling the wallet.

```solidity
function changeOwner(uint256 new_pubkey) external;
```

**Parameters:**

* `new_pubkey`— Public key of the new owner

**Access Control:**

* Must be signed by the current public key

**Effects:**

* Updates owner key
* Emits `OwnerChanged`

***

### **`deployPMP`**

Deploys a new PMP contract associated with this wallet

```solidity
function deployPMP(
    uint256 event_id,
    uint128[] oracleFee,
    uint32 token_type,
    string[] names,
    uint128[] index
) public;
```

**Parameters:**

* `event_id` — Identifier of the PMP event
* `oracleFee` — Array of additional fees (in shell tokens) for each oracle.\
  \&#xNAN;*Must match the length of `names` and `index`.*
* `token_type` — Token type used by the PMP contract
* `names` — Array of oracle names used to compute oracle addresses.
* `index` — Array of oracle indexes used to compute OracleEventList addresses.

**Deployment flow:**

1\. Validate input array lengths.\
2\. Compute oracle addresses from `names`.\
3\. Compute `OracleEventList` addresses using oracle code and indexes.\
4\. Aggregate oracle fees and include network fee.\
5\. Build PMP StateInit and compute deterministic PMP address.\
6\. Emit `PMPDeployed` event.\
7\. Deploy PMP contract with required currencies.

***

### **`setStake`**

Places a single-outcome stake on a PMP

```solidity
function setStake(
    uint256 event_id,
    uint256 oracle_list_hash,
    uint32 token_type,
    uint32 outcome,
    uint128 amount,
    bool use_coupon
) public;
```

**Parameters:**

* `event_id` - PMP event identifier
* `oracle_list_hash` - Hash of the oracle list configuration associated with the `PMP` event.\
  Must match the oracle list used when the `PMP` contract was deployed.
* `token_type` - Token type used for staking.\
  Must correspond to a token balance available in the wallet.
* `outcome` - Identifier of the outcome being staked on.\
  The meaning of the outcome is defined by the `PMP` contract logic.
* `amount` - Amount of tokens to stake.\
  Must be greater than zero and less than or equal to the available balance for the specified token type.
* `use_coupon` - Whether to use coupon for this stake\
  If true, amount will be taken from available coupons instead of balance

**Requirements**

* `amount > 0`
* If `use_coupon == true` → sufficient coupons
* Else → sufficient token balance
* Wallet is **not busy**

**Effects**

* Writes candidate stake
* Deducts balance or coupons
* Sets `_busy` and `_lastHash`
* Calls `PMP.acceptStake(...)`

***

### `setFullSetStake`

Places a full-set stake (amount per outcome)

```solidity
function setFullSetStake(
        uint256 event_id,
        uint256 oracle_list_hash,
        uint32 token_type,
        uint128[] amount
    ) public;
```

**Parameters:**

* `event_id` - PMP event identifier
* `oracle_list_hash` - Hash of the oracle list configuration associated with the `PMP` event.\
  Must match the oracle list used when the `PMP` contract was deployed
* `token_type` - Token type used for staking.\
  Must correspond to a token balance available in the wallet
* `amount` - Array of stake amounts per outcome

**Requirements**

* Wallet is **not busy**
* `amount.length > 0`
* `debt == 0`
* Sufficient balance
* If stake exists → lengths must match
* Owner authorization

**Effects**

* Sets `candidate_amount = sum(amount)`
* Deducts balance
* Sets `_busy` and `_lastHash`
* Calls `PMP.acceptFullSetStake(...)`

***

### **`cancelStake`**

Cancels an existing stake in `PMP`.

```solidity
function cancelStake(
    uint256 event_id,
    uint256 oracle_list_hash,
    uint32 token_type,
) public;
```

**Parameters**

* `event_id` — Identifier of the PMP event
* `oracle_list_hash` - Hash of the oracle list configuration associated with the `PMP` event.\
  Must match the oracle list hash of the existing stake.
* `token_type` - Token type used for the stake being cancelled.\
  Must correspond to the token type of the existing stake entry.

**Requirements**

* Wallet is **not busy**
* Stake record exists
* Owner authorization

**Flow**

1. Computes stake hash and PMP address
2. Sets `_busy` and `_lastHash`
3. Calls `PMP.cancelStake(...)`

***

### **`deleteStake`**

Deletes a local stake record (does not call PMP)

```solidity
function deleteStake(
    uint256 event_id,
    uint256 oracle_list_hash,
    uint32 token_type,
) public;
```

**Parameters:**

* `event_id` - PMP event identifier
* `oracle_list_hash` - Hash of the oracle list configuration associated with the stake.\
  Must match the oracle list hash used when the stake entry was created.
* `token_type` - Token type of the stake being deleted.\
  Used to identify the correct local stake record.

**Requirements**

* Wallet is **not busy**
* Owner authorization

**Effects**

* Removes the local stake record

***

### **`claim`**

Claims winnings from a resolved `PMP`.

```solidity
function claim(
    uint256 event_id,
    uint256 oracle_list_hash,
    uint32 token_type,
) public;
```

**Parameters**

* `event_id` - PMP event identifier.\
  Used to derive the event identifier and the address of the target `PMP` contract.
* `oracle_list_hash` - Hash of the oracle list configuration associated with the `PMP` event.\
  Must match the oracle list hash of the existing stake.
* `token_type` - Token type used for the stake.\
  Determines which internal balance will receive the payout.

**Requirements**

* Wallet is **not busy**
* No pending candidate amount
* Owner authorization

**Effects**

* Sets `_busy` and `_lastHash`
* Calls `PMP.claim(...)`

***

### `generateCoupon`

Generates a free coupon for a specified token type.

The function allows the wallet owner to receive a one-time free coupon.\
The coupon value depends on the provided `token_type` and is internally determined by the contract.

Coupons can later be used to place stakes instead of using wallet balance.

```solidity
function generateCoupon(uint32 token_type) public;
```

**Parameters**

* `token_type` - Token type for which the coupon should be generated

**Requirements**

* `debt == 0`
* No active stakes
* All balances are zero
* No existing coupon

***

### `withdrawFullSet`

Withdraws or cancels part of a full-set stake.

```solidity
function withdrawFullSet(
        uint256 event_id,
        uint256 oracle_list_hash,
        uint32 token_type,
        uint128[] amount
    ) public
```

**Parameters**

* `event_id` - PMP event ID
* `oracle_list_hash` - Hash of Oracles
* `token_type` - Token type
* `amount` - Array of amounts per outcome to withdraw

**Requirements**

* Wallet is **not busy**
* Debt must be zero.
* Stake record must exist
* Array length must match existing stake

**Effects**

* Sets `_busy` and `_lastHash`
* Calls `PMP.withdrawFullSet(...)`

### **`withdrawTokens`**

Withdraws tokens from the wallet via the `RootPN`.

```solidity
function withdrawTokens(
    uint8 flags,
    address dest_wallet_addr,
    uint32 token_type
) public;
```

**Parameters**

* `flags` - Transfer flags passed to the `RootPN` contract.\
  Control message delivery behavior during the token transfer.
* `dest_wallet_addr` - Destination wallet address that will receive the withdrawn tokens.
* `token_type` - Type of token to withdraw.\
  All available balance for this token type will be withdrawn.

**Requirements**

* No active stakes
* `debt == 0`
* Owner authorization

**Behavior:**

* Transfers full balance of the given token type
* Resets local balance to zero

***

## View Functions

### **`getPMPCode`**

Returns salted PMP code and its hash.

```solidity
function getPMPCode() external view returns(TvmCell pmpCode, uint256 pmpCodeHash)
```

***

### **`getDetails`**

Returns current wallet state:

```solidity
function getDetails() external view returns (
        uint256 depositIdentifierHash,
        uint256 etherealPubkey,
        mapping(uint32 => uint128) balance,
        uint256 pmpCodeHash,
        uint256 privateNoteCodeHash,
        optional(address) busyAddress
    )
```

**Returns:**

* `depositIdentifierHash` - deposit identifier hash
* `etherealPubkey` - public key
* `balance` - token balances
* `pmpCodeHash` - `PMP` code hash
* `privateNoteCodeHash` - `PrivateNote` code hash
* `busyAddress` - busy PMP address (if any)

***

### **`getVersion`**

Returns version and contract identifier.

```solidity
function getVersion() external pure returns (string, string)
```

**Returns:**

* semantic version string
* Contract name: `"PrivetNote"`


# RootOracle

(Work in progress) RootOracle Contract Interface Documentation

{% file src="/files/0ahzKOBUAgYq2Rt4Pb5B" %}

## Overview

**RootOracle** is the system root contract responsible for deploying and managing Oracle contracts.\
It also supports contract code upgrades and emits events related to Oracle deployment.

***

## Events

### OracleDeployed

Emitted when a new Oracle contract is successfully deployed.

```solidity
event OracleDeployed(address oracle, uint256 pubkey, string name);
```

* `oracle` — address of the deployed Oracle contract
* `pubkey` — public key associated with the Oracle
* `name` — name of the Oracle

***

## Public & External Interface

### **`deployOracle`**

Deploys a new Oracle contract.

```solidity
function deployOracle(uint256 oraclePubkey, string oracleName) public view accept;
```

**Parameters:**

* `oraclePubkey` — public key of the Oracle
* `oracleName` — human-readable name of the Oracle

**Behavior:**

* Ensures the root contract has the minimum required native balance
* Builds `stateInit` for the Oracle using `DexLib.buildOracleStateInit`
* Deploys a new `Oracle` contract with:
  * `value: 60 vmshell`
  * `flag: 1`
* Passes the following arguments to the Oracle constructor:
  * `oraclePubkey`
  * `_oracleEventListCode`
  * `_PrivateNoteCode`
  * `_pmpCode`
* Emits an `OracleDeployed` event to an external address

***

## View Functions

### **`getOracleAddress`**

Returns the deterministic address of an `Oracle` contract by its name.

```solidity
function getOracleAddress(string name) external view returns(address oracleAddress)
```

**Parameters:**

* `name` — unique Oracle name used during deployment

**Returns:**

* `oracleAddress` — deterministic address of the Oracle contract associated with the given name

### **`getVersion`**

Returns the contract version identifier.

```solidity
function getVersion() external pure returns (string, string)
```

**Returns:**

* semantic version string
* Contract name: `"RootOracle"`


# Oracle

(Work in progress) Oracle Contract Interface Documentation

{% file src="/files/cu9jncmhiQkUHE31qqMn" %}

## Overview

**Oracle** is a core contract responsible for managing Oracle events and deploying `OracleEventList` contracts.\
It provides authorization via an oracle public key, supports fee withdrawal, event list deployment, and helper utilities for proposal data encoding.

***

## Events

### OracleEventListDeployed

Emitted when a new `OracleEventList` contract is deployed.

```solidity
event OracleEventListDeployed(address eventListAddress, uint128 index);
```

* `eventListAddress` — address of the deployed OracleEventList
* `index` — index identifier of the event list

***

### EventPublished

Emitted when an event is published by the Oracle.

```solidity
event EventPublished(uint256 event_id, string event_name);
```

* `event_id` — unique identifier of the event
* `event_name` — human-readable event name

***

## Public & External Interface

### **`deployEventList`**

Deploys a new `OracleEventList` with a specified index.

```solidity
function deployEventList(uint128 index)
    public;
```

**Access:** oracle owner only\
**Modifiers:** `onlyOwnerPubkey`, `accept`

**Parameters:**

* `index` — index identifier of the new OracleEventList

**Behavior:**

* Ensures the contract has sufficient native balance
* Deploys a new `OracleEventList` for the given index
* Emits `OracleEventListDeployed` with the deployed address and index

***

### **`withdrawFees`**

Withdraws accumulated fees to a specified address.

```solidity
function withdrawFees(address to, uint128 amount)
    public;
```

**Access:** oracle owner only\
**Modifiers:** `onlyOwnerPubkey`, `accept`

**Parameters:**

* `to` — Recipient address.
* `amount` — Amount of fees to withdraw.

**Behavior:**

* Transfers the specified amount in shell currency to the recipient
* Uses a minimal attached value for the transfer

***

### **`getCellForProposalSetStakeDeadline`**

Encodes staking and result submission deadlines into a `TvmCell`.

```solidity
function getCellForProposalSetStakeDeadline(
    uint64 stakeStart,
    uint64 stakeEnd,
    uint64 resultStart,
    uint64 resultEnd
) public pure returns (TvmCell);
```

**Parameters:**

* `stakeStart` — staking period start timestamp
* `stakeEnd` — staking period end timestamp
* `resultStart` — result submission start timestamp
* `resultEnd` — result submission end timestamp

**Returns:**

* Encoded `TvmCell` containing all timestamps

***

### **`getCellForProposalSetResolve`**

Encodes event resolution data into a `TvmCell`.

```solidity
function getCellForProposalSetResolve(uint32 outcomeId)
    public
    pure
    returns (TvmCell);
```

**Parameters:**

* `outcomeId` — identifier of the winning outcome

**Returns:**

* Encoded `TvmCell` containing the outcome ID

***

### **`getEventListAddress`**

Returns the address of an `OracleEventList` for a given index.

```solidity
function getEventListAddress(uint128 index)
    external
    view
    returns (address);
```

**Parameters:**

* `index` — index of the OracleEventList (currently index `0` is supported)

**Returns:**

* Address of the corresponding OracleEventList contract

***

### **`getVersion`**

Returns the contract version information.

```solidity
function getVersion() external pure returns (string, string);
```

**Returns:**

* Semantic version string (e.g. `"1.0.0"`)
* Contract identifier string: `"Oracle"`


# OracleEventList

(Work in progress) OracleEventList Contract Interface Documentation

{% file src="/files/DxZeXyV0xmo6BGcJ87MO" %}

## Overview

**OracleEventList** is a contract that manages a list of events an Oracle is willing to service.\
It allows the Oracle to publish events, confirm or cancel participation via **Pari Mutuel Pool (PMP)** contracts, and manage event lifecycle state.

Each `OracleEventList` is uniquely identified by:

* the Oracle address
* a static index

***

## Events

### EventAdded

Emitted when a new event is added to the OracleEventList.

```solidity
event EventAdded(
    uint256 event_id,
    string event_name,
    uint128 oracle_fee,
    uint64 deadline
);
```

* `event_id` — unique identifier (hash) of the event
* `event_name` — human-readable name of the event
* `oracle_fee` — fee required by the Oracle
* `deadline` — timestamp until which the Oracle is willing to service the event

***

### EventConfirmed

Emitted when an Oracle confirms participation in an event via a `PMP` contract.

```solidity
event EventConfirmed(uint256 event_id, address pmpAddress);
```

* `event_id` — identifier of the confirmed event
* `pmpAddress` — address of the `PMP` contract that initiated confirmation

***

## Public & External Interface

### **`addEvent`**

Adds a new event that the Oracle is willing to service.

```solidity
function addEvent(
    string event_name,
    uint128 oracle_fee,
    uint64 deadline,
    string describe,
    mapping(uint32 => string) outcomeNames,
    optional(uint256) trustAddr
)
    public
    onlyOwnerPubkey(_oracle_pubkey)
    accept;
```

**Access:** oracle owner only\
**Modifiers:** `onlyOwnerPubkey`, `accept`

**Parameters:**

* `event_name` — human-readable event name
* `oracle_fee` — Oracle fee for servicing the event
* `deadline` — timestamp until which the event is valid
* `describe` — detailed event description
* `outcomeNames` — mapping of outcome IDs to outcome names
* `trustAddr` — optional trusted address for the event

**Behavior:**

* Validates that the deadline is in the future
* Ensures sufficient native balance
* Requires at least 2 and fewer than 20 outcomes
* Computes a deterministic `event_id` from event parameters
* Stores event information in contract storage
* Emits `EventAdded` to an external address

***

### **`confirmEvent`**

Confirms Oracle participation in an event.

```solidity
function confirmEvent(
    uint256 event_id,
    uint256 oracle_list_hash,
    uint32 token_type
)
    public
    senderIs(
        DexLib.computePMPAddress(
            _PrivateNoteCode,
            _pmpCode,
            event_id,
            oracle_list_hash,
            token_type
        )
    )
    accept;
```

**Access:** PMP contract only\
**Modifiers:** `senderIs`, `accept`

**Parameters:**

* `event_id` — identifier of the event
* `oracle_list_hash` — hash of the oracle list
* `token_type` — token type used by the PMP

**Behavior:**

* Ensures sufficient native balance
* Transfers received fees to the Oracle owner
* Rejects the event if it does not exist
* Rejects the event if:
  * the deadline has passed
  * the paid fee is lower than the Oracle fee
* Approves the event via the PMP contract if all conditions are met
* Emits `EventConfirmed` upon successful confirmation

***

### **`deleteEvent`**

Deletes an event from the OracleEventList.

```solidity
function deleteEvent(uint256 event_id)
    public
    onlyOwnerPubkey(_oracle_pubkey)
    accept;
```

**Access:** oracle owner only\
**Modifiers:** `onlyOwnerPubkey`, `accept`

**Behavior:**

* Ensures sufficient native balance
* Deletes the event if:
  * no active confirmations exist, or
  * the event deadline has passed

***

### **`getVersion()`**

Returns the contract version information.

```solidity
function getVersion() external pure returns (string, string);
```

**Returns:**

* Semantic version string (e.g. `"1.0.0"`)
* Contract identifier string: `"OracleEventList"`


# PARI MUTUEL POOL (PMP)

(Work in progress) PMP Contract Interface Documentation

{% file src="/files/37whHckTHWwNw6XFRgCn" %}

## Overview

**Pari Mutuel Pool** is a decentralized contract that aggregates user stakes on discrete outcomes of an event.\
A PMP **does not charge protocol fees**, but **requires approval from one or more oracles** before becoming active.

Each PMP is:

* Deployed by a **PrivateNote**
* Bound to a specific **event** and **oracle list**
* Governed by **oracle proposals** (multi-oracle voting)

***

## Contract Metadata

* **Contract name:** `PMP`
* **Role:** Pari Mutuel Pool
* **Deployed by:** `PrivateNote`
* **Authorization model:**
  * Users: `PrivateNote`
  * Oracles: oracle public keys
* **Lifecycle:**\
  `Deploy → Oracle Approval → Configuration → Staking → Resolution → Claims`

***

## Key Concepts

* **Outcomes** — Discrete result intervals (minimum 2)
* **Staking window** — Time interval for accepting stakes
* **Result window** — Time interval for resolving outcome
* **Oracle approval** — Required before activation
* **Oracle governance** — Proposals and voting for configuration & resolution

***

### Outcomes

* The event has `_numOutcomes` possible outcomes.
* Outcome names are stored in `mapping(uint32 => string) _outcomeNames`.
* Stakes are tracked per outcome and per bet type.

### Bet Types

`bet_type`:

* `0` — clean bet
* `1` — debt bet
* `2` — coupon bet

### **Staking window**

Oracles set:

* `_stakeStart` / `_stakeEnd` — stake acceptance window
* `_resultStart` / `_resultEnd` — result/resolution window

## Events

### `StakeAccepted`

Emitted when a stake is accepted and accounted into the pool.

```solidity
event StakeAccepted(address indexed note, uint32 outcomeId, uint128 amount, uint8 bet_type);
```

* `note` (`address`) — PrivateNote address (wallet) that placed the stake.
* `outcomeId` (`uint32`) — Outcome identifier the stake is placed on.
* `amount` (`uint128`) — Stake amount added to the pool.
* `bet_type` (`uint8`) — 0 - clean bet, 1 - debt bet, 2 - coupon bet

***

### `ApprovedByOracle`

Emitted when all oracle event lists approve the PMP.

```solidity
event ApprovedByOracle(address oracleEventList, uint256 oraclePubkey);
```

* `oracleEventList`: the oracle event list contract address that sent the approval
* `oraclePubkey`: the oracle public key used as an oracle identifier

***

### `Resolved`

Emitted when the event outcome is resolved.

```solidity
event Resolved(uint32 outcomeId);
```

* `outcomeId`: the resolved outcome identifier

***

### `ClaimProcessed`

Emitted when a claim is processed.

If the event is not resolved or the user did not win, `payout` will be `0` and `win` will be `false`.

```solidity
event ClaimProcessed(
    address note,
    uint128 payout,
    bool win
);
```

* `note` — `PrivateNote` address (wallet) that claimed.
* `payout` — Calculated payout amount (0 if no payout).
* `win` — True if the claim is winning and payout > 0.

***

### `NetworkFeeBurned`

Emitted when network fee was burned.

The shown code does not currently emit this event; it is reserved for future accounting.

```solidity
event NetworkFeeBurned(uint64 amount);
```

* `amount` — Burned fee amount in native units.

***

### `TimingsSet`

Emitted when staking and result windows are configured and the pool is marked approved.

```solidity
event TimingsSet(uint64 stakeStart, uint64 stakeEnd, uint64 resultStart, uint64 resultEnd);
```

* `stakeStart`: staking start timestamp
* `stakeEnd`: staking end timestamp
* `resultStart`: result window start timestamp
* `resultEnd`: result window end timestamp

***

### `NumOutcomesSet`

Emitted when number of outcomes is set.

The contract currently derives `_numOutcomes` from `outcomeNames` and may not emit this event.

```solidity
event NumOutcomesSet(uint32 numOutcomes);
```

* `numOutcomes` (`uint32`) — Number of available outcomes

***

### `EventCancelled`

Emitted when the event is cancelled by oracle governance.

```solidity
event EventCancelled();
```

***

### `PMPCancelled`

Emitted when a PMP is cancelled by oracle.

```solidity
event EventCancelled();
```

***

### ProposalCreated

Emitted when an oracle governance proposal is created.

```solidity
event ProposalCreated(uint256 proposalId, uint32 functionType, TvmCell data);
```

* `proposalId`: deterministic proposal identifier (typically hash of `functionType` + `data`)
* `functionType`: action type identifier
* `data`: ABI-encoded payload (`TvmCell`)

***

### ProposalExecuted

Emitted when a proposal is executed.

```solidity
event ProposalExecuted(uint256 proposalId, uint32 functionType, TvmCell data);
```

* `proposalId`: executed proposal identifier
* `functionType`: executed action type identifier
* `data`: ABI-encoded payload used for execution.

***

## Oracle Approval Flow

### `approveEvent`

The function is called by an **OracleEventList** contract to confirm/approve the event initialization for this pool. It also optionally binds an internal sender address to the oracle pubkey for later governance actions.

```solidity
function approveEvent(
    uint256 oracle_pubkey,
    mapping(uint32 => string) outcomeNames,
    string describe,
    string name,
    optional(uint256) trustAddr
) public;
```

**Parameters:**

* `oracle_pubkey`: oracle public key used as an oracle identifier
* `outcomeNames`: mapping `outcomeId -> name` (used only on first approval)\
  It represents a **logical band of outcomes for a single event**.\
  **Where:**

  * **`outcomeId`** (key, e.g. `0, 1, 2, …`) — the identifier of a specific outcome
  * **`name`** — a description of that outcome

  **Example:**\
  **Sports Event "**&#x52;eal vs Benfica"\
  **Outcome band:**

  * **0** — Real wins
  * **1** — Benfica wins
  * **2** — Draw
* `describe`: event description (used only on first approval)
* `name`: pool name (used on every approval call)
* `trustAddr`: optional internal address binding to `oracle_pubkey` for internal voting flows

**Access Control:**

* Callable only by approved `OracleEventList` contracts
* The call is ignored (returns immediately) if:
  * this oracle event list address was already processed (implementation currently checks\
    or
  * the number of approvals already reached.

**Behavior:**

* prevents duplicate approvals (by pubkey / sender rules in implementation);
* on the first oracle approval, initializes:
  * the event description (`describe`);
  * outcome names mapping (`outcomeNames`);
  * number of outcomes (`numOutcomes = outcomeNames.keys().length`);
* once all required oracle confirmations are collected, emits `ApprovedByOracle(...)`.

***

### `rejectEvent`

Rejects the `PMP` and self-destructs the contract.

```solidity
function rejectEvent() public;
```

***

## Staking

### `acceptStake`

Accepts a stake from the user’s `PrivateNote` and records it in the pool.

```solidity
function acceptStake(
    uint32 outcomeId,
    uint128 stakeAmount,
    uint256 deposit_identifier_hash,
    uint8 bet_type
) public;
```

**Parameters:**

* `outcomeId`-chosen outcome identifier
* `stakeAmount`- stake amount
* `deposit_identifier_hash`- hash used to compute the caller’s `PrivateNote` address
* `bet_type` — 0 - clean bet, 1 - debt bet, 2 - coupon bet

**Requirements:**

* PMP approved by all oracles
* Within staking time window
* Outcome ID valid

**Side Effects:**

* Updates pools and counters
* Notifies `PrivateNote` via callback

***

### `acceptFullSetStake`

Accepts a **full-set stake** from a `PrivateNote` wallet during the dedicated full-set staking window.

A full-set stake represents proportional participation across **all outcomes** of the event.

`acceptFullSetStake` allows a user to stake across **all outcomes simultaneously**, preserving the proportional distribution of existing pools.

This function:

* Validates that the event is approved and not cancelled.
* Ensures the event is not yet resolved.
* Restricts execution to the **full-set time window**.
* Verifies proportionality against current outcome pools.
* Updates internal pool accounting.
* Notifies the caller’s `PrivateNote` via `onFullSetStakeAccepted`.

```solidity
function acceptFullSetStake(
        uint128[] amount,
        uint256 deposit_identifier_hash
    ) public
```

**Parameters**

* **`amount`** - Array of stake amounts per outcome.
  * Must have length equal to `_numOutcomes`.
  * Must follow the required pool proportion rules (see below).
* **`deposit_identifier_hash`** - Deposit identifier hash used to deterministically compute the caller’s `PrivateNote` address.

**Effects**

* Increases total pool liquidity.
* Preserves pool balance proportions.
* Does not affect coupon or debt pools.
* Does not emit a specific event; confirmation occurs via callback.

**Notes**

* Full-set staking is only available during the final portion of the staking period.
* Designed to allow liquidity providers to enter proportionally without skewing odds.
* Cannot be executed after resolution or cancellation.

***

### `cancelStake`

Cancels a user’s stakes **after the event is cancelled** and returns refund information to the caller’s `PrivateNote` wallet.

```solidity
function cancelStake(
        uint128[] stakeAmount,
        uint128[] debtAmount,
        uint128[] couponsAmount,
        uint256 deposit_identifier_hash
    ) public;
```

#### Parameters

* `stakeAmount` — Array of **clean** stake amounts per outcome.
* `debtAmount` — Array of **debt** stake amounts per outcome.
* `couponsAmount` — Array of **coupon** stake amounts per outcome.
* `deposit_identifier_hash` — Deposit identifier hash used to deterministically compute the caller’s `PrivateNote` address.

#### **Access:**

* only the computed `PrivateNote` address for `deposit_identifier_hash`.

#### Requirements

* The event must be cancelled:
  * If `block.timestamp > _resultEnd` and the event is not resolved and not cancelled, the contract triggers `cancelEvent()` internally.
  * After that, the function requires `_isCancelled == true`.
* Caller must be the expected `PrivateNote` wallet address derived from `deposit_identifier_hash`.

#### External Calls

* Calls `PrivateNote(wallet).onStakeCancelled(...)` to notify the wallet about:
  * total refunded clean+debt stake (`totalStake`)
  * total refunded coupon amount (`totalCouponRefund`)

***

### `withdrawFullSet`

Cancels a previously placed **full-set stake** during the full-set window and updates pool accounting accordingly.

This function is used to **withdraw (undo) a proportional full-set stake** before the staking period ends

```solidity
function withdrawFullSet(
        uint128[] amount,
        uint256 deposit_identifier_hash
    ) public;
```

**Parameters**

* **`amount`** - Array of withdrawal amounts per outcome.
  * Must have length equal to `_numOutcomes`.
  * Must preserve proportionality relative to current outcome pools.
* **`deposit_identifier_hash`** - Deposit identifier hash used to deterministically compute the caller’s `PrivateNote` wallet address.

`withdrawFullSet` removes a proportional full-set stake across **all outcomes**, provided the withdrawal keeps the same proportionality constraints used for full-set staking.

The function:

* Ensures the event is approved, not cancelled, and not resolved.
* Restricts execution to the **full-set time window**.
* Validates proportionality of the provided `amount`.
* Decreases outcome clean pools and global totals.
* Notifies the caller’s `PrivateNote` wallet via `onFullSetStakeCancelled`.

**Proportionality Rule**

The withdrawal amounts must preserve the same proportional structure enforced for full-set operations:

* For outcomes with non-zero pools:
  * `amount[i]` must match the proportional ratio relative to pool sizes.
* For outcomes with zero pools:
  * `amount[i]` must be zero.

This is validated by `_checkFullSetProportion(amount)`.

**Notes**

* This function does not emit a dedicated event; confirmation is delivered via the callback to `PrivateNote`.
* Withdrawals are only possible before `_stakeEnd`, and only after `fullSetStart`.
* The proportionality rule prevents selective withdrawal that would skew the pool distribution.

***

## Claims

### `claim`

Claims winnings (or processes a zero-payout claim) for a `PrivateNote` wallet after event resolution.

```solidity
function claim(
        uint128[] stakeAmount,
        uint128[] debtAmount,
        uint128[] couponsAmount,
        uint256 deposit_identifier_hash
    ) public
```

`claim` allows a user to settle their position in the PMP after the event has been resolved.

Depending on the outcome and the user’s position, the function:

* Processes a **winning payout**, or
* Processes a **zero-payout claim** if:
  * The event is not resolved yet, or
  * The user has no stake on the winning outcome.

After calculation, the contract notifies the caller’s `PrivateNote` wallet via `onClaimAccepted` and emits `ClaimProcessed`.

**Effects**

* Finalizes user settlement.
* Distributes winnings according to pari-mutuel logic.
* Automatically terminates the contract when all winning claims are completed.

**Notes**

* Arrays are expected to correspond to `_numOutcomes`.
* Claim can be called multiple times by different participants until `_totalWinPool` is fully distributed.

***

## Oracle Governance

### `createProposal`

Creates a new oracle governance proposal for the PMP contract.

This function allows authorized oracle participants to propose administrative actions such as:

* Setting staking and result time windows
* Resolving the event
* Cancelling the event

```solidity
function createProposal(uint32 function_type, TvmCell data) public;
```

Parameters

* **`function_type`** - Identifier of the proposed action.\
  Must correspond to one of the supported `FUNCTION_TYPE_*` constants:
  * `FUNCTION_TYPE_SET_STAKE_DEADLINE`
  * `FUNCTION_TYPE_SET_RESOLVE`
  * `FUNCTION_TYPE_CANCEL_EVENT`
* **`data`** - ABI-encoded payload required for the specified function type.

**Behavior**:

`createProposal` initializes a new governance proposal and automatically casts the creator’s vote.

The proposal is identified deterministically by:

```
proposalId = hash(function_type, data)
```

If there is only **one oracle**, the proposal is executed immediately.

Otherwise, the proposal remains active until:

* It collects enough votes (based on threshold), or
* Its deadline expires (7 days from creation).

### Governance Flow

1. Oracle creates proposal → creator vote is automatically counted.
2. Other oracles call `vote(proposalId)`.
3. Once vote threshold is reached:
   * `executeProposal` is called.
4. Proposal is deleted after execution.
5. If deadline expires before threshold:
   * Proposal is discarded.

***

### `vote`

Votes on an existing proposal.

```solidity
function vote(uint256 proposalId) public;
```

**Parameter**:

* `proposalId`: identifier of the proposal to vote on

**Access**:

* only authorized oracles.

**Behavior**:

* rejects if proposal does not exist;
* ignores/removes proposal if it is past deadline;
* prevents double voting by the same oracle pubkey;
* executes proposal automatically once the threshold is reached (implementation-specific);
* successful execution leads to `ProposalExecuted(...)`.

***

## View Functions

### `getDetails`

Returns the full current state of the PMP contract.

This function provides a comprehensive snapshot of the pool configuration, lifecycle state, oracle status, and pool balances.

```solidity
function getDetails() external view returns (
        string name,
        uint32 token_type,
        uint256 event_id,
        uint256 oracle_list_hash,
        address deployer,
        uint256 privateNoteCodeHash,
        uint128 totalPool,
        bool approved,
        uint32 numOutcomes,
        optional(uint32) resolvedOutcome,
        uint64 stakeStart,
        uint64 stakeEnd,
        uint64 resultStart,
        uint64 resultEnd,
        bool isCancelled,
        uint128 numberOfOracleEvents,
        uint128 approvedOracleEvents,
        mapping(uint32 => mapping(uint8 => uint128)) typedOutcomePools,
        mapping(uint32 => string) outcomeNames
    )
```

**Returns** :

**General Information**

* **`name`** - Human-readable pool name.
* **`token_type`** - Static token type used for the pool.
* **`event_id`** - Identifier of the associated event.
* **`oracle_list_hash`** - Hash of the oracle list used during deployment.
* **`deployer`** - Address of the `PrivateNote` wallet that deployed the contract.
* **`privateNoteCodeHash`** - Hash of the `PrivateNote` contract code used for address derivation.

**Pool State**

* **`totalPool`** - Total amount currently in the pool (after fees and redistributions).
* **`approved`** - Indicates whether the event is approved and staking is enabled.
* **`isCancelled`** - Indicates whether the event has been cancelled.
* **`resolvedOutcome`** - Final outcome identifier, if resolved.

**Outcomes**

* **`numOutcomes`** - Total number of outcomes.
* **`outcomeNames`** - Mapping of outcome identifiers to human-readable names.
* **`typedOutcomePools`** - Pool balances separated by:
  * Outcome ID
  * Bet type (0 = clean, 1 = debt, 2 = coupon)

**Time Windows**

* **`stakeStart`** - Stake acceptance start timestamp.
* **`stakeEnd`** - Stake acceptance end timestamp.
* **`resultStart`** - Result acceptance start timestamp.
* **`resultEnd`** - Result acceptance end timestamp.

**Oracle Governance**

* **`numberOfOracleEvents`** -Total number of required oracle confirmations.
* **`approvedOracleEvents`** -Number of oracle confirmations received.

***

### `getVersion`

Returns the implementation version and kind identifier.

```solidity
function getVersion() external pure returns (string, string);
```

**Returns**:

* `semver`: version string
* `kind`: contract kind string (expected `"PMP"`)


# Overview

Shell Accumulator is an on-chain exchange system on the GOSH network that lets users trade **ECC SHELL** for **eccUSDC** at a fixed rate of **100 SHELL = 1 eccUSDC**.

## What it does

Sellers deposit SHELL into fixed-size lots (denominated in 1, 10, 100, or 1000 eccUSDC). Buyers deposit eccUSDC and receive SHELL — first matched against existing seller lots in FIFO order, then minted if no sellers are available. When a buyer's eccUSDC matches a seller's lot, the seller can claim their eccUSDC payout.

A separate token, **NACKL**, can be redeemed (burned) against the "free reserve" — the eccUSDC balance not owed to any seller.

## Tokens (ECC IDs)

| Token   | ECC ID | Decimals  | Role                            |
| ------- | ------ | --------- | ------------------------------- |
| NACKL   | 1      | 9 (nano)  | Value storage and staking       |
| SHELL   | 2      | 9 (nano)  | Utility token, sold by sellers  |
| eccUSDC | 3      | 6 (micro) | Stablecoin, deposited by buyers |

All token amounts in the contracts use their smallest unit: nanoSHELL, nanoNACKL, microeccUSDC.

## Contracts

| Contract                   | Source                                               | Role                                                                                                                                                                     |
| -------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ShellAccumulatorRootUSDC` | `contracts/accumulator/ShellAccumulatorRootUSDC.sol` | The central Accumulator contract: accepts eccUSDC, SHELL, and NACKL, manages FIFO seller queues, sells SHELL instantly, and handles eccUSDC payouts for claims and burn. |
| `ShellSellOrderLot`        | `contracts/accumulator/ShellSellOrderLot.sol`        | One per seller position; carries claim metadata                                                                                                                          |
| `AccumulatorLib`           | `contracts/accumulator/libraries/AccumulatorLib.sol` | Deterministic address derivation for lots                                                                                                                                |
| `Exchange`                 | `contracts/exchange/Exchange.sol`                    | TIP-3 USDC bridge and admin mint entry point                                                                                                                             |

## Key design decisions

**Fixed denominations.**

Lots come in exactly 4 sizes: 1, 10, 100, 1000 eccUSDC. There are no partial lots. A 154 eccUSDC buy matches 1×100 + 5×10 + 4×1 lots.

**FIFO guarantee.**

Each denomination has its own queue. Lots are matched strictly in order of creation — earlier sellers get paid first.

**Deterministic lot addresses.**

Lot contract addresses are derived from `(code, root, denom, orderId)` using `AccumulatorLib`. This means the Root can verify any caller claiming to be a lot by recomputing the expected address, without storing a mapping.

**Directed events.**

Events are emitted to hardcoded external addresses (610–617) so that off-chain backends can subscribe to specific event streams without parsing all contract messages. See [Events ](/accumulator-contract-system/api-reference#events)for the full list.


# Architecture

```mermaid
flowchart LR
    User[User / AN Wallet]
    Owner[Owner / Backend]

    subgraph OffChain[Off-chain]
        Backend[Bridge Backend]
        SettlementMonitor[Settlement Monitor]
        OrdersAPI[user_orders API]
    end

    subgraph OnChain[On-chain Contracts]
        Exchange[Exchange]
        Accumulator[ShellAccumulatorRootUSDC]
        SellOrder[ShellSellOrderLot]
    end

    User -->|Direct eccUSDC buy| Accumulator
    Owner -->|mintAndSendAccumulator + nonce| Exchange
    Exchange -->|buyShellFor + eccUSDC| Accumulator
    Accumulator -->|ECC SHELL| User

    User -->|ECC SHELL deposit| Accumulator
    Accumulator -->|Deploy lot| SellOrder

    User -->|claim| SellOrder
    SellOrder -->|claimUSDC| Accumulator
    Accumulator -->|eccUSDC payout| User

    User -->|ECC NACKL| Accumulator
    Accumulator -->|eccUSDC from free reserve| User

    Backend -->|triggerTransaction| Owner
    SettlementMonitor -.->|reads queues via getters| Accumulator
    SettlementMonitor --> OrdersAPI

    classDef actor fill:#eef6ff,stroke:#4a7bb7,color:#16324f;
    classDef offchain fill:#fff6e5,stroke:#c08a1a,color:#4b3200;
    classDef onchain fill:#ebfff0,stroke:#2f8f4e,color:#123a20;

    class User,Owner actor;
    class Backend,SettlementMonitor,OrdersAPI offchain;
    class Exchange,Accumulator,SellOrder onchain;
```

## Contract roles

**ShellAccumulatorRootUSDC** is the central contract. It holds all ECC balances (eccUSDC and SHELL from sellers), manages four FIFO queues (one per denomination), matches buyers against sellers, mints SHELL when sellers are insufficient, pays out USDC on claims, and handles NACKL redemption.

**ShellSellOrderLot** is a lightweight per-order contract deployed by the Root when a seller deposits SHELL. It stores the seller's address, denomination, and order ID. Its only active function is `claim()`, which calls back into Root's `claimUSDC`. After payout confirmation, it self-destructs.

**AccumulatorLib** is a pure library used by the Root to compute deterministic lot addresses. It salts the lot code with `(versionLib, root)` and encodes `(_denom, _orderId)` as static variables, producing a unique address per lot.

**Exchange** is a separate contract that bridges TIP-3 USDC into ECC USDC. It has two paths: the `onTransferReceived` callback (triggered when someone sends TIP-3 USDC to the Exchange's wallet) and admin-only `mintAndSend` / `mintAndSendAccumulator` functions. It connects to the Accumulator at a hardcoded `ACCUMULATOR_ADDRESS`.

## FIFO queue model

Each denomination (1, 10, 100, 1000) has four counters:

| Counter      | Meaning                                         |
| ------------ | ----------------------------------------------- |
| `nextId`     | Next order ID to assign (starts at 1)           |
| `available`  | Number of lots waiting to be matched            |
| `soldPrefix` | Contiguous prefix of sold lots                  |
| `owedCount`  | Sold lots whose eccUSDC hasn't been claimed yet |

Order IDs are **1-based** (`nextId` starts at 1). The first lot gets `orderId = 1`, the second gets `orderId = 2`, etc. `soldPrefix = 3` means lots 1, 2, 3 are sold.

Key invariant: `available <= nextId - 1 - soldPrefix`. Total created = `nextId - 1`. Of those, `soldPrefix` are sold, `available` are waiting to be matched, and the rest are in transition.

## Address coupling

Exchange sends buy flow to a **fixed** `ACCUMULATOR_ADDRESS` (`0x3535...3535`)


# Sell/Buy/Burn Flows

All primary flows in the Accumulator system.

**Seller lifecycle: from order creation (SHELL deposit) to eccUSDC payout:**

```mermaid
sequenceDiagram
    autonumber
    actor Seller
    actor Buyer
    actor Owner as Owner / Backend
    participant Exchange
    participant Accumulator as ShellAccumulatorRootUSDC
    participant SellOrder as ShellSellOrderLot

    rect rgb(240, 255, 240)
        Note over Seller,SellOrder: 1. Seller deposits SHELL — joins the queue
        Seller->>Accumulator: Send SHELL (e.g. 1000 SHELL = 10 eccUSDC lot)
        Accumulator->>Accumulator: Validate denomination and amount
        Accumulator->>Accumulator: Assign FIFO orderId, increment available[D]
        Accumulator->>SellOrder: Deploy lot contract
        Accumulator-->>Seller: Emit SellOrderCreated
        Note over SellOrder: Lot status: Waiting
    end

    rect rgb(235, 245, 255)
        Note over Buyer,Accumulator: 2. Buyer pays eccUSDC — seller's lot gets matched
        alt Direct buy
            Buyer->>Accumulator: Send eccUSDC
        else Buy through Exchange
            Owner->>Exchange: mintAndSendAccumulator(buyer, value, nonce)
            Exchange->>Accumulator: buyShellFor(buyer) + eccUSDC
        end
        Accumulator->>Accumulator: Match FIFO queues 1000 → 100 → 10 → 1
        Accumulator->>Accumulator: soldPrefix[D] += matched lots
        Accumulator->>Accumulator: Mint remaining SHELL if sellers insufficient
        Accumulator-->>Buyer: Transfer ECC SHELL
        Note over SellOrder: Lot status: Sold (orderId ≤ soldPrefix)
    end
    
    rect rgb(255, 248, 235)
        Note over Seller,SellOrder: 3. Seller claims eccUSDC payout
        Seller->>SellOrder: claim() — called by wallet automatically
        SellOrder->>Accumulator: claimUSDC(denom, orderId, owner)
         alt Lot is sold
            Accumulator-->>Seller: Transfer eccUSDC directly to seller
            Accumulator-->>SellOrder: onReceiveUSDC(amount)
            Note over SellOrder: Lot destroyed
        else Lot not sold yet
            Accumulator--xSellOrder: Bounce (require failed)
            SellOrder->>SellOrder: Reset _claimed = false
            Note over SellOrder: Lot status: Waiting (retry later)
        end
    end 

```

## Sell Shell (create sell order)

```mermaid
sequenceDiagram
    autonumber
    actor Seller
    actor Buyer
    participant Exchange
    participant Accumulator as ShellAccumulatorRootUSDC
    participant SellOrder as ShellSellOrderLot

    rect rgb(240, 255, 240)
        Note over Seller,SellOrder: 1. Seller deposits SHELL — joins the queue
        Seller->>Accumulator: Send ECC SHELL (e.g. 1000 SHELL = 10 eccUSDC lot)
        Accumulator->>Accumulator: Validate denomination and amount
        Accumulator->>Accumulator: Assign FIFO orderId, increment available[D]
        Accumulator->>SellOrder: Deploy lot contract
        Accumulator-->>Seller: Emit SellOrderCreated
        Note over SellOrder: Lot status: Waiting
    end

```

A seller creates a lot by sending ECC SHELL to the Root's `receive()`. The amount must correspond to exactly one denomination:

| Denomination | SHELL required (nanoSHELL)  |
| ------------ | --------------------------- |
| 1 eccUSDC    | 100,000,000,000 (100 × 10⁹) |
| 10 eccUSDC   | 1,000,000,000,000           |
| 100 eccUSDC  | 10,000,000,000,000          |
| 1000 eccUSDC | 100,000,000,000,000         |

**What happens on-chain:**

1. Root validates `shellAmount % SHELL_PER_USDC == 0` and the resulting denomination is one of {1, 10, 100, 1000}.
2. Assigns `orderId = nextId[D]`, increments `nextId[D]` and `available[D]`.
3. Adds `shellAmount` to `_sellerShellPool`.
4. Deploys a new `ShellSellOrderLot` contract with deterministic address derived from `(code, root, denom, orderId)`.
5. Emits `SellOrderCreated` twice: once to the seller's external address (for per-user subscription) and once to external address `610` (for global monitoring).

**Result:** the seller holds a lot contract and waits for a buyer to match it.

***

## Buy Shell (deposit eccUSDC)

```mermaid
sequenceDiagram
    autonumber
    actor Buyer
    actor Owner as Owner / Backend
    participant Exchange
    participant Accumulator as ShellAccumulatorRootUSDC
    participant SellOrder as ShellSellOrderLot

    rect rgb(235, 245, 255)
        Note over Buyer,Accumulator: 2. Buyer pays eccUSDC — seller's lot gets matched
        alt Direct buy
            Buyer->>Accumulator: Send eccUSDC
        else Buy through Exchange
            Owner->>Exchange: mintAndSendAccumulator(buyer, value, nonce)
            Exchange->>Accumulator: buyShellFor(buyer) + eccUSDC
        end
        Accumulator->>Accumulator: Match FIFO queues 1000 → 100 → 10 → 1
        Accumulator->>Accumulator: soldPrefix[D] += matched lots
        Accumulator->>Accumulator: Mint remaining SHELL if sellers insufficient
        Accumulator-->>Buyer: Transfer ECC SHELL
        Note over SellOrder: Lot status: Sold (orderId ≤ soldPrefix)
    end
```

A buyer sends eccUSDC to the Root (directly or via Exchange). The amount must be in whole eccUSDC units (`amount % 1_000_000 == 0`).

**Matching algorithm (largest-first FIFO):**

```
remaining = usdcAmount / USDC_DECIMALS_FACTOR   // whole eccUSDC

for each D in [1000, 100, 10, 1]:
    take = min(available[D], remaining / D)
    if take > 0:
        available[D]  -= take
        soldPrefix[D] += take
        owedCount[D]  += take
        remaining     -= take * D
        totalShellFromSellers += take * D * SHELL_PER_USDC

if remaining > 0:
    mint remaining * SHELL_PER_USDC fresh ECC SHELL

send totalShellFromSellers + mintedShell to buyer
```

**Important details:**

* Matching is greedy: it takes as many lots as possible from the largest denomination first.
* If sellers partially cover the amount, the rest is minted. The buyer always gets 100% of the SHELL.
* The eccUSDC stays on the Root. It is tracked in `_usdcBalance` and becomes available for seller claims and NACKL redemption.
* Two events are emitted: `ShellPurchased` (to ext addr 611) and `MatchedOrders` (to ext addr 617, with current `soldPrefix` values).

**Note on `buyShellFor` vs `receive`:** Both accept eccUSDC and trigger the same `_processUsdcDeposit` logic. The difference: `receive()` rejects messages carrying more than one ECC currency (`require(currencies.keys().length <= 1)`), while `buyShellFor()` only checks that eccUSDC is present. If a multi-currency message arrives via `buyShellFor`, the non-USDC ECC will remain on the contract.

***

## Claim — seller collects eccUSDC

```mermaid
sequenceDiagram
    autonumber
    actor Seller
    participant Exchange
    participant Accumulator as ShellAccumulatorRootUSDC
    participant SellOrder as ShellSellOrderLot

    rect rgb(255, 248, 235)
        Note over Seller,SellOrder: 3. Seller claims eccUSDC payout
        Seller->>SellOrder: claim() — called by wallet automatically
        SellOrder->>Accumulator: claimUSDC(denom, orderId, owner)
        alt Lot is sold
            Accumulator-->>Seller: Transfer eccUSDC directly to seller
            Accumulator-->>SellOrder: onReceiveUSDC(amount)
            Note over SellOrder: Lot destroyed
        else Lot not sold yet
            Accumulator--xSellOrder: Bounce (require failed)
            SellOrder->>SellOrder: Reset _claimed = false
            Note over SellOrder: Lot status: Waiting (retry later)
        end
    end
```

After a lot is matched (sold), the seller calls `claim()` on their lot contract to receive the eccUSDC payout.

{% stepper %}
{% step %}

#### SellOrderLot.claim()

Sets `_claimed = true`, then calls `Root.claimUSDC(denom, orderId, owner)`.
{% endstep %}

{% step %}

#### Root.claimUSDC()

Verifies the caller's address matches the expected lot address (recomputed deterministically), checks `orderId <= soldPrefix[D]` (lot is sold), checks `owedCount[D] > 0`, and checks `_usdcBalance >= owedTotal`. If all pass:

* Sends `D × USDC_DECIMALS_FACTOR` eccUSDC **directly to the seller** (not to the lot).
* Calls `SellOrderLot.onReceiveUSDC(payout)` to confirm.
* Decrements `owedCount[D]` and `_usdcBalance`.
  {% endstep %}

{% step %}

#### SellOrderLot.onReceiveUSDC()

Verifies the amount, emits `OrderDestroyed`, self-destructs back to the Root.
{% endstep %}

{% step %}

#### If the lot is not yet sold

`claimUSDC` reverts (require fails), the message bounces back, and the lot's `onBounce` handler resets `_claimed = false`. The seller can try again later.
{% endstep %}

{% step %}

#### Double-claim protection

Double-claim protection is multi-layered: the lot checks `!_claimed` before calling, the Root checks `owedCount > 0`, and the lot self-destructs after success — so the contract ceases to exist.
{% endstep %}
{% endstepper %}

***

## Redeem (Burn-to-earn) NACKL

```mermaid
sequenceDiagram
    autonumber
    actor User
    actor Owner as Owner / Backend
    participant Exchange
    participant Accumulator as ShellAccumulatorRootUSDC
    
    rect rgb(255, 235, 240)
        Note over User,Accumulator: Redeem NACKL
        User->>Accumulator: Send ECC NACKL
        Accumulator->>Accumulator: Burn NACKL, compute payout
        Accumulator-->>User: Transfer eccUSDC
    end
```

A NACKL holder sends ECC NACKL to the Root's `receive()` to burn it and claim a share of the "free reserve" — eccUSDC not owed to any seller.

**Payout formula:**

```
supply        = M(t)                    // NACKL emission curve
currentSupply = supply - _nacklBurned   // subtract all previously burned NACKL
redeemable    = _usdcBalance - owedUsdcTotal()  // free reserve

payout = redeemable × burnAmount / currentSupply
```

Where `M(t) = T_KM × (1 - exp(-u_M × t))`, capped at `NACKL_T`. `t` is seconds since `_unixstart`.

**Key point:** `currentSupply` is **not** `M(t)` — it's `M(t) minus all NACKL burned to date`. As more NACKL is burned, the denominator shrinks, so each subsequent burn receives a larger share of the remaining reserve. This is by design: later redeemers get proportionally more of whatever eccUSDC is left.

{% stepper %}
{% step %}

#### Burn the NACKL

Burn the NACKL via `gosh.burnecc()`.
{% endstep %}

{% step %}

#### Compute currentSupply and check it

Compute `currentSupply` and check it's sufficient.
{% endstep %}

{% step %}

#### Compute redeemable and check it

Compute `redeemable` (free reserve) and check it's positive.
{% endstep %}

{% step %}

#### Compute payout

Compute `payout = redeemable * burnAmount / currentSupply`.
{% endstep %}

{% step %}

#### Update balances

Increment `_nacklBurned`, decrement `_usdcBalance`.
{% endstep %}

{% step %}

#### Send payout

Send eccUSDC to the sender.
{% endstep %}
{% endstepper %}

***

## Exchange TIP3 to eccUSDC through Exchange

The Exchange also has `onTransferReceived` — a callback from its TIP-3 USDC wallet. When someone sends TIP-3 USDC to the Exchange's wallet, it mints equivalent eccUSDC and sends it back to the depositor's address (not to the Accumulator). The depositor can then send it to the Accumulator directly.


# API reference

Complete reference for all public/external functions, events, and error codes across the Accumulator contract system.

## ShellAccumulatorRootUSDC

Source: `contracts/accumulator/ShellAccumulatorRootUSDC.sol` · Version: 1.0.2\
\&#xNAN;*It will be available after the next node release*

### Entry points

#### `buyShellFor(address buyer)`

```solidity
function buyShellFor(address buyer) public
```

Accepts eccUSDC attached to the message and processes a buy on behalf of `buyer`. Used by Exchange to forward purchases. Does **not** check for multi-currency messages — only verifies eccUSDC is present.

#### `claimUSDC(uint16 D, uint64 orderId, address seller)`

```solidity
function claimUSDC(uint16 D, uint64 orderId, address seller) public
```

Called by a SellOrderLot to claim its eccUSDC payout. Verifies caller address deterministically, checks the order is sold (`orderId <= soldPrefix[D]`), sends eccUSDC to `seller`, then calls `onReceiveUSDC` on the lot.

### Admin

#### `setPubkey(uint256 pubkey)`

```solidity
function setPubkey(uint256 pubkey) public onlyOwnerPubkey accept
```

Replaces the owner public key. Only callable by the current owner (verified via `msg.pubkey()`).

### Getters

#### `getQueueState(uint16 D)`

```solidity
function getQueueState(uint16 D) external view
    returns (uint64 nextId, uint64 available, uint64 soldPrefix, uint64 owedCount)
```

Returns the FIFO queue state for denomination `D` (1, 10, 100, or 1000).

* `nextId` — next order ID to assign (1-based)
* `available` — lots waiting to be matched by a buyer
* `soldPrefix` — contiguous count of sold lots from the start
* `owedCount` — sold lots that haven't been claimed yet

#### `getDetails()`

```solidity
function getDetails() external view
    returns (uint256 ownerPubkey, uint128 sellerShellPool, uint128 usdcBalance, uint128 owedTotal)
```

Returns high-level contract state.

* `sellerShellPool` — total SHELL held from seller deposits (nanoSHELL)
* `usdcBalance` — total eccUSDC tracked by the contract (microUSDC)
* `owedTotal` — total eccUSDC owed to sellers awaiting claim (microUSDC)

#### `getSellOrderAddress(uint16 D, uint64 orderId)`

```solidity
function getSellOrderAddress(uint16 D, uint64 orderId) external view
    returns (address sellOrderAddr)
```

Computes the deterministic address of a lot contract given its denomination and order ID. Useful for off-chain address resolution without deploying.

#### `owedUsdcTotal()`

```solidity
function owedUsdcTotal() external view returns (uint128)
```

Returns total eccUSDC owed to all sellers across all denominations (microUSDC).

#### `getSellerShellPool()`

```solidity
function getSellerShellPool() external view returns (uint128)
```

Returns total ECC SHELL in the seller pool (nanoSHELL).

#### `getUsdcBalance()`

```solidity
function getUsdcBalance() external view returns (uint128)
```

Returns the eccUSDC balance tracked by the contract (microUSDC). This is the accounting balance, not necessarily the on-chain ECC balance.

#### `getNacklInfo()`

```solidity
function getNacklInfo() external view
    returns (uint128 supply, uint128 burned, uint32 unixstart)
```

Returns NACKL emission state.

* `supply` — current `M(t)` from the emission curve (nanoNACKL)
* `burned` — total NACKL burned via `redeemNACKL` to date (nanoNACKL)
* `unixstart` — emission start timestamp (Unix seconds)

The effective circulating supply is `supply - burned`.

#### `getVersion()`

```solidity
function getVersion() external pure returns (string version, string name)
```

Returns `("1.0.2", "ShellAccumulatorRootUSDC")`.

***

## ShellSellOrderLot

Source: `contracts/accumulator/ShellSellOrderLot.sol` · Version: 1.0.2\
\&#xNAN;*It will be available after the next node release*

### Entry points

#### `claim()`

```solidity
function claim() public
```

Initiates eccUSDC payout claim. Sets `_claimed = true` and calls `Root.claimUSDC(denom, orderId, owner)`. If the root rejects (order not yet sold), the bounced message resets `_claimed = false` via `onBounce`.

Can be called by anyone (no `msg.sender` check), but the payout always goes to `_owner` (the original seller).

#### `onReceiveUSDC(uint128 amount)`

```solidity
function onReceiveUSDC(uint128 amount) public senderIs(_root) accept
```

Callback from the Root confirming payout was sent. Verifies `amount == _denom * USDC_DECIMALS_FACTOR`, emits `OrderDestroyed`, and self-destructs.

### Getters

#### `getDetails()`

```solidity
function getDetails() external view
    returns (address root, address owner, uint16 denom, uint64 orderId, bool claimed)
```

Returns all lot metadata.

* `root` — parent Accumulator address
* `owner` — seller address (receives eccUSDC payout)
* `denom` — lot denomination (1, 10, 100, 1000)
* `orderId` — FIFO position within the denomination queue
* `claimed` — `true` if `claim()` was called and is pending or completed

#### `getVersion()`

```solidity
function getVersion() external pure returns (string version, string name)
```

Returns `("1.0.2", "ShellSellOrderLot")`.

***

## Exchange

Source: `contracts/exchange/Exchange.sol` · Version: 1.0.4\
\&#xNAN;*It will be available after the next node release*

### Entry points

#### `onTransferReceived(address from, address to, uint128 value, uint128 balance)`

```solidity
function onTransferReceived(address from, address, uint128 value, uint128) external override
```

ISubscriber callback from the Exchange's TIP-3 USDC wallet. Mints equivalent eccUSDC and sends it to `from` (the depositor). Only callable by `_usdcWallet`.

#### `mintAndSend(address recipient, uint128 value, uint64 nonce)`

```solidity
function mintAndSend(address recipient, uint128 value, uint64 nonce) public onlyOwnerPubkey accept
```

Admin-only. Mints eccUSDC and sends to `recipient`. Requires `nonce == _mintNonce + 1`.

#### `mintAndSendAccumulator(address buyer, uint128 value, uint64 nonce)`

```solidity
function mintAndSendAccumulator(address buyer, uint128 value, uint64 nonce) public onlyOwnerPubkey accept
```

Admin-only. Mints eccUSDC and calls `Accumulator.buyShellFor(buyer)` with the minted eccUSDC attached. Requires whole eccUSDC units and `nonce == _mintAccumulatorNonce + 1`. Uses separate nonce space from `mintAndSend`.

### Admin

#### `setPubkey(uint256 pubkey)`

```solidity
function setPubkey(uint256 pubkey) public onlyOwnerPubkey accept
```

Replaces the owner public key.

#### `triggerTransaction(address txAddr)`

```solidity
function triggerTransaction(address txAddr) public view onlyOwnerPubkey accept
```

Sends 1 vmshell to `txAddr`. Used to trigger Transaction contracts for wallet setup (e.g., `SET_SUBSCRIBER_TYPE`).

### Getters

#### `getUsdcWallet()`

```solidity
function getUsdcWallet() external view returns (address)
```

Returns the TIP-3 USDC TokenWallet address used for the bridge.

#### `getOwnerPubkey()`

```solidity
function getOwnerPubkey() external view returns (uint256)
```

Returns the current owner public key.

#### `getTotalMinted()`

```solidity
function getTotalMinted() external view returns (uint128)
```

Returns total eccUSDC minted by this contract across all methods (microUSDC).

#### `getNonces()`

```solidity
function getNonces() external view returns (uint64 mintNonce, uint64 mintAccumulatorNonce)
```

Returns current nonces for both mint paths. The next valid nonce for each path is `current + 1`.

#### `getVersion()`

```solidity
function getVersion() external pure returns (string version, string name)
```

Returns `("1.0.4", "Exchange")`.

***

## AccumulatorLib

Source: `contracts/accumulator/libraries/AccumulatorLib.sol` · Version: 1.0.2\
\&#xNAN;*It will be available after the next node release*

#### `calculateSellOrderAddress(TvmCell code, address root, uint16 denom, uint64 orderId)`

```solidity
function calculateSellOrderAddress(TvmCell code, address root, uint16 denom, uint64 orderId)
    public returns (address)
```

Computes the deterministic address of a SellOrderLot. The address is `makeAddrStd(0, hash(stateInit))`.

#### `composeSellOrderStateInit(TvmCell code, address root, uint16 denom, uint64 orderId)`

```solidity
function composeSellOrderStateInit(TvmCell code, address root, uint16 denom, uint64 orderId)
    public returns (TvmCell)
```

Builds the full stateInit for a lot: salted code + static variables `_denom` and `_orderId`.

#### `buildSellOrderCode(TvmCell originalCode, address root)`

```solidity
function buildSellOrderCode(TvmCell originalCode, address root)
    public returns (TvmCell)
```

Salts the lot code with `abi.encode(versionLib, root)`. This binds the lot to a specific Root contract and library version.

***

## Events

All events are emitted to **external addresses** (directed events) for off-chain subscription. The external address is constructed as `address.makeAddrExtern(eventId, 256)`.

### Root events

| Event              | Ext Addr                   | Fields                                                                               | Emitted when                                                                     |
| ------------------ | -------------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- |
| `SellOrderCreated` | **610** + seller's address | `(address seller, uint16 denom, uint64 orderId, uint128 shellAmount)`                | New lot created. Emitted twice: to addr 610 and to the seller's external address |
| `ShellPurchased`   | **611**                    | `(address buyer, uint128 usdcAmount, uint128 shellFromSellers, uint128 shellMinted)` | Buy completed                                                                    |
| `UsdcClaimed`      | **612**                    | `(uint64 orderId, uint16 denom, address seller, uint128 payout)`                     | Seller claimed eccUSDC                                                           |
| `NacklRedeemed`    | **613**                    | `(address recipient, uint128 burnAmount, uint128 payout)`                            | NACKL burned for USDC                                                            |
| `MatchedOrders`    | **617**                    | `(uint64 lastSold1, uint64 lastSold10, uint64 lastSold100, uint64 lastSold1000)`     | Updated soldPrefix values after a buy                                            |

### Lot events

| Event            | Target   | Fields                                           |
| ---------------- | -------- | ------------------------------------------------ |
| `ClaimInitiated` | internal | `(uint64 orderId, uint16 denom, address owner)`  |
| `OrderDestroyed` | internal | `(uint64 orderId, uint16 denom, uint128 amount)` |

### Exchange events

| Event          | Ext Addr | Fields                               | Emitted when                                                           |
| -------------- | -------- | ------------------------------------ | ---------------------------------------------------------------------- |
| `UsdcMigrated` | **615**  | `(address from, uint128 value)`      | TIP-3 USDC bridged to ECC                                              |
| `UsdcMinted`   | **616**  | `(address recipient, uint128 value)` | Admin-minted eccUSDC (from `mintAndSend` and `mintAndSendAccumulator`) |

***

## Error Codes

### Accumulator errors (Root + SellOrderLot)

| Code | Name                          | Meaning                                                     |
| ---- | ----------------------------- | ----------------------------------------------------------- |
| 200  | `ERR_INVALID_DENOM`           | Denomination is not 1, 10, 100, or 1000                     |
| 201  | `ERR_WRONG_SHELL_AMOUNT`      | SHELL amount doesn't divide evenly by SHELL\_PER\_USDC      |
| 202  | `ERR_WRONG_USDC_AMOUNT`       | eccUSDC amount mismatch in onReceiveUSDC or balance check   |
| 203  | `ERR_NOT_WHOLE_USDC`          | eccUSDC amount is not a whole number (not divisible by 10⁶) |
| 204  | `ERR_ZERO_AMOUNT`             | Zero amount supplied                                        |
| 205  | `ERR_ORDER_NOT_SOLD`          | Lot's orderId > soldPrefix (not yet matched)                |
| 206  | `ERR_NO_OWED`                 | No owed claims remaining for this denomination              |
| 207  | `ERR_INVALID_SENDER`          | Caller is not the expected contract                         |
| 208  | `ERR_ALREADY_CLAIMED`         | claim() already called on this lot                          |
| 209  | `ERR_NOT_OWNER`               | msg.pubkey() doesn't match owner                            |
| 210  | `ERR_INSUFFICIENT_REDEEMABLE` | Not enough free reserve for NACKL redemption                |
| 211  | `ERR_WRONG_CODE`              | (reserved)                                                  |
| 212  | `ERR_WRONG_ADDRESS`           | Caller address doesn't match deterministic lot address      |
| 213  | `ERR_MULTIPLE_CURRENCIES`     | Message carries more than one ECC currency type             |
| 214  | `ERR_OVERFLOW`                | Amount exceeds uint64 max                                   |

### Exchange errors

| Code | Name                 | Meaning                          |
| ---- | -------------------- | -------------------------------- |
| 204  | `ERR_ZERO_AMOUNT`    | Zero value                       |
| 207  | `ERR_INVALID_SENDER` | Caller is not the eccUSDC wallet |
| 209  | `ERR_NOT_OWNER`      | msg.pubkey() doesn't match owner |
| 213  | `ERR_NOT_WHOLE_USDC` | Value not divisible by 10⁶       |
| 214  | `ERR_OVERFLOW`       | Value exceeds uint64 max         |
| 215  | `ERR_INVALID_NONCE`  | Nonce is not current + 1         |

{% hint style="info" %}
Error code 213 means different things in different contracts: `ERR_MULTIPLE_CURRENCIES` in the Accumulator vs `ERR_NOT_WHOLE_USDC` in the Exchange. When debugging failed transactions, check which contract emitted the error.
{% endhint %}

***

## Constants

### Token IDs and decimals

| Constant                | Value                       | Used in        |
| ----------------------- | --------------------------- | -------------- |
| `NACKL_ECC_ID`          | 1                           | Root           |
| `SHELL_ECC_ID`          | 2                           | Root           |
| `USDC_ECC_ID`           | 3                           | Root, Exchange |
| `SHELL_DECIMALS_FACTOR` | 1,000,000,000 (10⁹)         | Root           |
| `USDC_DECIMALS_FACTOR`  | 1,000,000 (10⁶)             | Root, Exchange |
| `SHELL_PER_USDC`        | 100,000,000,000 (100 × 10⁹) | Root           |

### NACKL emission

| Constant         | Value                      | Meaning                        |
| ---------------- | -------------------------- | ------------------------------ |
| `NACKL_T`        | 10,400,000,000,000,000,000 | Max supply cap (nanoNACKL)     |
| `NACKL_T_KM`     | 10,400,104,000,000,000,000 | T × (1 + K\_M), K\_M = 0.00001 |
| `NACKL_U_M_FP18` | 5,756,467,732              | Growth rate × 10¹⁸             |
| `FP18`           | 10¹⁸                       | Fixed-point scaling factor     |
| `INV_E_FP18`     | 367,879,441,171,442,322    | exp(-1) × 10¹⁸                 |

### Denominations

```
DENOM_1    = 1
DENOM_10   = 10
DENOM_100  = 100
DENOM_1000 = 1000
```


# Bee Engine Overview

**Bee Engine** is an embeddable mining engine and contract system that allows any application to run [**NACKL**](https://docs.ackinacki.com/glossary#nackl) **mining on the client side** and securely validate the results on the blockchain.

The core idea of Bee Engine is **mining as a background process**, independent of the application type.

It can be a game, a utility, a document editor or even a non-gaming service.

A user can play chess, work with text, or use any other application —\
**while simultaneously mining NACKL**

### What Bee Engine Solves

Bee Engine enables developers to:

* Embed mining directly into their applications
* Use client-side computation without trusting the client
* Distribute rewards based on verifiable results
* Build reputation and reward systems based on real user contribution

Mining becomes **part of the user experience**, not a separate process.

### Architecture

Bee Engine consists of two logically independent but connected components.

#### 1. Client Bee Engine Miner

Code that runs on the client side.

It is responsible for:

* Hash computation (Proof-of-Work)
* Result aggregation
* Building a Merkle Tree based on completed work
* Preparing data for subsequent verification

The Bee Engin Miner can operate:

* in the background
* with resource limitations
* in parallel with the main application logic

#### 2. Mobile Verifiers Miner Subsystem Contracts

This [on-chain contract subsystem](https://github.com/ackinacki/ackinacki/tree/main/contracts/mvsystem) provides:

* Mining rules
* Work validation
* Reward economics
* Extensible logic (reputation, penalties, limits, seasons, etc.)

It:

* Accepts the Merkle Tree generated by the client
* Verifies correctness of computations
* Validates that the work was actually performed
* Distributes rewards (NACKL)
* May take into account reputation, frequency, and client behavior

This part **fully distrusts the client** — only cryptographically provable data is verified.

### Universality

Bee Engine is not tied to any specific application type.

Any application can:

* Run NACKL mining
* Start and stop the mining process
* Obtain verifiable results
* Integrate rewards and reputation into its mechanics

This can be: a game, a web application, a desktop utility, productivity software, any client with computational resources.

{% hint style="info" %}
**This documentation is intended for developers who want to:**

* Integrate Bee Engine into their application
* Understand the Bee Engin Miner and verifier architecture
* Customize mining behavior for their product

In the following section, we will go through the integration scenario in detail.
{% endhint %}


# Bee Engine SDK — Integration Documentation

The page is under development

## Getting Started

This section describes the minimal steps required to integrate **Bee Engine SDK** into your application and start client-side [NACKL](https://docs.ackinacki.com/glossary#nackl) mining.

{% hint style="info" %}
Repository with artifacts is here:\
<https://github.com/gosh-sh/bee-engine>
{% endhint %}

## Integration Overview

Before users can start mining, you must complete the following steps:

1. Application Registration (for Mainnet)
2. Install Bee SDK
3. Integrate into your application (React + Vite example)
4. User Authorization via AN Wallet
5. Work with Bee Engine Miner API

### Step 1. Application Registration

To connect your application to the Bee Engine system:

You must obtain your application identifier in the system: **app\_dapp\_id**.

* At the current stage of development, to obtain it, [please contact us](https://t.me/EugeneDAO) \
  and provide to get it:
  * your App name;
  * App link;
  * link to your logo\
    the image must be preliminarily [converted into webp format](https://squoosh.app/)
* In the future, the developer will:
  * deploy their own application smart contract system in the **Acki Nacki blockchain**
  * retrieve `app_dapp_id`, which will equal the [DAPP ID](https://docs.ackinacki.com/glossary#dapp-id) of the first deployed contract

**Why `app_dapp_id` is required**

This identifier:

* Is required when initializing the Bee Engine Miner
* Is used for public mining key binding inside the [Miner contract](https://github.com/ackinacki/ackinacki/blob/main/contracts/mvsystem/Miner.sol)
* Is necessary for the user to authenticate in the developer’s application

In the example, insert it into the `APP_ID` variable.

**Example:**

```ts
const APP_ID = "your_app_dapp_id_here";
```

### Step 2. Install Bee SDK

Install the SDK via npm:

```bash
npm install @teamgosh/bee-sdk
```

### Step 3. Integration Example (React + Vite)

A minimal integration example is available [in the repository](https://github.com/gosh-sh/bee-engine) :

File: `App.tsx`\
Folder: `miner-react` ([download this folder](https://github.com/gosh-sh/bee-engine/blob/main/examples/javascript/miner-react))

#### This Example Demonstrates:

* Miner initialization
* Starting and stopping mining
* Subscribing to miner events (in progress)
* Using `add_tap()`
* Polling and waiting for mining keys to be propagated in the Miner contract (`ensure_mining_keys_propagated`)
* Retrieving the user’s Miner contract address (`get_miner_address_by_wallet_name`)

It is strongly recommended to use this example as the baseline for your integration.

### Step 4. User Authorization ***(in progress)***

**To enable mining, users must authorize via** [**Acki Nacki Wallet**](https://ackinacki.com/wallet) **(AN Wallet)**.

**Authorization Overview:**

There are two user flows:

1. User already has an Acki Nacki Wallet
2. User does not have an Acki Nacki Wallet ***(in progress)***

#### Flow 1 — User Already Has AN Wallet

If the user already has an **Acki Nacki Wallet**, the authorization process works as follows:

#### 1. Collecting Information from the User

The developer needs to obtain:

* **The AN Wallet name** that the user will use to log in.

{% hint style="info" %}
**The AN Wallet name** is a human-readable identifier that the user chooses when creating the wallet.

The `bee-sdk` abstracts all address-related operations internally, so the developer only needs the wallet name to interact with the system.
{% endhint %}

***

#### 2. Mining Key Generation (Developer Side)

The developer must:

* Generate a **Mining key pair**.

{% hint style="info" %}
Mining keys are cryptographic keys used to sign and submit mining results. These keys are generated by the application developer and are created separately for each application.
{% endhint %}

```ts
const resultOfGenKeys = await gen_mining_keys(APP_ID);
```

The output of the key generation process has the following type:

```
{
  deep_link: string, 
  secret: string
  public: string
}
```

The handling of the `deep_link` is left to the developer’s discretion. It can be implemented either as a connection button to the AN Wallet application or as a QR code that opens the application.

***

#### 3. Operation Confirmation by the User

The user:

* Either scans the QR code
* Or clicks the button from the previous step

This opens the AN Wallet application, where the user is asked to confirm registration in the developer’s application.

If the user confirms:

* The mining keys are written to their Miner contract.

{% hint style="info" %}
Mining keys are not secret. If someone else uses them, they will simply mine on behalf of the key owner.
{% endhint %}

{% hint style="info" %}
After scanning the QR code, the AN Wallet does not return any response
{% endhint %}

***

#### 4. Waiting for Authorization Confirmation (Developer Side)

The developer calls the following function:

```ts
await ensure_mining_keys_propagated({
    client_config: {
      network: {
        endpoints: ENDPOINTS,
      },
    },
    miner_address: minerAddress,
    app_id: APP_ID,
    expected_owner_public: resultOfGenKeys.public,
    max_attempts: 30,
    interval_ms: 1000,
  });
```

The implementation of the function’s result handling is the responsibility of the developer. A successful execution indicates that the user has confirmed authorization in the application. Otherwise, the function will return an error.

{% hint style="info" %}
The developer is responsible for managing and storing the session state after successful authentication.
{% endhint %}

***

#### 5. Additional Verification — First Tap (Developer Side)

For final verification, it is necessary to send the first tap to the Miner contract.\
To do this, use the following function:

```ts
add_tap(x: number, y: number)
```

* The tap is signed with the private mining key.
* The signature must correspond to the public key stored in the Miner contract.

If the Miner contract does not reject the message:

→ The user is indeed the owner of the connected AN Wallet.

***

**As a Result, This Ensures:**

* **A cryptographic binding between the user and the application**
* **A separate mining key pair for each application**
* **Secure authorization without sharing the user’s private wallet keys with the application**

{% hint style="warning" %}

#### AN Wallet Authorization Scope

Authorization through AN Wallet is limited to the wallet scenarios and Mobile Verifiers system (`mvsystem`) processes required by Bee Engine.

Acki Nacki Wallet is not intended for calling arbitrary methods of user contracts, because it operates under the system DAPP ID.

If your application requires users to interact with your smart contracts, deploy your own DAPP and implement that interaction there.\
[DAPP development prerequisites](https://dev.ackinacki.com/#prerequisites)

If you need to call contract methods through a wallet, use Multisig Wallet, which supports sending an ABI-encoded payload as part of a transaction. \
[Deployment guide](https://dev.ackinacki.com/how-to-deploy-a-multisig-wallet)
{% endhint %}

#### Flow 2 — User Does NOT Have AN Wallet ***(in progress)***

#### General Description

The developer independently implements the wallet creation flow for their users in the AN Wallet application.

Additional functionality to support and simplify this flow will be provided in the future.

After the wallet is created, the developer must generate the user’s mining keys and register them in the user’s Miner contract, as described above.

### Limitations

* One wallet can be connected to **no more than 100 applications**
* Exceeding this limit will cause new connections to be rejected

{% hint style="warning" %}

### Important — Mining Rewards Activation

Mining will only generate rewards if the user has activated ecosystem participation.

The user must:

1. Visit one of the official ecosystem applications:
   * [Ludo](https://t.me/ackinackibot/ackinacki_app?startapp=)
   * [Batteries](https://t.me/ackinacki_miner_bot/ackinacki_miner_app?startapp=)
   * [Popits](https://t.me/LudoBidBot/LudoBid?startapp=)
2. Complete the required task
3. Place the first part in the Mambaboard

After activation, the user will start earning mining rewards in your application.\
**This is a required condition. Programmatic initialization of Mamaboard is not supported**
{% endhint %}

### Step 5. Working with the Bee Engine API

Below are the core `bee_engine_miner` methods used to control mining.

#### `can_start() -> bool`

Checks whether mining can be started.

Returns `true` if:

* the Bee Engine Miner is not running
* there is no active mining process
* there are available seeds to work with

⚠️ If you call `start()` without checking and mining is not possible, an error will be thrown.

#### `start(duration_ms: number, callback: (event: object) -> void) -> void`

Starts the mining process for a specified duration.

* `duration_ms` — session duration in milliseconds
* `callback` — function receiving miner events

After starting:

* the Bee Engine Miner begins hashing with reduced difficulty
* events (status, progress, errors) are delivered via callback

#### `add_tap(x: number, y: number) -> void`

Adds a user action (tap) to the Merkle Tree.

Features:

* this hash is computed with increased difficulty
* used to bind user activity to mining
* coordinates `(x, y)` are defined by the application

#### `stop() -> void`

Forcefully stops the Bee Engine Miner.

When called:

* mining is terminated
* results are sent to the contract for validation

If not called, the Bee Engine Miner:

* stops automatically after `duration_ms`
* submits results on its own

#### `get_reward() -> void`

Collects available rewards from previous mining sessions.

Recommendations:

* no need to call more than once per epoch (\~1000 blocks)
* rewards are collected automatically when submitting data to the contract

Use this method if:

* the application has just launched
* you need to explicitly synchronize the user’s balance

#### `polling()`

A special function that:

* polls the mining contract
* waits for the key pair requested by Bee Engine via AN Wallet
* is used to synchronize state during authorization

## What’s Next

After basic integration, you can:

* Start and stop the mining process
* bind `add_tap` to user actions
* use miner events for UI / telemetry
* integrate reputation and economics into your application


# About Acki Nacki SDK

Overview of SDK components

Acki Nacki SDK consists of

* Client Libraries
* CLI

Core TVM-SDK client library is written in Rust, with bindings for other programming languages.

JS/TS guides are present here as reference guides meaning bindings in other languages have the same api calls.

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

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

* [TVM SDK](#tvm-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)
  * [Versioning](#versioning)
  * [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/tvmlabs/tvm-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 TVM Virtual Machine, Transaction Executor, ABI-related functions, BOC manipulation 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, desktop Dapps etc.

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

### Official Javascript(Typescript) binding

Repository: [JavaScript SDK](https://github.com/tvmlabs/tvm-sdk-js)

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

| Platform                       | Package                                                            |
| ------------------------------ | ------------------------------------------------------------------ |
| core package for all platforms | [@tvmsdk/core](https://www.npmjs.com/package/@tvmsdk/core)         |
| Node.js                        | [@tvmsdk/lib-node](https://www.npmjs.com/package/@tvmsdk/lib-node) |
| Web                            | [@tvmsdk/lib-web](https://www.npmjs.com/package/@tvmsdk/lib-web)   |

### Community bindings

| Language | Repository                                                                                                                                                                               |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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> |
| .NET     | [everscale-actions/everscale-dotnet](https://github.com/everscale-actions/everscale-dotnet)                                                                                              |

### 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](/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](/for-binding-developers/json_interface).\
Here you can find directions how to use `json_interface` and write your own binding.

## Use-cases

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

* Create and send messages to blockchain
* Process messages reliably (supports retries and message expiration mechanics)
* Supports TVM Solidity and ABI compatible contracts
* Emulate transactions locally
* Run get methods
* Get account state
* Query blockchain data (blocks, transactions, messages)
* 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 Acki Nacki [Block Keeper node](https://docs.ackinacki.com/glossary#block-keeper-node-bk) or [Block Manager](https://docs.ackinacki.com/glossary#block-manager) node

## Quick Start

Quick Start (Javascript binding)

[Error descriptions](/acki-nacki-sdk/error_codes)

[JavaScript SDK Types and Methods (API Reference)](https://github.com/tvmlabs/tvm-sdk-js)

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

Guides

## Versioning

We aim to follow semver practises, although before the mainnet launch we may introduce breaking changes in any release: patch and minor. Check the CHANGELOG.md file for breaking changes.

## How to avoid Soft Breaking Problems

Soft Breaking is API changes that include only new optional fields in the existing structures. This 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 TVM 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 Mac OS, 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 tvmcli
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 GraphQL endpoint to run on. Such an API is exposed by a Block Manager or Keeper node.

```
TON_USE_SE: true/false - flag defining if tests run against local network (true) or a real network (false)
TON_NETWORK_ADDRESS - Block Keeper addresses separated by comma.
TON_GIVER_SECRET - Sponsor Wallet secret key. If not defined, default Local Network giver keys are used
TON_GIVER_ADDRESS - Address of the Sponsor Wallet to use for prepaying accounts before deploying test contracts. If not defined, the address is calculated using `GiverV2.tvc` and configured public key
```


# Quick Start TVM SDK JavaScript

### **Prerequisites**

* Rust v1.85+
* Node.js v18.19.1
* Python 3
* Python 3 setuptools
* [TVM-CLI and Multisig Wallet](/how-to-deploy-a-multisig-wallet)

**This demo app implements the following scenario:**

1. Creates and initializes an instance of the SDK client.
2. Deploys the `helloWorld` contract:\
   2.1. Generates a key pair for the contract.\
   2.2. Calculates the future address of the contract.\
   2.3. Sends tokens to the future address of the contract, which are required for deployment.\
   2.4. Deploys the `helloWorld` contract.
3. Retrieves account information and prints the balance of the `helloWorld` contract.
4. Runs the account's `get` method `timestamp`.
5. Executes the `touch` method for the newly deployed `helloWorld` contract.
6. Calls the `get` method again to ensure the timestamp has changed.
7. Sends tokens from the `helloWorld` contract to a random account.

{% hint style="info" %}
For testing your developed applications, you can the test network at [`shellnet.ackinacki.org`](https://shellnet.ackinacki.org)

To replenish the balance of the Multisig wallet contract, please contact us in the [Telegram channel](https://t.me/tvmlabs).
{% endhint %}

We will perform all the tasks in this quick start within a separate `~/test-sdk` folder. Let's create it:

```
cd ~
mkdir test-sdk
```

### **Build core TVM library for Node.js**

1. Clone the repository into a separate directory:

```
cd ~/test-sdk
git clone https://github.com/tvmlabs/tvm-sdk-js.git
```

2. Run build:

```
cd tvm-sdk-js/packages/lib-node/build
cargo run
```

As a result, the built binding `tvmsdk.node` will be placed in the folder `~/test-sdk/tvm-sdk-js/packages/lib-node`.

### **Prepare demo application**

1. Clone the repository containing the demo application:

```
cd ~/test-sdk
git clone https://github.com/tvmlabs/sdk-examples.git
cd sdk-examples/js/nodejs/helloWorld
```

2. Configure the Multisig wallet for use in the demo app:

To do this, in the demo folder, edit the `.env` file with the following content:

```
WALLET_ADDRESS=YOUR_MULTISIG_WALLET_ADDRESS
WALLET_KEYS=FULL_PATH_TO_YOUR_MULTISIG_WALLET_KEYS_FILE  # the absolute path must be specified
```

3. Install the `@tvmsdk/core` and `@tvmsdk/lib-node` packages for the demo application:

```
npm install
```

4. Replace the binary file in `@tvmsdk/lib-node` with the Acki Nacki - compatible one that was built earlier:

```
cp ~/test-sdk/tvm-sdk-js/packages/lib-node/tvmsdk.node ~/test-sdk/sdk-examples/js/nodejs/helloWorld/node_modules/@tvmsdk/lib-node/
```

### **Run it**

Go to the folder containing the demo application and run it:

```
cd ~/test-sdk/sdk-examples/js/nodejs/helloWorld
node index.js
```

You will see a result similar to the following:

{% hint style="info" %}
All amounts are specified in nanotokens.
{% endhint %}

```
wallet keys fname: /home/username/wallet/wallet.keys.json
Future address of helloWorld contract is: 0:ef6e287ce266c9ab6bc1190b3bed061bef935796e4a0d659eb28ddcc6f9ecd03
Transferring 2000000000 nanoSHELL tokens from Multisig wallet to 0:ef6e287ce266c9ab6bc1190b3bed061bef935796e4a0d659eb28ddcc6f9ecd03
Success. Tokens were transferred

Deploying helloWorld contract
Success. Contract was deployed

helloWorld balance is 983952999 nanoVMSHELL
Run `timestamp` get method
`timestamp` value is { timestamp: '1736843146' }
Calling `touch` function
Success. TransactionId is: d9c26ef8a0adae234c500d020b298fa600f3e1b8b27758240eff654cd9b85c39

Run `timestamp` get method
Updated `timestamp` value is { timestamp: '1736843151' }
Sending 100000000 nanoSHELL tokens to 0:a088cb42523b9cacf79ca598b9070c160a13674edc8de9c662636caa7969e506
Normal exit
```

### **Source code**

The source code of all the components used can be found [here](https://github.com/tvmlabs/sdk-examples)


# Core Library Reference

This section contains documents describing TVM SDK Types and Methods supported by various [modules](/acki-nacki-sdk/types-and-methods/modules).

* [Module abi](/acki-nacki-sdk/types-and-methods/mod_abi)
* [Module boc](/acki-nacki-sdk/types-and-methods/mod_boc)
* [Module client](/acki-nacki-sdk/types-and-methods/mod_client)
* [Module crypto](/acki-nacki-sdk/types-and-methods/mod_crypto)
* [Module debot](/acki-nacki-sdk/types-and-methods/mod_debot)
* [Module net](/acki-nacki-sdk/types-and-methods/mod_net)
* [Module processing](/acki-nacki-sdk/types-and-methods/mod_processing)
* [Module proofs](/acki-nacki-sdk/types-and-methods/mod_proofs)
* [Module tvm](/acki-nacki-sdk/types-and-methods/mod_tvm)
* [Module utils](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_client) – Provides information about library.

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

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

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

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

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

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

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

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

[tvm\_crc16](/acki-nacki-sdk/types-and-methods/mod_crypto#tvm_crc16) – Calculates CRC16 using TVM algorithm.

[generate\_random\_bytes](/acki-nacki-sdk/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\_tvm\_safe\_format](/acki-nacki-sdk/types-and-methods/mod_crypto#convert_public_key_to_tvm_safe_format) – Converts public key to tvm safe\_format

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[nacl\_box\_open](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_crypto#nacl_secret_box) – Encrypt and authenticate message using nonce and secret key.

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

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

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

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

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

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

[hdkey\_xprv\_from\_mnemonic](/acki-nacki-sdk/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](/acki-nacki-sdk/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](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_crypto#hdkey_secret_from_xprv) – Extracts the private key from the serialized extended private key

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

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

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

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

[get\_crypto\_box\_info](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_crypto#get_crypto_box_seed_phrase) – Get Crypto Box Seed Phrase.

[get\_signing\_box\_from\_crypto\_box](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_crypto#get_encryption_box_from_crypto_box) – Gets Encryption Box from Crypto Box.

[clear\_crypto\_box\_secret\_cache](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_crypto#register_signing_box) – Register an application implemented signing box.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[update\_initial\_data](/acki-nacki-sdk/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](/acki-nacki-sdk/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](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_abi#decode_boc) – Decodes BOC into JSON as a set of provided parameters.

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

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

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

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

[decode\_tvc](/acki-nacki-sdk/types-and-methods/mod_boc#decode_tvc) – Decodes tvc according to the tvc spec. Read more about tvc structure [here](https://github.com/tvmlabs/tvm-sdk/blob/00fd198e4f8f404d5f495c6a65d84b54fe76881b/tvm_struct/src/scheme/mod.rs#L31)

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

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

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

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

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

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

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

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

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

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

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

[cache\_unpin](/acki-nacki-sdk/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](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_boc#get_code_salt) – Returns the contract code's salt if it is present.

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

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

[encode\_state\_init](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_boc#encode_external_in_message) – Encodes a message

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

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

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

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

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

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

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

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

[wait\_for\_transaction](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_processing#process_message) – Creates message, sends it to the network and monitors its processing.

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

[convert\_address](/acki-nacki-sdk/types-and-methods/mod_utils#convert_address) – Converts address from any TVM format to any TVM format

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

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

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

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

### [tvm](/acki-nacki-sdk/types-and-methods/mod_tvm)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[query\_counterparties](/acki-nacki-sdk/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](/acki-nacki-sdk/types-and-methods/mod_net#query_transaction_tree) – Returns a tree of transactions triggered by a specific message.

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

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

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

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

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

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

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


# 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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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/tonlabs/TON-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*](/acki-nacki-sdk/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*](broken://pages/b7U0dxs59ESc6rtN09mV#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*](broken://pages/b7U0dxs59ESc6rtN09mV#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*](broken://pages/b7U0dxs59ESc6rtN09mV#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*](broken://pages/b7U0dxs59ESc6rtN09mV#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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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/tvmlabs/tvm-sdk/blob/00fd198e4f8f404d5f495c6a65d84b54fe76881b/tvm_struct/src/scheme/mod.rs#L31)

[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](#paramsofboccacheget)

ResultOfBocCacheSet

ParamsOfBocCacheUnpin

ParamsOfEncodeBoc

ResultOfEncodeBoc

ParamsOfGetCodeSalt

ResultOfGetCodeSalt

ParamsOfSetCodeSalt

ResultOfSetCodeSalt

ParamsOfDecodeStateInit

ResultOfDecodeStateInit

ParamsOfEncodeStateInit

ResultOfEncodeStateInit

ParamsOfEncodeExternalInMessage

ResultOfEncodeExternalInMessage

ParamsOfGetCompilerVersion

ResultOfGetCompilerVersion

## Functions

### decode\_tvc

Decodes tvc according to the tvc spec. Read more about tvc structure [here](https://github.com/tvmlabs/tvm-sdk/blob/00fd198e4f8f404d5f495c6a65d84b54fe76881b/tvm_struct/src/scheme/mod.rs#L31)

```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 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 `TVM 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 "\~/.tvmclient" for native environments and ".tvmclient" 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 "\~/.tvmclient" for native environments and ".tvmclient" 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.** Acki Nacki endpoint.
* `endpoints`?: *string\[]* – List of Acki NAcki 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*](broken://pages/b7U0dxs59ESc6rtN09mV#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

[tvm\_crc16](#tvm_crc16) – Calculates CRC16 using TVM 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\_tvm\_safe\_format](#convert_public_key_to_tvm_safe_format) – Converts public key to tvm 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)

[ParamsOfTvmCrc16](#paramsoftoncrc16)

[ResultOfTvmCrc16](#resultoftoncrc16)

[ParamsOfGenerateRandomBytes](#paramsofgeneraterandombytes)

[ResultOfGenerateRandomBytes](#resultofgeneraterandombytes)

[ParamsOfConvertPublicKeyToTvmSafeFormat](#paramsofconvertpublickeytotonsafeformat)

[ResultOfConvertPublicKeyToTvmSafeFormat](#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

### tvm\_crc16

Calculates CRC16 using TVM algorithm.

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

type ResultOfTvmCrc16 = {
    crc: number
}

function tvm_crc16(
    params: ParamsOfTvmCrc16,
): Promise<ResultOfTvmCrc16>;

function tvm_crc16_sync(
    params: ParamsOfTvmCrc16,
): ResultOfTvmCrc16;
```

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\_tvm\_safe\_format

Converts public key to tvm safe\_format

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

type ResultOfConvertPublicKeyToTvmSafeFormat = {
    tvm_public_key: string
}

function convert_public_key_to_tvm_safe_format(
    params: ParamsOfConvertPublicKeyToTvmSafeFormat,
): Promise<ResultOfConvertPublicKeyToTvmSafeFormat>;

function convert_public_key_to_tvm_safe_format_sync(
    params: ParamsOfConvertPublicKeyToTvmSafeFormat,
): ResultOfConvertPublicKeyToTvmSafeFormat;
```

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

#### Parameters

* `public_key`: *string* – Public key - 64 symbols hex string

#### Result

* `tvm_public_key`: *string* – Public key represented in TVM 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/tvmlabs/tvm-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, Acki Nacki 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, Acki Nacki 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/tvmlabs/tvm-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/tvmlabs/tvm-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, Acki Nacki 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, Acki Nacki 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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Module for working with debot.

### Functions

[init](#init) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Creates and instance of DeBot.

[start](#start) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Starts the DeBot.

[fetch](#fetch) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Fetches DeBot metadata from blockchain.

[execute](#execute) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Executes debot action.

[send](#send) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Sends message to Debot.

[remove](#remove) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Destroys debot handle.

### Types

[DebotErrorCode](#deboterrorcode)

[DebotHandle](#debothandle) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Handle of registered in SDK debot

[DebotAction](#debotaction) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Describes a debot action in a Debot Context.

[DebotInfo](#debotinfo) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Describes the operation that the DeBot wants to perform.

[Spending](#spending) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Parameters to init DeBot.

[RegisteredDebot](#registereddebot) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Returning values from Debot Browser callbacks.

[ParamsOfStart](#paramsofstart) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Parameters to fetch DeBot metadata.

[ResultOfFetch](#resultoffetch) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md)

[ParamsOfExecute](#paramsofexecute) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Parameters for executing debot action.

[ParamsOfSend](#paramsofsend) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Parameters of `send` function.

[ParamsOfRemove](#paramsofremove) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md)

[AppDebotBrowser](#appdebotbrowser) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Debot Browser callbacks

## Functions

### init

[UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/mod_AppDebotBrowser.md#appdebotbrowser) – [UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Handle of registered in SDK debot

```ts
type DebotHandle = number
```

### DebotAction

[UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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* – Acki Nacki 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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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*](broken://pages/b7U0dxs59ESc6rtN09mV#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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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*](broken://pages/b7U0dxs59ESc6rtN09mV#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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md)

```ts
type ResultOfFetch = {
    info: DebotInfo
}
```

* `info`: [*DebotInfo*](#debotinfo) – Debot metadata.

### ParamsOfExecute

[UNSTABLE](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/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*](broken://pages/b7U0dxs59ESc6rtN09mV#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 Acki Nacki 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*](/acki-nacki-sdk/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 Acki Nacki 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*](/acki-nacki-sdk/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)

```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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/types-and-methods/mod_abi#paramsofencodemessage) – Message encode parameters.
* `send_events`?: *boolean* – Flag for requesting events sending. Default is `false`.
* `responseHandler`?: [*ResponseHandler*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/types-and-methods/mod_tvm#transactionfees) – Transaction fees

### DecodedOutput

```ts
type DecodedOutput = {
    out_messages: DecodedMessageBody | null[],
    output?: any
}
```

* `out_messages`: [*DecodedMessageBody*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/UNSTABLE.md) [DEPRECATED](https://github.com/tvmlabs/tvm-sdk/blob/main/docs/reference/types-and-methods/DEPRECATED.md) Module for proving data, retrieved from TVM API.

### Functions

[proof\_block\_data](#proof_block_data) – Proves that a given block's data, which is queried from TVM API, can be trusted.

[proof\_transaction\_data](#proof_transaction_data) – Proves that a given transaction's data, which is queried from TVM API, can be trusted.

[proof\_message\_data](#proof_message_data) – Proves that a given message's data, which is queried from TVM 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 TVM 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 TVM-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 TestNet 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/tvmlabs/tvm-sdk/blob/main/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 TVM 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 TVM 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 TVM 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 TVM 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*](/acki-nacki-sdk/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `skip_transaction_check`?: *boolean* – Skip transaction check flag
* `boc_cache`?: [*BocCacheType*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `boc_cache`?: [*BocCacheType*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `skip_transaction_check`?: *boolean* – Skip transaction check flag
* `boc_cache`?: [*BocCacheType*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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*](/acki-nacki-sdk/types-and-methods/mod_abi#abi) – Contract ABI for decoding output messages
* `boc_cache`?: [*BocCacheType*](/acki-nacki-sdk/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*](/acki-nacki-sdk/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 TVM format to TVM format

[get\_address\_type](#get_address_type) – Validates and returns the type of any Acki Nacki 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 Acki Nacki format to any Acki Nacki 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 Acki NAcki 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 Acki Nacki address.

Address types are the following

`0:919db8e740d50bf349df2eea03fa30c385d846b991ff5542e67098ee833fc7f7` - standard Acki Nacki 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 TVM. 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 TVM 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 Acki Nacki 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 TVM 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.


# Core Library Error API

SDK Error API

* [TVMClientError](#tvmclienterror)
  * [Properties](#properties)
* [Types](#types)
  * [ErrorData](#errordata)
* [Error example](#error-example)

## TVMClientError

### 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)
* [TVM Virtual Machine Runtime Errors](#tvm-virtual-machine-runtime-errors)
  * [Action phase errors](#action-phase-errors)

## SDK Errors

[Client Error codes (1-99)](https://dev.ackinacki.com/reference/types-and-methods/mod_client#clienterrorcode)

[Crypto Error codes (100-199)](https://dev.ackinacki.com/reference/types-and-methods/mod_crypto#cryptoerrorcode)

[Boc error codes(200-299)](https://dev.ackinacki.com/reference/types-and-methods/mod_boc#bocerrorcode)

[Abi Error codes (300-399)](https://dev.ackinacki.com/reference/types-and-methods/mod_abi#abierrorcode)

[TVM Error codes (400-499)](https://dev.ackinacki.com/reference/types-and-methods/mod_tvm#tvmerrorcode)

[Processing Error codes (500-599)](https://dev.ackinacki.com/reference/types-and-methods/mod_processing#processingerrorcode)

[Net Error Codes (600-699)](https://dev.ackinacki.com/reference/types-and-methods/mod_net#neterrorcode)

[DeBot Error Codes (800-899)](https://dev.ackinacki.com/reference/types-and-methods/mod_debot#deboterrorcode)

## Solidity Runtime Errors

<https://github.com/gosh-sh/TVM-Solidity-Compiler/blob/master/API.md#solidity-runtime-errors>

## TVM Virtual Machine Runtime Errors

`0` TVM terminated successfully

`1` TVM terminated successfully: alternative code

`2` Stack underflow

`3` Stack overflow

`4` Integer overflow

`5` Range check error

`6` Invalid opcode

`7` Type check error

`8` Cell overflow

`9` Cell underflow

`10` Dictionary error

`11` Unknown error

`12` Fatal error

`-14` Out of gas: the contract is either low on gas, or its limit is exceeded

`17` Execution timeout: the transaction execution time limit for the Virtual Machine has been reached.

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


# Acki Nacki VM Instructions

## MINTECC (C726)

Mint any ECC Token

```
Input: ECC KEY
```

Can be invoked only in special contracts.\
[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/a58e859e68e14a17a8acd2f142d260127a0a3f2d/tvm_assembler/src/simple.rs#L840)

## CNVRTSHELLQ (С727)

Converts SHELL to VMSHELL at a 1:1 ratio.

```
Input: amount of nanotokens to convert
```

Q in the end stands for ‘quiet’ which means that if there is not enough Shell, it will not throw an exception.

If the account balance does not have the required number of tokens, the exchange will be made for the entire available amount. That is, `MIN(available_tokens, want_cnt_to_convert)`.\
[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/a58e859e68e14a17a8acd2f142d260127a0a3f2d/tvm_assembler/src/simple.rs#L841)

## MINTSHELL (С728)

Mint some VMSHELL tokens, allowed by available credit in Dapp Config for this Dapp Id

```
Input: amount of nanoVMSHELL to mint
```

[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_assembler/src/simple.rs#L842)

## CALCBKREWARD (С729)

Calculate reward for BK after epoch ended.

```
Input: params of bkroot state:
    uint128 numberOfActiveBlockKeepers,
    uint128 stake,
    uint128 totalStake,
    uint128 reputationTime,
    uint128 timenetwork,
    uint128 epochDuration
```

[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_assembler/src/simple.rs#L843)

## CALCMINSTAKE (С730)

Calculate minstake for BK epoch start.

```
Input: params of bkroot state:
    uint128 epochDuration,
    uint128 timenetwork,
    uint128 numberOfActiveBlockKeepers,
    uint128 numberOfNeededActiveBlockKeeper
```

[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_assembler/src/simple.rs#L844)

## VERGRTH16 (С731)

Verify Groth16 zero-knowledge proof prepared based on JWT token and extra salt password to prove that the user owns some OpenId account (Google, Facebook, Kakao accounts etc). Takes as input the proof, related public input Poseidon hash and index of verification key.

```
Input:
    uint32 vk_index,
    bytes public_inputs, // of length = 32 bytes
    bytes proof // of length = 128 bytes
```

```
Output:
    boolean value indicating if proof is valid or not.
```

Note: public\_inputs must be prepared using POSEIDON instruction.

[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_assembler/src/simple.rs#L845)

## POSEIDON (С732)

Calculate POSEIDON hash function. This hash function is designed for now especially for ZkLogin protocol needs. It takes as input all public ZkLogin data related to OpenId authentication (i.e. some public fields of JWT token and extra public data).

```
Inputs:
    string zkaddr,
    uint256 ephimeral_pub_key,
    bytes modulus,
    uint64 max_epoch,
    string iss_base_64,
    uint8 index_mod_4,
    string header_base_64
```

```
Outputs:
    Poseidon hash (32 bytes array) of input data being sequentially concatenated.
```

Note: There is: zkaddr = Poseidon(JWT.stable\_id, JWT.iss, User salt password), where JWT.stable\_id and User salt password are secrets. ephimeral\_pub\_key is a temporary key that will be used sign transactions (i.e. the related secret key) till Unix timestamp max\_epoch (ephimeral\_pub\_key is embedded into JWT.nonce and JWT is a kind of TLS certificate for ephimeral\_pub\_key). modulus is RSA JWK public fresh modulus published by OpenId provider (the JWK is used to sign JWT tokens). iss\_base\_64, index\_mod\_4 is JWT public data describing OpenId provider. header\_base\_64 is JWT public data containing “kid” (key id) of JWK.\
[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_assembler/src/simple.rs#L846)

## RUNWASM

Instruction allows arbitrary pre-compiled wasm code to be executed directly by the node.

```
Input:
    wasmHash,
    wasmArgs,
    wasmFunction,
    wasmModule,
    wasmBinary
```

\
You can find official documentation [here](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_vm/WASM.md) and example project [here](https://github.com/tvmlabs/tvm-sdk/blob/main/examples/wasm/WASM_EXAMPLES.md)\
[link to the opcode](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_assembler/src/simple.rs#L853)


# Formal Verification

About Formal Verification approach

The formal verification of Block Keeper smart contracts was performed by the [Pruvendo Team](https://pruvendo.com/).

[Learn what formal verification is and find out about Pruvendo's formal verification approach.](https://drive.google.com/file/d/1xcZ5-1uLzTSMFbfHiq-4onhfwSoUWNZ2/view?usp=sharing)<br>


# Acki Nacki VM Instructions Business-Level Specification

Prepared by Pruvendo

<div align="right"><figure><img src="/files/9l2YtHp1ry4oz7icxwkd" alt=""><figcaption></figcaption></figure></div>

## Purpose <a href="#docs-internal-guid-d0a50a9d-7fff-dd98-77a3-5b0f8254351a" id="docs-internal-guid-d0a50a9d-7fff-dd98-77a3-5b0f8254351a"></a>

The purpose of the present document is to create business-level specification (highest-level of specification) for the *Acki Nacki - specific* VM instructions. This document is intended to:

* Be thoroughly reviewed by the Customer
* Act as a base for the high-level specification

## Introduction <a href="#docs-internal-guid-78137ad4-7fff-57d2-2c7a-211e319816cb" id="docs-internal-guid-78137ad4-7fff-57d2-2c7a-211e319816cb"></a>

Being a TVM-based blockchain, [Acki Nacki](https://www.ackinacki.com/) follows its [specification and instruction set](https://ton.org/tvm.pdf). However, some additional instructions are required to support some specific features introduced in Acki Nacki. Such instructions are described in the present document.

## Acki Nacki - specific instructions <a href="#docs-internal-guid-0e3b4765-7fff-ac3e-9f41-1bee55c7cb64" id="docs-internal-guid-0e3b4765-7fff-ac3e-9f41-1bee55c7cb64"></a>

For all the instructions below the current account is taken from *c4* register.

### CNVRTSHELLQ <a href="#docs-internal-guid-d761d100-7fff-0c23-f089-995c4fe6dc01" id="docs-internal-guid-d761d100-7fff-0c23-f089-995c4fe6dc01"></a>

Signature : *`C727`* $$n ( - )$$ , where $$0 \leq n < 2^{256}$$

Brief description: Transforms [*SHELL*](https://docs.ackinacki.com/glossary#shell) into the same amount of [*VMSHELL*](https://docs.ackinacki.com/glossary#vmshell) (using 1:1 ratio)

Input : $$n \bmod 2^{64}$$ - amount of nanotokens to exchange

Behavior:

* If the sender has enough balance of *SHELL*, the required amount of *SHELL*’s are transformed into *VMSHELL*
* Otherwise, the whole balance of *SHELL* is transformed into *VMSHELL*
* In any case the counter of special operations is increased

### MINTECC <a href="#docs-internal-guid-08520189-7fff-5876-be75-74b8ca24319c" id="docs-internal-guid-08520189-7fff-5876-be75-74b8ca24319c"></a>

Signature : *`C726`* $$y \space x ( - )$$, where $$0 \leq x < 256$$, $$0 \leq y < 2^{128}$$

Brief description : mints the required amount of any *ECC* tokens, can be called by a special contract only

Input : $$x$$ - index of *ECC* token, $$y$$ - amount of nanotokens to mint

Behavior:

* If the contract is not **special**, *NOT\_SPECIAL\_CONTRACT* error happens
* If the adding of tokens fails, *OVERFLOW* error happens
* Otherwise:
  * token balance is increased by the specified amount
  * counter of special actions is increased

### MINTSHELL <a href="#docs-internal-guid-23d7310b-7fff-8379-9be7-f9a162b450b1" id="docs-internal-guid-23d7310b-7fff-8379-9be7-f9a162b450b1"></a>

Signature : *`C728`* $$n ( - )$$, where $$0 \leq n < 2^{128}$$

Brief description : mints *SHELL* tokens, up to the specified amount, using the available credit

Input : n - amount of *SHELL* nanotokens to be minted

Behavior:

* In case of *infinite credit*, the specified amount of *SHELL* tokens is minted
* Up to the $$n$$ tokens will be minted, but **Minted shell value** afterwards does not exceed available credit
* **Minted shell value** is increased by the amount of the minted value
* In case of success the counter of special actions is increased

All the values must not exceed $$2^{128}$$.

### CALCBKREWARD <a href="#docs-internal-guid-a5808a80-7fff-2166-ca00-6297d9bee59b" id="docs-internal-guid-a5808a80-7fff-2166-ca00-6297d9bee59b"></a>

Signature : *`C729`* $$r \space s \space \tau \space e \space \varSigma \space n \space a \space (\rho)$$, where:

* $$0 \leq r < 2^{128}$$
* $$0 \leq s < 2^{128}$$
* $$0 \leq \tau < 2^{128}$$
* $$0 \leq e < 2^{128}$$
* $$0 \leq \varSigma < 2^{128}$$
* $$0 \leq n < 2^{128}$$
* $$0 \leq a < 2^{128}$$

Brief description : calculates and returns validator’s reward by the end of each epoch

Input :

* $$r$$ - reputation coefficient
* $$s$$ - stake
* $$\tau$$ - total stake at the epoch start
* $$e$$ - epoch duration
* 𝛴- total amount of minted reward tokens
* $$n$$ - number of active block keepers
* $$a$$ - last calculated reward adjustment

Output : $$\rho$$ - assigned reward

Behavior: it follows [Acki Nacki tokenomics](https://tokenomics.ackinacki.com/tokenomics.pdf):

* $$\varSigma = 0 \rArr \rho = \frac{aer}{10^9n}$$
* $$0\lt\varSigma \lt TOTALSUPPLY \Rightarrow \rho = \frac{a e r s}{10^9 \tau}$$
* $$\varSigma \ge TOTALSUPPLY \Rightarrow \rho =0$$

### CALCMINSTAKE <a href="#docs-internal-guid-f18e0587-7fff-b43e-ba60-86002d69ea5f" id="docs-internal-guid-f18e0587-7fff-b43e-ba60-86002d69ea5f"></a>

Signature : *`C730`* $$v \space n \space t \space s \space (\mu)$$, where:

* $$0 \leq v < 2^{128}$$
* $$0 \leq n < 2^{128}$$
* $$0 \leq t < 2^{128}$$
* $$0 \leq s < 2^{128}$$

Brief description : calculates a minimal deposit for a validator (in nanotokens)

Input:

* $$v$$ - number of needed active blokkeepers (10000)
* $$n$$ - number of active blokkeepers
* $$t$$ - network duration + ⅓ of the preepoch duration
* $$s$$ - total reward amount subtracted by the total slashed amount

Output : $$\mu$$ - minimally allowed stake

Behavior: it follows [Acki Nacki tokenomics](https://tokenomics.ackinacki.com/tokenomics.pdf)

### CALCBKREWARDADJ <a href="#docs-internal-guid-53350c37-7fff-e909-f366-c5f749fef3c0" id="docs-internal-guid-53350c37-7fff-e909-f366-c5f749fef3c0"></a>

Signature: *`C733`* $$t \space a \space p \space r \space s \space (𝛼)$$

All the values must not exceed $$2 ^ {128}$$.

Brief description: adjusts reward engine to be aligned with the theoretical curve.

Input:

* $$t$$ - network time
* $$a$$ - the previous adjustment factor
* $$p$$ - reward period
* $$r$$- average reputation coefficient
* $$s$$ - total reward amount

Output : $$a$$ - new adjustment factor

Behavior: it follows [Acki Nacki tokenomics](https://tokenomics.ackinacki.com/tokenomics.pdf)

### CALCREPCOEF <a href="#docs-internal-guid-74742e9d-7fff-4462-583d-5502648353d8" id="docs-internal-guid-74742e9d-7fff-4462-583d-5502648353d8"></a>

Signature: *`C734`* $$r (c)$$

All the values must not exceed $$2^{128}$$

Brief description: calculates reputation coefficient based on the reputation time.

Input:

* $$r$$ - reputation time

Output : $$c$$ - reputation coefficient

Behavior: it follows [Acki Nacki tokenomics](https://tokenomics.ackinacki.com/tokenomics.pdf)

### Zero-knowledge instructions <a href="#docs-internal-guid-69a99c51-7fff-01b1-0ac6-8c032b755c3f" id="docs-internal-guid-69a99c51-7fff-01b1-0ac6-8c032b755c3f"></a>

One of the common drawbacks of common blockchain systems is a necessity to use seed phrases for authentication. It’s hard to remember them and other (off-chain) approaches such as [OAuth2](https://developers.google.com/identity/protocols/oauth2) that commonly are better in terms or user experience than the former one. The popular solution is to use self-custodial wallets such as [Metamask](https://metamask.io/) or [TON Wallet](https://wallet.ton.org/). Such wallets are often not so transparent as desired and can be vulnerable to attacks (such as the recent [Atomic Wallet case](https://atomicwallet.io/blog/articles/june-3rd-event-statement)).

The provided solution is intended to support popular off-chain authentication systems in blockchain, thus preventing frequent authentication using seed phrases or off-chain wallets, thus combining a high level of security with great user experience.

The solution is based on [Zero-knowledge technology](https://www.rareskills.io/zk-book) and follows the similar solution implemented in [Sui](https://sui.io/) blockchain named *zkLogin* and described [here](https://docs.sui.io/concepts/cryptography/zklogin) in details, with some important exceptions:

1. Salt is not defined by the user, but simply works as a second password
2. [Poseidon](https://www.poseidon-hash.info/) is used as a hash function
3. The [Ceremony](https://docs.sui.io/concepts/cryptography/zklogin#ceremony) process is completely new

The changes are to be described in a separate document.

### VERGRTH16 <a href="#docs-internal-guid-16cbe58b-7fff-dc84-8535-b9ec05dc8e03" id="docs-internal-guid-16cbe58b-7fff-dc84-8535-b9ec05dc8e03"></a>

Verifies the proofs using Groth16 algorithm

Signature : *`C731`* $$\pi \space \rho \space i \space (b)$$, where:

* $$\rho \isin TvmSlice$$
* $$d \isin TvmSlice$$
* $$0 \leq i < 2^{32}$$
* $$b \isin B$$

Brief description : checks [zk-Snark](https://z.cash/learn/what-are-zk-snarks/) proof, returning the logical result

Input:

* $$\pi$$ - *slice is public inputs*
* $$\rho$$ - proof (in terms of zk-Snark)
* $$i$$ - algorithm used, where:
  * *0* - unsecure algorithm
  * *1* - secure algorithm
  * *anything else* - test algorithm

Output:

* $$b$$ - boolean value that indicates if the verification was correct or not

Behavior is as follows:

1. $$\pi$$ and $$\rho$$ are decoded into corresponding arrays of bytes
2. proofs then decoded into array of `Proof<Bn254>` structures, using external function
3. public inputs, in their turn, are decoded into *array* of *Fr* (where $$Fr = \lbrace 0, ..., 2^{256} -1 \rbrace$$)\
   using:\
   a. external methods for deserialization to the array of `FieldElementWrapper`\
   b. wrapping by the first element
4. Depending on $$i$$, selected the predefined set of verifying keys - **unsecure, secure** or **test**
5. External function with data calculated at steps 2-4 is called to verify the proofs using **Groth16** algorithm

### POSEIDON <a href="#docs-internal-guid-3f5e4e8d-7fff-fbe5-f625-82858221accf" id="docs-internal-guid-3f5e4e8d-7fff-fbe5-f625-82858221accf"></a>

Calculates Poseidon hash.

Signature : *`C732`* $$i \space m \space p \space \mu \space s \space h \space z \space (\pi)$$, where:

* $$0 \leq i < 256$$
* $$0 \leq m < 2^{64}$$
* $$0 \leq p < 2^{256}$$
* $$\mu \isin TvmSlice$$
* $$s \isin TvmSlice$$
* $$h \isin TvmSlice$$
* $$z \isin TvmSlice$$
* $$\pi \isin TvmCell$$

Input:

* $$z$$ - [zk-address](https://docs.sui.io/concepts/cryptography/zklogin#will-my-zklogin-address-ever-change)
* $$h$$ - JWT header (base64)
* $$s$$ - *iss* (provider’s name) (base64)
* $$\mu$$ - modulus
* $$p$$ - ephemeral public key
* $$m$$ - maximum epoch
* $$i$$ - key index

Output:

* $$\pi$$ - array of public input as a cell

Behavior:

1. Initially:
   1. $$z$$ is transformed into a string (*z-string*)
   2. $$h$$ is transformed into a *base64* string (*h-string*)
   3. $$s$$ is transformed into a *base64* string (*s-string*)
   4. $$\mu$$ is transformed into array of bytes (*𝜇-array*)
   5. $$p$$ is transformed into a byte array with proper number of bytes, extra bytes are dropped, in case of lack of bytes exception must be raised
   6. $$m$$ is transformed into *u64* (*m64*)
   7. $$i$$ is transformed into a *base64* string (*i-string*)
2. Then:
   1. $$z-string$$ is transformed into big number using an external function
   2. $$h-string$$ is transformed into big number using an external function
   3. $$s-string$$ is transformed into big number using an external function
   4. $$\mu -array$$ is transformed into big number using an external function
   5. $$p-string$$ is split into two big numbers using external function
   6. $$m64$$ is transformed into a string and then, to big number using an external function
   7. $$i-string$$ is transformed into big number using an external function
3. Then, an array of public inputs is created using a call of external functions
4. Finally, the list is serialized into a cell and push into a stack


# GraphQL Quick Start

Let's start with observing API playground of Acki Nacki testnet <https://shellnet.ackinacki.org/graphql>.

Learn how to read API documentation in the playground.

Then move to making an api request with curl.

And integrate it with TVM SDK.

## Playground

Go to <https://shellnet.ackinacki.org/graphql>

Insert this query in the left part.

```graphql
query{
blockchain{
    account(address:"0:1111111111111111111111111111111111111111111111111111111111111111"){
      info{
        balance(format:DEC)
        address
      }
    }
  }
}
```

Now click play button and you will see the result:

## Documentation

Click on the button "book" in the upper left corner of the screen. You will see the API documentation with all available fields.

## Request with curl

```
curl --location --request POST https://shellnet.ackinacki.org/graphql \
--header 'Content-Type: application/json' \
--data-raw '{"query":"query($address: String!){\n  blockchain{\n    account(address:$address){\n      info{\n        balance(format:DEC)\n      }\n    }\n  }\n}","variables":{"address":"0:ee150cacfc7508f522dbd9bd6c705238ef316b324244843eea3e81e35ae2a962"}}'
```

## Request with SDK (JavaScript)

```javascript
const {TvmClient} = require("@tvmsdk/core");
const {libNode} = require("@tvmsdk/lib-node");

TvmClient.useBinaryLibrary(libNode)

const client = new TvmClient({
    network: {
        endpoints: [
            "https://shellnet.ackinacki.org/graphql"
        ],
    },
});

(async () => {
    try {
        // Get account balance. 
        const query = `
            query {
              blockchain {
                account(
                  address: "${address}"
                ) {
                   info {
                    balance(format: DEC)
                  }
                }
              }
            }`
        const {result}  = await client.net.query({query})
        console.log(`The account balance is ${result.data.blockchain.account.info.balance}`);
        client.close();
    }
    catch (error) {
        console.error(error);
    }
}
)()
```


# Blockchain API

`blockchain` root type is API that includes such basic real-time data as:

* blocks
* transactions
* account data
  * account info
  * account transactions
  * account messages

This API is natively Graph-oriented API .

We followed GraphQL best practices and implemented Relay Cursor Connections Specification for pagination for all lists. You can read more here <https://relay.dev/graphql/connections.htm>


# Info API

Info query is used to get API version, as well as health parameters of the API, such as latency of blocks, messages and transactions

```graphql
query{
  info{
    version # API version
  }
}
```


# Web Playground

**Test your queries and explore blockchain data**

GraphQL web playground is available for each network at its root endpoint URL.

Use the playground to explore documentation and test your queries.

Go to <https://shellnet.ackinacki.org/graphql>

<figure><img src="/files/Iw7AaoLuLSkh7KBL1Rp5" alt=""><figcaption></figcaption></figure>


# GraphQL API Examples


# Connect to GraphQL API

### HTTPS

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request POST https://shellnet.ackinacki.org/graphql \
--header 'Content-Type: application/json' \
--data-raw '{"query":"query{\n  blockchain{\n    blocks(last:1){\n      edges{\n        node{\n          hash\n          seq_no\n        }\n      }\n    }\n  }\n}","variables":{}}'
```

{% endtab %}

{% tab title="tvm-sdk-js" %}

```javascript
const {TvmClient} = require("@tvmsdk/core");
const {libNode} = require("@tvmsdk/lib-node");

TvmClient.useBinaryLibrary(libNode)

const client = new TvmClient({
    network: {
        endpoints: [
            "endpoint"
        ],
    },
});

(async () => {
    try {
        queryString = `
            query{
                blockchain{
                blocks(last:1){
                    edges{
                    node{
                        hash
                        seq_no
                    }
                    }
                }
                }
            }
        `
        let {seq_no, hash} = (await client.net.query({ 
            "query": queryString }))
        .result.data.blockchain.blocks.edges[0].node;
        console.log("The last masterchain block seqNo is " + seq_no+ '\n' + "the hash is" + hash);
        client.close();
}
    catch (error) {
            console.error(error);
    }
}
)()
```

{% endtab %}

{% tab title="JS fetch" %}

```javascript
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var graphql = JSON.stringify({
  query: "query{\n  blockchain{\n    blocks(last:1){\n      edges{\n        node{\n          hash\n          seq_no\n        }\n      }\n    }\n  }\n}",
  variables: {}
})
var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: graphql,
  redirect: 'follow'
};

fetch("endpoint", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
```

{% endtab %}

{% tab title="Postman" %}

```
URL: endpoint
Body: GraphQL
Query:

query{
  blockchain{
    blocks(last:1){
      edges{
        node{
          hash
          seq_no
        }
      }
    }
  }
}
```

{% endtab %}
{% endtabs %}

In the next section find out how to work with GraphQL Web playground and easily explore blockchain data with it.


# Send message


# Retrieve all blocks, transactions, events

## Blocks pagination

### Get finalized timestamp

As the API is eventually consistant before starting pagination we need to limit the pagination range by the finalized timestamp (timestamp that guarantees that there is not missed objects before it).

```
query{
    blockchain{
        finalized_timestamp
    }
}
```

### What is сhain\_order?

Because Acki Nacki blockchain dynamically splits and merges it is not possible to follow one chain seqno to sequentially retrieve all the blocks.

We added a unique index for blocks to paginate them across all the threads: `chain_order`

```
chain_order = block-timestamp-in-seconds + 
                placeholder-for-future-purposes +
                thread_id + height
```

Each value should be converted to hex string and prefixed with \<string size -1>.

For example:

chain\_order=`7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0`, where

`7698320d0` (8-length of timestamp, timestamp value = 1770201296 or Wednesday, 4 February 2026 10:34:56

`00` - placeholder value for future usage with value 0 and length=1-1=0

`6700000000000000000000000000000000000000000000000000000000000000000000` - thread \`00000000000000000000000000000000000000000000000000000000000000000000 , length 68-1=67

`61d4b1c0` - height=30716352, length 7-1=6

### Paginate by blocks within timestamp range <a href="#paginate_by_seqno" id="paginate_by_seqno"></a>

Pagination parameters:

```
master_seq_no_range:{
    start: 1770201296 # start timestamp
    end: 1770204896 # end timestamp <=finalized_timestamp !!!
 }
```

`after,before` - specify chain\_order/cursor field here

Here we continue pagination within timestamp range and ask for the next 3 blocks after the last cursor in the previous query. We see that the next page exists so we can continue paginating within the same timestamp range.

```graphql
query{
  blockchain{
    blocks(
      master_seq_no_range:{
        start: 1770201296
        end: 1770204896
      }
      after:"7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0"
      first:3
    ){
      edges{
        node{
          id
          tr_count
          chain_order
        }
        cursor        
      }
      pageInfo{
        startCursor
        endCursor
        hasNextPage
      }
    }
  }
}
```

Result:

```
{
  "data": {
    "blockchain": {
      "blocks": {
        "edges": [
          {
            "node": {
              "id": "a040869b8cbeaeb7ab4b189e492d4fbd4b58e2694a618e2b5804b531c7644b5e",
              "tr_count": 16,
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0"
            },
            "cursor": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0"
          },
          {
            "node": {
              "id": "2be70019c807dfebcdee35b1972a59d30b5176097d0c20040c4a0303a7148140",
              "tr_count": 14,
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c1"
            },
            "cursor": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c1"
          },
          {
            "node": {
              "id": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c2",
              "tr_count": 18,
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c2"
            },
            "cursor": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c2"
          }
        ],
        "pageInfo": {
          "startCursor": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0",
          "endCursor": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c2",
          "hasNextPage": true
        }
      }
    }
  }
}
```

You can see cursor field in each edge object is same as cursor (because chain\_order plays the role of cursor), which can be passed over to the next query for pagination. Get the latest cursor for the page in `PageInfo.endCursor` field.

### Query all transactions/calls/internal transfers/events within block

{% hint style="info" %}
**Calls** in Acki Nacki are incoming messages attached to the transaction in transaction.in\_message object with msg\_type=0

**Internal transfers** are incoming(in\_message) and outgoing messages (out\_messages) of the transaction with msg\_type=1

**Events** are outgoing messages (out\_messages) of transaction with msg\_type=2
{% endhint %}

1. Get the required block's chain\_order. For example chain\_order = "`7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0`"
2. Calculate chain\_order for the block with height = height+1. You can write your own code or use this JS script as an example - that parses chain\_order, adds 1 to height and encodes it back.

```js
function isHexChar(ch) {
  return (
    (ch >= "0" && ch <= "9") ||
    (ch >= "a" && ch <= "f") ||
    (ch >= "A" && ch <= "F")
  );
}

function readDecimalPrefix(s, pos) {
  if (pos >= s.length || s[pos] < "0" || s[pos] > "9") {
    throw new Error(`Expected decimal prefix at position ${pos}`);
  }
  let end = pos;
  while (end < s.length && s[end] >= "0" && s[end] <= "9") end++;
  const prefixStr = s.slice(pos, end);
  const valueLen = Number(prefixStr) + 1; // hex chars
  return { valueLen, nextPos: end };
}

function readHexPayload(s, pos, len) {
  const end = pos + len;
  if (end > s.length) throw new Error(`Payload overruns string at position ${pos}`);
  const payload = s.slice(pos, end);
  for (let i = 0; i < payload.length; i++) {
    if (!isHexChar(payload[i])) {
      throw new Error(`Non-hex char at position ${pos + i}`);
    }
  }
  return { payload: payload.toLowerCase(), nextPos: end };
}

function parseChainOrder(chainOrder) {
  const s = chainOrder.trim();
  let pos = 0;

  const a = readDecimalPrefix(s, pos);
  const ts = readHexPayload(s, a.nextPos, a.valueLen);
  pos = ts.nextPos;

  const b = readDecimalPrefix(s, pos);
  const ph = readHexPayload(s, b.nextPos, b.valueLen);
  pos = ph.nextPos;

  const c = readDecimalPrefix(s, pos);
  const tid = readHexPayload(s, c.nextPos, c.valueLen);
  pos = tid.nextPos;

  const d = readDecimalPrefix(s, pos);
  const ht = readHexPayload(s, d.nextPos, d.valueLen);
  pos = ht.nextPos;

  if (pos !== s.length) throw new Error(`Trailing data after ${pos}`);

  return {
    timestampHex: ts.payload,
    placeholderHex: ph.payload,
    threadIdHex: tid.payload,
    threadHeightHex: ht.payload,
  };
}

function encodeField(hexPayload) {
  const v = hexPayload.toLowerCase().replace(/^0x/, "");
  return String(v.length - 1) + v;
}

function incrementThreadHeight(chainOrder) {
  const p = parseChainOrder(chainOrder);

  const oldHeight = BigInt("0x" + p.threadHeightHex);
  const newHeightHex = (oldHeight + 1n).toString(16); // no pad

  return (
    encodeField(p.timestampHex) +
    encodeField(p.placeholderHex) +
    encodeField(p.threadIdHex) +
    encodeField(newHeightHex)
  );
}

/* === Your example === */
const example =
  "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0";

console.log(incrementThreadHeight(example));
// -> 7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c1
```

3. Paginate all transactions for the block with chain\_order = "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0"

```graphql
query{
  blockchain{
    transactions(after:"7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c0", before:"7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c1" first:5){
      edges{
        node{
          now
          block_id
          id
          chain_order
          in_message{
            src
            value
            msg_type
          }
          out_messages{
            dst
            value
            msg_type
          }
          total_fees
          aborted
        }
      }
      pageInfo{
        startCursor
        endCursor
      }
    }
  }
}
```

The result:

```
{
  "data": {
    "blockchain": {
      "transactions": {
        "edges": [
          {
            "node": {
              "now": 1770181201,
              "block_id": "8f600f3cf187f89d4f1d89398edaa81a8666881aaaa02a0dd0c9654f52c1a8f6",
              "id": "0b340f91708e711e616da2d117a724e8650208b1c346feff85117dec7e25f86a",
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c001",
              "in_message": {
                "src": "",
                "value": null,
                "msg_type": 1
              },
              "out_messages": [],
              "total_fees": "0x9a28d8",
              "aborted": false
            }
          },
          {
            "node": {
              "now": 1770181201,
              "block_id": "8f600f3cf187f89d4f1d89398edaa81a8666881aaaa02a0dd0c9654f52c1a8f6",
              "id": "6a14a13a0170ddccd03b5dd889b4c9a20f33442ac35a37d83dc672e44029f905",
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c002",
              "in_message": {
                "src": "",
                "value": null,
                "msg_type": 1
              },
              "out_messages": [],
              "total_fees": "0x98a238",
              "aborted": false
            }
          },
          {
            "node": {
              "now": 1770181201,
              "block_id": "8f600f3cf187f89d4f1d89398edaa81a8666881aaaa02a0dd0c9654f52c1a8f6",
              "id": "188c575a3665d9831147c61b924665466b44d533768d01e5e35b0bb6791d28f5",
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c003",
              "in_message": {
                "src": "0:27da272e789e604aaff3cc4f23c85319366e9c02592b285609b18dd5144cd2bd",
                "value": "0x5f5e100",
                 "msg_type": 0
              },
              "out_messages": [
                {
                  "dst": "0:27da272e789e604aaff3cc4f23c85319366e9c02592b285609b18dd5144cd2bd",
                  "value": "0x5f5e100",
                   "msg_type": 0
                }
              ],
              "total_fees": "0x62eec3",
              "aborted": false
            }
          },
          {
            "node": {
              "now": 1770181201,
              "block_id": "8f600f3cf187f89d4f1d89398edaa81a8666881aaaa02a0dd0c9654f52c1a8f6",
              "id": "a20cff059c4e2915ae232c46af8164136efcd8cae2b041598542a78d7ced355c",
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c004",
              "in_message": {
                "src": "0:c91685cb50b74ae16e4c1fb896fc5e924da72bd7136ecae7a62fb0683128abec",
                "value": "0x5f5e100"
              },
              "out_messages": [
                {
                  "dst": "0:7e87112fc59c0e83812c411e714cc3f0f989c786b8f24126be275625775efc18",
                  "value": "0x5f5e100",
                  "msg_type": 0
                }
              ],
              "total_fees": "0x216568",
              "aborted": false
            }
          },
          {
            "node": {
              "now": 1770181201,
              "block_id": "8f600f3cf187f89d4f1d89398edaa81a8666881aaaa02a0dd0c9654f52c1a8f6",
              "id": "3e7e2c92ea8bb3994dd35927290aec35978c6b4d996c8cfe93bf1ebf97258194",
              "chain_order": "7698320d000670000000000000000000000000000000000000000000000000000000000000000000061d4b1c005",
              "in_message": {
                "src": "0:27da272e789e604aaff3cc4f23c85319366e9c02592b285609b18dd5144cd2bd",
                "value": "0x5f5e100",
                "msg_type": 0
              },
              "out_messages": [],
              "total_fees": "0x26ba100",
              "aborted": false
            }
          }
        ],
        "pageInfo": {
          "startCursor": "76982d251000161d3c69201",
          "endCursor": "76982d251000161d3c69205"
        }
      }
    }
  }
}
```


# Account queries

## Get account info

To get account info **including its state (BOC), data and code**, use the following GraphQL query:

<pre class="language-graphql"><code class="lang-graphql"><strong>query {
</strong>  blockchain{
   account(address:"0:653b9a6452c7a982c6dc92b2da9eba832ade1c467699ebb3b43dca6d77b780dd"){
    info{
      address
      acc_type
      balance
      last_paid
      last_trans_lt
      boc
      data
      code
      library
      data_hash
      code_hash
      library_hash
    }
  }
  }
}
</code></pre>

Result:

```graphql
{
  "data": {
    "blockchain": {
      "account": {
        "events": {
          "edges": [
            {
              "node": {
                "msg_id": "541be3a1be3224687158d9dcd39f313ffcb1d03d5428b2a7f51d702b177755d2",
                "body": "te6ccgEBAQEAOAAAayoqI7SAFmHd/5cK3iZgSQPbLrz9F5UkzXuik7iu9XDZGTVWJFFAAAAAAAAAAAAAAAAAAATiEA==",
                "created_at": 1775532241
              },
              "cursor": "769d478d100670000000000000000000000000000000000000000000000000000000000000000000062bc501a12102"
            },
            {
              "node": {
                "msg_id": "11ea69af1314ff8c77cb82d6bf020928a15b0bc2c1505a25b5f65b339b60e194",
                "body": "te6ccgEBAQEAOAAAayoqI7SAFJMDNXNXk8vxpapdbJTHe2M1weAqWxceYB4zXilZqp1gAAAAAAAAAAAAAAAAADDUEA==",
                "created_at": 1775547492
              },
              "cursor": "769d4b46400670000000000000000000000000000000000000000000000000000000000000000000062bcff350302"
            }
          ],
          "pageInfo": {
            "hasNextPage": false
          }
        }
      }
    }
  }
}
```

## Get transactions within timestamp range

### Use-cases

* Paginate transactions to get both transactions and messages of account within the required timestamp range
* Collect account transactions with detailed fees information
* Collect account balance history by pre-processing `balance_delta` changes on your side
* Query new account transactions to trigger some logic on your side
* Optionally filter transactions by `Aborted` type or `balance_delta` value
* Pull transactions for a period if your websocket subscription failed (use last`Transaction.chain_order` field as `after` cursor ;-) )

### Filter parameters

You can filter account transactions by these parameters:

```graphql
aborted: Boolean
min_balance_delta: String
max_balance_delta: String
```

### Pagination parameters

Use `cursor`, {`first`, `after`} or {`last`, `before`} filters for pagination.

{% hint style="success" %}
We followed GraphQL best practices and implemented Relay Cursor Connections Specification for pagination for all list types. You can read more here <https://relay.dev/graphql/connections.htm>
{% endhint %}

Let's paginate some account transactions from the very first one:

```graphql
query {
  blockchain{
   account(address:"0:653b9a6452c7a982c6dc92b2da9eba832ade1c467699ebb3b43dca6d77b780dd"){
    transactions
    {
      edges{
        node{
          hash
          in_message{
            hash
            value
            body
          }
          out_messages{
            hash
            value
            body
          }
          
        }
      }
      pageInfo{
        endCursor
        hasNextPage
      }
    }
  }
  }
}
```

Result

```graphql
{
  "data": {
    "blockchain": {
      "account": {
        "transactions": {
          "edges": [
            {
              "node": {
                "hash": "c8153cd353bf90c7c1214d8c1a50a30ea6d0d900f0f6c7242d1434644c1e49fb",
                "hash": "c8153cd353bf90c7c1214d8c1a50a30ea6d0d900f0f6c7242d1434644c1e49fb",
                "in_message": {
                  "hash": "c2b064872a2ce6db65ca724a03d1be5de37abe784c658ef4d5998249b9643144",
                  "value": "0x229bd2a5eb3ef4",
                  "body": null
                },
                "out_messages": []
              }
            },
            ...
          ],
          "pageInfo": {
            "endCursor": "5286af50052a33e50104",
            "hasNextPage": true
          }
        }
      }
    }
  }
}
```

Use `endCursor` field for further pagination and `hasNextPage` for identifying if more records exist.

## Get messages within timestamp range

Use-cases:

* get transfers that some account sent or received
* get account's events
* get external calls of an account
* get transfers between an account and some counterparty account
* get account events to an external address
* optionally filter messages by value amount
* Pull messages for a period if your websocket subscription failed (use Message`.chain_order` field as `after` cursor ;-) )

In all these cases you need to paginate account messages with some filters applied. Lets see how to do it.

### Filter parameters

You can filter messages by these parameters:

```graphql
master_seq_no_range: {start: Timestamp, end: Timestamp} # Time interval for pagination
counterparties: [String!]
msg_type: [BlockchainMessageTypeFilterEnum!]
min_value: String

enum BlockchainMessageTypeFilterEnum {
    ExtIn #    External inbound
    ExtOut #    External outbound
    IntIn #    Internal inbound
    IntOut #    Internal outbound
}
```

### Pagination parameters

Use `cursor`, {`first`, `after`} or {`last`, `before`} filters for pagination.

{% hint style="success" %}
We followed GraphQL best practices and implemented Relay Cursor Connections Specification for pagination for all list types. You can read more here <https://relay.dev/graphql/connections.htm>
{% endhint %}

### Account transfers

Lets get first 2 transfers some account received or sent. So we need to get incoming and outcoming internal messages. We separated `internal` message type into 2 types: `IntIn` and `IntOut` for search convenience. This way it is possible also to get only deposits, and only withdrawals.

```graphql
query{
  blockchain{
    account(address:"-1:99392dea1c5035feddb1bb3db9e71138d82868f7460c6da3dca26f0520798ebd"){
      messages(msg_type:[IntIn, IntOut],first:2){
        edges{
          node{
            src
            dst
            id
            hash
            value(format:DEC)
            msg_type
            created_at_string
          }
          cursor
        }
        pageInfo{
          hasNextPage
        }
      }
    }
  }
}
```

Result. We see that the next page exists, we can continue pagination.

```graphql
{
  "data": {
    "blockchain": {
      "account": {
        "messages": {
          "edges": [
            {
              "node": {
                "src": "0:7db5e456a7c41306c23c588fb0561fe63443a6f17d7e2a08672369636980678f",
                "dst": "-1:99392dea1c5035feddb1bb3db9e71138d82868f7460c6da3dca26f0520798ebd",
                "id": "message/a74d826adf7f00153e034e1ee4de4f6e5a38843ee8d14c744bfcbf3c0df9f73d",
                "hash": "a74d826adf7f00153e034e1ee4de4f6e5a38843ee8d14c744bfcbf3c0df9f73d",
                "value": "1090000000",
                "msg_type": 0,
                "created_at_string": "2021-07-17 21:08:16.000"
              },
              "cursor": "59876bem0400"
            },
            {
              "node": {
                "src": "-1:99392dea1c5035feddb1bb3db9e71138d82868f7460c6da3dca26f0520798ebd",
                "dst": "-1:3333333333333333333333333333333333333333333333333333333333333333",
                "id": "message/ead06f194b988c1658215e178e68522f27cc018df1830bcfe779d9b9ce7fee93",
                "hash": "ead06f194b988c1658215e178e68522f27cc018df1830bcfe779d9b9ce7fee93",
                "value": "1000000000",
                "msg_type": 0,
                "created_at_string": "2021-07-17 21:08:24.000"
              },
              "cursor": "59876bem0401"
            }
          ],
          "pageInfo": {
            "hasNextPage": true
          }
        }
      }
    }
  }
}
```

### Account events

To get account events run this query.

```graphql
query {
  blockchain {
    account(
      address: "0:1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a"
    ) {
      events(
        dst: ":0000000000000000000000000000000000000000000000000000000000000267"
        last: 2
      ) {
        edges {
          node {
            msg_id
            body
            created_at
          }
          cursor
        }
        pageInfo {
          hasNextPage
        }
      }
    }
  }
}
```

Result

```graphql
{
  "data": {
    "blockchain": {
      "account": {
        "events": {
          "edges": [
            {
              "node": {
                "msg_id": "541be3a1be3224687158d9dcd39f313ffcb1d03d5428b2a7f51d702b177755d2",
                "body": "te6ccgEBAQEAOAAAayoqI7SAFmHd/5cK3iZgSQPbLrz9F5UkzXuik7iu9XDZGTVWJFFAAAAAAAAAAAAAAAAAAATiEA==",
                "created_at": 1775532241
              },
              "cursor": "769d478d100670000000000000000000000000000000000000000000000000000000000000000000062bc501a12102"
            },
            {
              "node": {
                "msg_id": "11ea69af1314ff8c77cb82d6bf020928a15b0bc2c1505a25b5f65b339b60e194",
                "body": "te6ccgEBAQEAOAAAayoqI7SAFJMDNXNXk8vxpapdbJTHe2M1weAqWxceYB4zXilZqp1gAAAAAAAAAAAAAAAAADDUEA==",
                "created_at": 1775547492
              },
              "cursor": "769d4b46400670000000000000000000000000000000000000000000000000000000000000000000062bcff350302"
            }
          ],
          "pageInfo": {
            "hasNextPage": false
          }
        }
      }
    }
  }
}
```

Then, by decoding the \`body\` of that message you can obtain the data attached to the event.\
You can parse it with SDK function [`abi.decode_message_body`](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_abi#decode_message_body) or use tvm-cli comand:\
For example:

```
tvm-cli decode body te6ccgEBAQEAOAAAayoqI7SAFmHd/5cK3iZgSQPbLrz9F5UkzXuik7iu9XDZGTVWJFFAAAAAAAAAAAAAAAAAAATiEA== --abi ./contracts/0.79.3_compiled/exchange/Exchange.abi.json
```

As a result, you will get something approximately like this:

```
Input arguments:
    body: te6ccgEBAQEAOAAAayoqI7SAFmHd/5cK3iZgSQPbLrz9F5UkzXuik7iu9XDZGTVWJFFAAAAAAAAAAAAAAAAAAATiEA==
     abi: ./contracts/0.79.3_compiled/exchange/Exchange.abi.json


UsdcMigrated: {
  "from": "0:b30eeffcb856f13302481ed975e7e8bca9266bdd149dc577ab86c8c9aab1228a",
  "value": "10000"
}
Signature: None
Header: null
FunctionId: 9981240F
```

### Account external calls

If you want to collect external calls of an account, filter by msg\_type = `ExtIn`. `Body` field contains ABI-encoded information with Event data. You can parse it with SDK function [`abi.decode_message_body`](https://docs.everos.dev/ever-sdk/reference/types-and-methods/mod_abi#decode_message_body). Lets get the last external call:

```graphql
query{
  blockchain{
    account(address:"0:3d10c4d6dfc5d3cf6f8ac3d7468b792b91385c087da8f59669569493c7c0e28e"){
      messages(msg_type:[ExtIn],last:1){
        edges{
          node{
            hash
            body
            created_at_string
          }
          cursor
        }
        pageInfo{
          hasPreviousPage
        }
      }
    }
  }
}
```

Result

```graphql
{
  "data": {
    "blockchain": {
      "account": {
        "messages": {
          "edges": [
            {
              "node": {
                "hash": "3ebc5a30f598825a015b99048b3f9baeb1d60818aa77ec6ceb3b84254e649723",
                "body": "te6ccgEBAQEAewAA8cb04wBQrr+dL/xBeDVKUIHJpF+ixQ9vsl7rIu8BtyRr72MIA9l87nY/maACAjMiwTkNeYlx+Vm3AtMvU000ZYXOo+U6Dh8fZKMrMO68do6VqlWYBXM3BEnQiVL3dDmtSMAAAGABANbS2JO2i4ap0DtYk7XgW5WzcGA=",
                "created_at_string": "2022-04-07 12:32:53.000"
              },
              "cursor": "5f7bcee00615d8d7711c0000"
            }
          ],
          "pageInfo": {
            "hasPreviousPage": true
          }
        }
      }
    }
  }
}
```


# Messages

## Get message info by hash

```graphql
query{
  blockchain{
    message(hash:"f19c40cc408a453c76417fcae8afc48407abf31610b295f4bb1039cb4d13a7f4"){
      id
      hash
      value
      src
      dst
      # check other available fields in the schema in playground
    }
  }
}
```

Result

```graphql
{
  "data": {
    "blockchain": {
      "message": {
        "id": "message/f19c40cc408a453c76417fcae8afc48407abf31610b295f4bb1039cb4d13a7f4",
        "hash": "f19c40cc408a453c76417fcae8afc48407abf31610b295f4bb1039cb4d13a7f4",
        "value": null,
        "src": "",
        "dst": "-1:8888888888888888888888888888888888888888888888888888888888888888"
      }
    }
  }
}
```


# ABI Specification

ABI specifies message bodies layout for client to contract and contract to contract interaction.

## Introduction

In Acki Nacki client to contract and contract to contract interaction occurs through external and internal messages respectively.

ABI specification describes the structure of body of these messages. ABI stored as JSON serves as an interface for smart contracts and is used when calling contract methods externally or on-chain.

The goal of the ABI specification is to design ABI types that are cheap to read to reduce gas consumption and gas costs. Some types are optimized for storing without write access.

## Message body

### External Inbound Messages

Message body with encoded function call has the following format:

`Maybe(Signature)` + `Enc(Header)` +`Function ID` + `Enc(Arguments)`

First comes an optional signature. It is prefixed by one bit flag that indicates the signature presence. If it is `1`, then in the next `512 bit` a signature is placed, otherwise the signature is omitted.

Then comes the encoded header parameters set (same for all functions).

It is followed by ***32 bits*** of function ID identifying which contract functions are called. The `function ID` comes within the first `32 bits` of the `SHA256` hash of the function signature.

The highest bit is set to `0` for function ID in external inbound messages, and to `1` for external outbound messages.

Function parameters are next. They are encoded in compliance with the present specification and stored either in the root cell or the next one in the chain.

:::note An encoded parameter cannot be split between different cells :::

### External Outbound Messages

External outbound messages are used to return values from functions or to emit events.

Return values are encoded and put into the message response:

`Function ID`+`Enc(Return values)`

Function ID's highest bit is set to `1`.

Events are encoded as follows:

`Event ID` + `Enc(event args)`

`Event ID` - 32 bits of SHA256 hash of the event function signature with highest bit set to `0`.

### Internal Messages

Internal messages are used for contract-to-contract interaction; they have the following body format:

`Function ID` + `Enc(Arguments)`

`Function ID` - 32 bits function id calculated as first 32 bits SHA256 hash of the function signature. The highest bit of function ID is `0`. Internal messages contain only function calls and no responses.

## Message Body Signing

The message body can be protected with a cryptographic signature to identify a user outside the blockchain. In this case, an *External inbound message* that calls the function carries a user *private key* signature. This requirement applies only to *External inbound messages* because *Internal inbound messages* are generated within the blockchain, and *src address* can be used to identify the caller.

If a user does not want to sign a message, bit `0` should be placed to the root cell start and signature omitted.

The message body signature is generated from the *representation hash* of the bag of cells following the signature prepended with src address.

## Signing Algorithm

1. ABI serialization generates bag of cells containing header parameters, function ID and function parameters. 591 free bits are reserved in the root cell for destination address ([the maximum size of address](#address)).
2. The root cell data is prepended with actual destination address data without padding to maximum size.
3. *Representation hash* of the bag is signed using the *Ed25519* algorithm.
4. Address data is removed from the root cell and replaced with bit `1` followed by 512 bits of the signature.

:::note This functionality is added since `ABI v2.3` and supported staring with [0.64.0](https://github.com/tonlabs/TON-Solidity-Compiler/blob/master/Changelog_TON.md#0640-2022-08-18) version of the Solidity compiler. :::

## Function Signature (Function ID)

The following syntax is used for defining a signature:

* function name
* list of input parameter types (input list) in parenthesis
* list of return values types (output list) in parenthesis
* ABI version

Single comma is used to divide each input parameter and return value type from one another. Spaces are not used.

Parameter and return value names are not included.

The function name, input and output lists are not separated and immediately follow each other.

If a function has no input parameters or does not return any values, the corresponding input or output lists are empty (empty parenthesis).

Function ID may be indicated in ABI separately. Then the first bit stays the same regardless of incoming/outgoing message.

### Function Signature Syntax

`function_name(input_type1,input_type2,...,input_typeN)(output_type1,output_type2,...,output_typeM)v2`

### Signature Calculation Syntax

`SHA256("function_name(input_type1,input_type2,...,input_typeN)(output_type1,output_type2,...,output_typeM)v2")`

### Sample Implementation

**Function**

`func(int64 param1, bool param2) -> uint32`

**Function Signature**

`func(int64,bool)(uint32)v2`

**Function Hash**

`sha256("func(int64,bool)(uint32)v2") = 0x1354f2c85b50aa84c2f65ebb8cec69aba0aa3269c21e03e142e014e84ea59649`

**function ID** then is `0x1354f2c8` for function call and `0x9354f2c8` for function response

### Event ID

**Event ID** is calculated in the same way as the **function ID** except for cases when the event signature does not contain the list of return values types: `event(int64,bool)v2`

## Header parameter types

* [`time`](#time): message creation timestamp. Encoded as 64 bit Unix time in milliseconds.
* [`expire`](#expire): Unix time (in seconds, 32 bit) after that message should not be processed by contract.
* [`pubkey`](#pubkey): public key from key pair used for signing the message body. This parameter is optional.

**Note**: Header may also contain any of standard function parameter types described below to be used in custom checks.

## Function parameter types

* [`int<N>`](#intn): two’s complement signed `N` bit integer. Big-endian encoded signed integer stored in the cell-data.
* [`uint<N>`](#uintn): unsigned `N` bit integer. Big-endian encoded unsigned integer stored in the cell-data.
* [`varint<N>`](#varintn): variable-length signed integer. Bit length is between `log2(N)` and `8 * (N-1)`, where `N` is equal to 16 or 32.
* [`varuint<N>`](#varuintn): variable-length unsigned integer with bit length equal to 8 \* N, where Nis equal to 16 or 32 e.g. Processed like `varint<N>`.
* [`bool`](#bool): equivalent to uint1.
* [tuple `(T1, T2, ..., Tn)`](#tuple): tuple that includes `T1`, ..., `Tn`, `n>=0` types encoded in the following way:

  ```
  Enc(X(1)) Enc(X(2)) ..., Enc(X(n)); where X(i) is value of T(i) for i in 1..n 
  ```

  Tuple elements are encoded as independent values so they can be placed in different cells
* [`map(K,V)`](#mapkeytypevaluetype) is a dictionary of `V` type values with `K` type key. Dictionary is encoded as `HashmapE` type (one bit put into cell data as dictionary root and one reference with data is added if the dictionary is not empty).
* [`cell`](#cell): a type for defining a raw tree of cells. Stored as a reference in the current cell. Must be decoded with `LDREF` command and stored as-is.
  * Note: this type is useful to store payloads as a tree of cells analog to contract code and data in the form of `StateInit` structure of `message` structure.
* [`address`](#address) is an account address in Acki Nacki blockchain. Encoded as `MsgAddress` struct (see TL-B schema in blockchain [spec](https://github.com/ton-blockchain/ton/blob/master/crypto/block/block.tlb#L107)).
* [`bytes`](#bytes): an array of `uint8` type elements. The array is put into a separate cell.
* [`fixedbytes[N]`](#fixedbytesn) an array of N `uint8` type elements. The array is put into the cell data and limited to 127 bytes.
* [`string`](#string) - a type containing UTF-8 string data, encoded like `bytes`.
* [`optional`](#optionalinnertype) - value of optional type `optional(innerType)` can store a value of `innerType` or be empty.
* [`itemType[]`](#itemtype) is a dynamic array of `itemType` type elements. It is encoded as a TVM dictionary. `uint32` defines the array elements count placed into the cell body. `HashmapE` (see TL-B schema in TVM spec) struct is then added (one bit as a dictionary root and one reference with data if the dictionary is not empty). The dictionary key is a serialized `uint32` index of the array element, and the value is a serialized array element as `itemType` type.
* `T[k]` is a static size array of `T` type elements. Encoding is equivalent to `T[]` without elements count.
* [`ref(T)`](#reft) indicates that `T` will be stored in a separate cell

## Default values for parameter types

Starting from API 2.4 the specification defines default values for parameter types.

* [`int<N>`](#intn) – `N` zero bits.
* [`uint<N>`](#uintn) – `N` zero bits.
* [`varint<N>`](#varintn)/[`varuint<N>`](#varuintn) – `x` zero bits, where `x = [log2(N)]`.
* [`bool`](#bool) – equivalent to [`int<N>`](#uintn), where `N = 1`.
* [`tuple(T1, T2, ..., Tn)`](#tuple) – default values for each type, i.e. `D(tuple(T1, T2, ..., Tn)) = tuple(D(T1), D(T2), ..., D(Tn))`, where `D` is defined as a function that takes ABI type and returns the corresponding default value.
* [`map(K,V)`](#mapkeytypevaluetype) – 1 zero bit, i.e. `b{0}`.
* [`cell`](#cell) – reference to an empty cell, i.e. `^EmptyCell`.
* [`address`](#address) – `addr_none$00` constructor, i.e. 2 zero bits.
* [`bytes`](#bytes) – reference to an empty cell, i.e. `^EmptyCell`.
* [`string`](#string) – reference to an empty cell, i.e. `^EmptyCell`.
* [`optional(T)`](#optionalinnertype) – 1 zero bit, i.e. `b{0}`.
* [`T[]`](#itemtype) – `x{00000000} b{0}`, i.e. 33 zero bits.
* `T[k]` – encoded as an array with `k` default values of type `T`
* [`ref(T)`](#reft) – reference to a cell, cell is encoded as the default value of type `T`.

## Encoding of function ID and its arguments

Function ID and the function arguments are located in the chain of cells. The last reference of each cell (except for the last cell in the chain) refers to the next cell. After adding the current parameter in the current cell we must presume an invariant (rule that stays true for the object) for our cell: number of unassigned references in the cell must be not less than 1 because the last reference is used for storing the reference on the next cell. The last cell in the chain can use all 4 references to store argument's values.

When we add a specific value of some function argument to the cell we assume that it takes the max bit and max ref size for a particular argument type (see [`types reference`](#types-reference) section). Only if the current parameter (by max bit or max ref size) does not fit into the current cell do we create a new cell and insert the parameter in the new cell. But if the current argument and all the following arguments fit into the current cell by max size, then we push the parameters in the cell. The serialized argument value takes up only the necessary bits and refs size without aligning to max sizes of its type.

In the end we connect the created cells in the chain of cells by assigning the last reference in each cell to next cell.

Below are some examples:

```solidity
function f(address a, address b) public;
```

Here we create 2 cells. In the first cell there is function id and `a`. There may be not more than 32+591=623 bits (591 bits is the [maximum size of 'address'](#address)). So it is not more than 1023 bits. The next parameter `b` thus can't fit into the first cell. In the second cell there is only `b`.

```solidity
function f(mapping(uint=>uint) a, mapping(uint=>uint) b, mapping(uint=>uint) c, mapping(uint=>uint) d)
```

[map](#mapkeytypevaluetype) type takes up maximum 1 bit and 1 ref so all parameters can fit into one cell: function ID, `a`, `b` `c`, `d`.

```solidity
struct A {
  string a;
  string b;
  string c;
  string d;
}

function f(A a, uint32 e) public;
```

Same as the previous example, this fits in one cell because [string](#string) takes 32 bits and 1 ref.

```solidity
function f(string a, string b, string c, string d, uint32 e) public
```

Function ID, `a`, `b`, `c` are located in the first cell. `d` and `e` fit in the first cell by max size. That's why we push all parameters in the fist cell.

```solidity
function f(string a, string b, string c, string d, uint e, uint f, uint g, uint h) public
```

`uint` in Solidity is equal to `uint256`. We use 3 cells. In the first cell there are function Id, `a`, `b,` `c`. In the second - `d`, `e`, `f`, `g`. In the third - `h`.

## Encoding header for external messages

External message's body contains function call header in addition to function ID and arguments. Header has up to 3 optional parameters and mandatory signature. Function ID and function parameters are put after header parameters.

Maximum header size is calculated as follows (no references used).

```js
maxHeader =
  591 +
  (hasPubkey ? 1 + 256 : 0) +
  (hasTime ? 64 : 0)  +
  (hasExpire ? 32 : 0);
```

591 bits are reserved for message destination address to use it while [signing](#signing-algorithm) the body.

Let's look at some examples of header encoding. Assume that header contains `time` and `expire` parameters. It requires `591 + 64 + 32 = 687` bits

```solidity
function f(address a, address b) public;
```

Now we have to use 3 cells. In the first cell we put header and function ID. Parameter `a` can not fit in first cell so it goes to second and `b` is put in the third cell.

```solidity
function f(mapping(uint=>uint) a, mapping(uint=>uint) b, mapping(uint=>uint) c, mapping(uint=>uint) d)
```

Here header and all arguments fit in the first cell. After signing it will contain 645 bits and 4 refs.

## ABI JSON

The contract interface is stored as a JSON file called contract ABI. It includes all public functions with data described by ABI types. Below is a structure of an ABI file in TypeScript notation:

```typescript
type Abi = {
  version: string,
  header?: HeaderParam[],
  functions: Function[],
  events?: Event[],
  data?: Data[],
  fields?: Param[],
}

type HeaderParam = Param | string

type Function = {
  name: string,
  inputs?: Param[],
  outputs?: Param[],
  id?: number,
}

type Event = {
  name: string,
  inputs?: Param[],
  id?: number,
}

type Data = Param & {
  key: number,
}

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

### Header

This section describes additional parameters of functions within the contract. Header-specific types are specified as strings with the type `name`. Other types are specified as function parameter type (see [Functions](#function-parameter-types)))

```json
{
  "header": [
    "header_type",
    {
      "name": "param_name",
      "type": "param_type"
    }
  ]
}
```

Example

```json5
{
  "header": [
    "time",
    "expire",
    {
      "name": "custom",
      "type": "int256"
    }
  ]
}
```

### Functions

Specifies each interface function signature, including its name, input, and output parameters. Functions specified in the contract interface can be called from other contracts or from outside the blockchain via ABI call.

Functions section has the following fields:

```json5
{
  "functions": [
    {
      "name": "method_name",
      "inputs": [
        {"name": "func_name", "type": "ABI_type"},
      ],
      "outputs": [],
      "id": "0xXXXXXXXX", //optional
    }
  ]
}
```

* `name`: function name;
* `inputs`: an array of objects, each containing:
  * `name`: parameter name;
  * `type`: the canonical parameter type.
  * `components`: used for tuple types, optional.
* `id`: an optional `uint32` `id` parameter can be added. This `id` will be used as a `Function ID` instead of automatically calculated. PS: the last case can be used for contracts that are not ABI-compatible.
* `outputs`: an array of objects similar to `inputs`. It can be omitted if the function does not return anything;

### Events

This section specifies the events used in the contract. An event is an external outbound message with ABI-encoded parameters in the body.

```json5
{
  "events": [
    {
      "name": "event_name",
      "inputs": [],
      "id": "0xXXXXXXXX", //optional
    },
  ]
}
```

`inputs` have the same format as for functions.

### Fields

This section describes persistent smart contract data. Data structure is described as a list of variables names with corresponding data types and init flag. They are listed in the order in which they are stored in the smart contract data.

Fields that are `init = true` are recommended to be specified as initial data during deploy for correct contract behaviour. Tools and SDK, that responsible for encoding of this section should raise errors when a developer attempts to set a non-init (`init = false`) variable, requiring the specification of all init variables and filling non-init variables with [default values](#default-values-for-parameter-types).

:::note In case of [Solidity Compiler implementation for TVM](https://github.com/tonlabs/TON-Solidity-Compiler/tree/master) fields with `init = true` contain Solidity static variables and some specific internal Solidity variables that are required for smart contract deploy by the compiler, for example, `_pubkey`. :::

Solidity contract state variables example:

```solidity
contract Bank {
  uint256 creditLimit;
  uint256 totalDebt;
  uint256 balance;
  uint256 value;
  uint256 static seqno;
}
```

Fields section of the abi file. In this case the developer will need to explicitly pass `_pubkey` and `seqno` fields, and the rest of the variables will be filled with default values for its types.

```json
{
  "fields": [
    {"name":"_pubkey","type":"uint256","init": true},
    {"name":"_timestamp","type":"uint64","init": false},
    {"name":"_constructorFlag","type":"bool","init": false},
    {"name":"creditLimit","type":"uint256","init": false},
    {"name":"totalDebt","type":"uint256","init": false},
    {"name":"balance","type":"uint256","init": false},
    {"name":"value","type":"uint256","init": false},
    {"name":"seqno","type":"uint256","init": true}
  ]
}
```

### Types Reference

#### `time`

*Header parameter type.*

`time` is the message creation timestamp. Used for **replay attack protection**, encoded as 64 bit Unix time in milliseconds.

| Usage                                                                                                                                                                                   | Value                                     | Examples       | Max bit size | Max ref size |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -------------- | ------------ | ------------ |
| Cell                                                                                                                                                                                    | 64 bit, big endian                        |                | 64 bits      | 0 refs       |
| JSON object                                                                                                                                                                             | string with hex or decimal representation | `"1685634471"` |              |              |
| **Rule**: the contract should store the timestamp of the last accepted message. The initial timestamp is 0. When a new message is received, the contract should do the following check: |                                           |                |              |              |

`last_time` < `new_time` < `now + interval`, where

`last_time` - last accepted message timestamp (loaded from c4 register),

`new_time` - inbound external message timestamp (loaded from message body),

`now` - current block creation time (just as NOW TVM primitive),

`interval` - 30 min.

The contract should continue execution if these requirements are met. Otherwise, the inbound message should be rejected.

#### `expire`

*Header parameter type.*

Unix time (in seconds, 32 bit) after which message should not be processed by contract. It is used for indicating lost external inbound messages.

| Usage       | Value                                     | Examples | Max bit size | Max ref size |
| ----------- | ----------------------------------------- | -------- | ------------ | ------------ |
| Cell        | 32 bit, big endian                        |          | 32 bits      | 0 refs       |
| JSON object | string with hex or decimal representation | `"3600"` |              |              |

**Rule**: if contract execution time is less then `expire` time, then execution is continued. Otherwise, the message is expired, and the transaction aborts itself (by `ACCEPT` primitive). The client waits for message processing until the `expire` time. If the message wasn't processed during that interval it is considered to be expired.

#### `pubkey`

*Header parameter type.*

Public key from key pair used for signing the message body. This parameter is optional. The client decides if they need to set the public key or not. It is encoded as bit 1 followed by 256 bit of public key if parameter provided, or by bit `0` if it is not.

| Usage       | Value                                             | Examples                                                              | Max bit size | Max ref size |
| ----------- | ------------------------------------------------- | --------------------------------------------------------------------- | ------------ | ------------ |
| Cell        | 1 bit, `0` or `1` + 256 bit key if if first bit=1 |                                                                       | 257 bit      | 0 refs       |
| JSON object | string hexadecimal representation of byte array   | `"33a2ed7a92bb55b3aabe1185d0107d48 faa798246c95ed76f262d857c3d1227b"` |              |              |

#### `int<N>`

Fixed-sized signed integer, where `N` is a decimal bit length. Examples: `int8`, `int32`, `int256`.

| Usage          | Value                                               | Examples                | Max bit size | Max ref size |
| -------------- | --------------------------------------------------- | ----------------------- | ------------ | ------------ |
| Cell           | N bit, big endian                                   |                         | N bits       | 0 refs       |
| JSON (returns) | string with hex or decimal representation           | `"0x12"`, `"100"`       |              |              |
| JSON (accepts) | number or string with hex or decimal representation | `12`, `"0x10"`, `"100"` |              |              |

#### `uint<N>`

Fixed-sized unsigned integer, where N is a decimal bit length e.g., `uint8`, `uint32`, `uint256`. Processed like `int<N>`.

#### `varint<N>`

Variable-length signed integer. Bit length is between `log2(N)` and `8 * (N-1)`, where `N` is equal to 16 or 32, e.g. `varint16`, `varint32`.

| Usage          | Value                                                                                                                                                 | Examples                | Max bit size                                                 | Max ref size |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------ | ------------ |
| Cell           | <p>4 (N=16) of 5 (N=32) bits that encode byte length of the number <code>len</code><br>followed by <code>len \* 8</code> bit number in big endian</p> |                         | `varint16` type — 124 bits, `varint32` type — 253 bits, etc. | 0 refs       |
| JSON (returns) | string with hex or decimal representation                                                                                                             | `"0x12"`, `"100"`       |                                                              |              |
| JSON (accepts) | number or string with hex or decimal representation                                                                                                   | `12`, `"0x10"`, `"100"` |                                                              |              |

#### `varuint<N>`

Variable-length unsigned integer with bit length equal to `8 * N`, where `N`is equal to 16 or 32 e.g., `varint16`, `varint32`. Processed like `varint<N>`.

#### `bool`

Boolean type.

| Usage          | Usage                                          | Examples               | Max bit size | Max ref size |
| -------------- | ---------------------------------------------- | ---------------------- | ------------ | ------------ |
| Cell           | 1 bit, `0` or `1`                              |                        | 1 bit        | 0 refs       |
| JSON (returns) | `true`, `false`                                |                        |              |              |
| JSON (accepts) | `true`, `false`, `0`, `1`, `"true"`, `"false"` | `0`, `true`, `"false"` |              |              |

#### `tuple`

Struct type, consists of fields of different types. All fields should be specified as an array in the `components` section of the type.

`structure (aka tuple)` type is considered as a sequence of its types when we encode the function parameters. That's why `tuple` type doesn't have max bit or max ref size. Nested `tuple`'s also are considered as a sequence of its types. For example:

```solidity
struct A {
  uint8 a;
  uint16 b;
}

struct B {
  uint24 d;
  A a;
  uint32 d;
}
```

structure `B` is considered as a sequence of `uint24`, `uint8`, `uint16`, `uint32` types.

For example, for structure `S`:

```solidity
struct S {
  uint32 a;
  uint128 b;
  uint64 c;
}
```

parameter `s` of type `S` would be described like:

```json
{
  "components": [
    {"name":"a","type":"uint32"},
    {"name":"b","type":"uint128"},
    {"name":"c","type":"uint64"}
  ],
  "name":"s",
  "type":"tuple"
}
```

| Usage       | Value                                                                                                       | Examples                   |
| ----------- | ----------------------------------------------------------------------------------------------------------- | -------------------------- |
| Cell        | <p>chain of cells with tuple data types encoded consistently<br>(without splitting value between cells)</p> |                            |
| JSON object | dictionary of struct field names with their values                                                          | `{"a": 1, "b": 2, "c": 3}` |

#### `map(<keyType>,<valueType>)`

Hashtable mapping keys of `keyType` to values of the `valueType`, e.g., `map(int32, address)`. Key may be any of `int<N>/uint<N>` types with `N` from `1` to `1023` or address of std format.

| Usage       | Value                                                                              | Examples                              | Max bit size | Max ref size |
| ----------- | ---------------------------------------------------------------------------------- | ------------------------------------- | ------------ | ------------ |
| Cell        | 1 bit (`0` - for empty mapping, otherwise `1`) and ref to the cell with dictionary |                                       | 1 bit        | 1 ref        |
| JSON object | dictionary of keys and values                                                      | `{"0x1":"0x2"}`, `{"2":"3","3":"55"}` |              |              |

There are some specifics when working with "big" structures as values in mappings. Read [below](#big-structures-as-values-in-mappings-and-arrays) how to implement them correctly.

#### `cell`

TVM Cell type.

| Usage       | Value                                          | Examples                                     | Max bit size | Max ref size |
| ----------- | ---------------------------------------------- | -------------------------------------------- | ------------ | ------------ |
| Cell        | stored in a ref                                |                                              | 0 bit        | 1 ref        |
| JSON object | cell serialized into boc and encoded in base64 | `"te6ccgEBAQEAEgAAH/////////////////////g="` |              |              |

#### `address`

Contract address in type `address`, can be any of the [existing variants](https://github.com/tvmlabs/tvm-sdk/blob/gitbook/docs/arch/40-accounts.md#account-address) (although not all may be supported by the compilator you are using).

**Important notes:**

1. All hexadecimal values represented in **lower case**.
2. Bitstrings are represented in hexadecimal variable length form with `_` suffix if length is not multiple of 4. When length is multiple of 4 bitstring is always encoded **without** `_` suffix.

**Format**

```jsx
"" // None
":A...A" // External
"[N..N:]W:A...A" // Internal
```

where:

* `W` is a decimal signed representation for workchain\_id.
* `A...A` is a string representation of bitstring (see important nodes above);
* `N...N` is a string representation of bitstring with anycast rewrite prefix.

**Serialization**

Internal addresses are serialised as:

* `std` when workchain id is 8-bit and address is 256-bit
* `var` otherwise.

**Size**

Maximum size allocated for address is 591 bits: see <https://github.com/ton-blockchain/ton/blob/master/crypto/block/block.tlb#L107>

```tl-b
anycast_info$_ depth:(#<= 30) { depth >= 1 }
   rewrite_pfx:(bits depth) = Anycast;

addr_var$11 anycast:(Maybe Anycast) addr_len:(## 9) 
   workchain_id:int32 address:(bits addr_len) = MsgAddressInt;

2 +          // 11 
1 + 5 + 30 + // anycast
9 +          // addr_len
32 +         // workchain_id:int32
512          // address
 = 
591
```

| Usage       | Value                                                                                                             | Examples                                                                  | Max bit size | Max ref size |
| ----------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------ | ------------ |
| Cell        | 2 bits of address type, 1 bit of anycast, wid - 8 bit signed integer and address value - 256 bit unsigned integer |                                                                           | 591 bits     | 0 refs       |
| JSON object | string                                                                                                            | `"123:000000000000000000000000000000 000000000000000000000000000001e0f3"` |              |              |

#### `bytes`

An array of `uint8` type elements. The array is put into a separate cell. In the case of array overflow, the maximum cell-data size it's split into multiple sequential cells.

**Note**: contract stores this type as-is without parsing. For high-speed decoding, cut reference from body slice as `LDREF`. This type is helpful if some raw data must be stored in the contract without write or random access to elements.

Analog of `bytes` in Solidity. In C lang can be used as `void*`.

| Usage       | Value                                 | Examples   | Max bit size | Max ref size |
| ----------- | ------------------------------------- | ---------- | ------------ | ------------ |
| Cell        | cell with data stored in a ref        |            | 0 bit        | 1 ref        |
| JSON object | binary data represented as hex string | `"313233"` |              |              |

#### `fixedbytes<N>`

An array of N `uint8` type elements. The array is put into the cell data and limited to 127 bytes.

| Usage       | Value                                 | Examples   | Max bit size | Max ref size |
| ----------- | ------------------------------------- | ---------- | ------------ | ------------ |
| Cell        | `N * 8` bits                          |            | `N * 8` bit  | 0 ref        |
| JSON object | binary data represented as hex string | `"313233"` |              |              |

#### `ref(T)`

The auxiliary type `ref(T)` helps to explicitly say that `T` will be encoded into a separate cell and stored in the current cell as a reference. And `T` can be of any ABI types, including [`tuple(T1, T2, ..., Tn)`](#tuple), or contain itself like `ref(ref(...)`.

| Usage       | Value                                     | Examples  | Max bit size | Max ref size |
| ----------- | ----------------------------------------- | --------- | ------------ | ------------ |
| Cell        | cell with data stored in a ref            |           | 0 bit        | 1 ref        |
| JSON object | according to `T` or `null` if it is empty | `"hello"` |              |              |

#### `string`

UTF-8 String data. Encoded like `bytes`. In JSON is represented as a sting.

| Usage       | Value                          | Examples  | Max bit size | Max ref size |
| ----------- | ------------------------------ | --------- | ------------ | ------------ |
| Cell        | cell with data stored in a ref |           | 0 bit        | 1 ref        |
| JSON object | string data                    | `"hello"` |              |              |

#### `optional(innerType)`

Value of optional type `optional(innerType)` can store a value of `innerType` or be empty.

Example: `optional(string)`.

The optional type is a `large` if `maxBitSize(InnerType) + 1 > 1023 || maxRefSize(InnerType) >= 4`.

Large optional values are always stored as a reference. The optional bit itself is stored on the main branch.

Small optional values are stored in the same cell with the optional bit.

| Usage       | Value                                                                                                            | Examples  | Max bit size                                                                 | Max ref size                                   |
| ----------- | ---------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------- | ---------------------------------------------- |
| Cell        | 1 bit flag (`1` - value is stored, otherwise `0`) and the value itself (according to `innerType`) if it presents |           | 1 bit if `optional` is large, `1 bit + maxBitQty(T), maxRefQty(T)` otherwise | 1 ref if `optional` is large, 0 refs otherwise |
| JSON object | according to `innerType` or `null` if it is empty                                                                | `"hello"` |                                                                              |                                                |

#### `itemType[]`

Array of the `itemType` values. Example: `uint256[]`

| Usage       | Value                                                                                                                                                                               | Examples                          | Max bit size | Max ref size |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | ------------ | ------------ |
| Cell        | 32 unsigned bit length of the array, 1 bit flag (`0` if array is empty, otherwise `1`) and dictionary of keys and values where key is 32 unsigned bit index and value is `itemType` |                                   | 33 bit       | 1 ref        |
| JSON object | list of `itemType` values in `[]`                                                                                                                                                   | `[1, 2, 3]`, `["hello", "world"]` |              |              |

There are some specifics when working with "big" structures as values in arrays. Read [below](#big-structures-as-values-in-mappings-and-arrays) how to implement them correctly.

### "Big" structures as values in mappings and arrays

When working with "big" structures in mappings and arrays data may be written in two possible ways - either into cell or into reference, depending on the size:

```
if (12 + len(key) + maxValueBitLength <= 1023) then write data into cell

else write data to reference.

12 = 2 + 10 ≥ 2 + log2(keyLength).
```

See <https://github.com/ton-blockchain/ton/blob/master/crypto/block/block.tlb#L30>

## Reference

* [ABI changelog specifications](https://github.com/tvmlabs/tvm-sdk/blob/main/tvm_abi/CHANGELOG.md)
* [ABI implementation](https://github.com/tvmlabs/tvm-sdk/tree/main/tvm_abi)


# Mnemonics and Keys

This guide explains which mnemonic standards the SDK uses, how it derives signing keys from a mnemonic, how to create signing keys without a mnemonic, and which signature algorithm is used for messages.

## Standards and algorithms

The SDK mnemonic and signing APIs are based on these standards and algorithms:

| Purpose                         | SDK API                                                     | Standard or algorithm                                                                                                                                                             |
| ------------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Mnemonic dictionary             | `mnemonic_from_random`, `mnemonic_words`, `mnemonic_verify` | `MnemonicDictionary::English` by default: English BIP-39 dictionary                                                                                                               |
| Supported mnemonic dictionaries | `MnemonicDictionary`                                        | `Ton = 0`, `English = 1`, `ChineseSimplified = 2`, `ChineseTraditional = 3`, `French = 4`, `Italian = 5`, `Japanese = 6`, `Korean = 7`, `Spanish = 8`                             |
| BIP-39 mnemonic validation      | `mnemonic_verify`                                           | BIP-39 word list and checksum validation                                                                                                                                          |
| BIP-39 mnemonic to seed         | `hdkey_xprv_from_mnemonic`, `mnemonic_derive_sign_keys`     | PBKDF2-HMAC-SHA512, 2048 iterations                                                                                                                                               |
| HD master key                   | `hdkey_xprv_from_mnemonic`                                  | BIP-32-style master key: HMAC-SHA512 with key `Bitcoin seed`                                                                                                                      |
| HD derivation                   | `hdkey_derive_from_xprv`, `hdkey_derive_from_xprv_path`     | BIP-32-style derivation over secp256k1/k256 extended private keys                                                                                                                 |
| Default derivation path         | `mnemonic_derive_sign_keys`                                 | <p><br>Currently uses <code>m/44'/396'/0'/0/0</code>.<br>Will switch to <code>1331</code> after Acki Nacki is registered in the SLIP-0044 registry via the SatoshiLabs PR<br></p> |
| Signing key pair                | `mnemonic_derive_sign_keys`, `generate_random_sign_keys`    | Ed25519 key pair; public key is derived from a 32-byte signing secret                                                                                                             |
| Message signature               | `sign`, `nacl_sign`, `nacl_sign_detached`, ABI signing      | Ed25519 / NaCl signature, 64 bytes / 512 bits                                                                                                                                     |

By default, the SDK crypto config uses:

```javascript
const DEFAULT_MNEMONIC_DICTIONARY = 1; // English BIP-39
const DEFAULT_MNEMONIC_WORD_COUNT = 12;
const DEFAULT_HD_PATH = "m/44'/396'/0'/0/0"; // Will switch to 1331 after Acki Nacki is registered in the SLIP-0044 registry via the SatoshiLabs PR
```

For reproducible behavior, pass `dictionary`, `word_count`, and `path` explicitly instead of relying on defaults. The mnemonic APIs described in this guide use the crypto config default, which is English BIP-39. Some higher-level CryptoBox seed phrase helpers use `Ton` as their own default, so always check the API you call or pass the dictionary explicitly. The `Ton` dictionary is TON-compatible and uses a different seed validation and seed derivation flow than BIP-39 dictionaries.

## Mnemonic generation

To generate a random mnemonic, use `mnemonic_from_random`. Specify the dictionary and a number of words. The most common SDK setup uses the English BIP-39 dictionary and 12 words:

```javascript
const SEED_PHRASE_WORD_COUNT = 12;
const SEED_PHRASE_DICTIONARY_ENGLISH = 1;

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"
```

For BIP-39 dictionaries the supported word counts are 12, 15, 18, 21, and 24. The phrase is generated with the selected BIP-39 word list and checksum. You can inspect the selected word list with `mnemonic_words`.

## Key pair generation from mnemonic

The simplest way to get a signing key pair from a mnemonic is `mnemonic_derive_sign_keys`.

```javascript
const HD_PATH = "m/44'/396'/0'/0/0"; //Will switch to 1331 after Acki Nacki is registered in the SLIP-0044 registry via the SatoshiLabs PR

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'
}
```

Internally, for a BIP-39 mnemonic the SDK performs this flow:

1. Validates the phrase against the selected BIP-39 dictionary and checksum.
2. Converts the phrase to a 64-byte seed with PBKDF2-HMAC-SHA512, 2048 iterations, salt `mnemonic`.
3. Builds the HD master private key with HMAC-SHA512 using key `Bitcoin seed`.
4. Derives an extended private key by the requested BIP-32-style derivation path.
5. Takes the derived 32-byte secret and creates an Ed25519 signing key pair from it.

For `dictionary: 0` (`Ton`), the SDK uses TON-compatible mnemonic validation and seed derivation, then applies the same HD path derivation and Ed25519 signing key creation.

## Key pair generation without mnemonic

If you do not need a human-readable recovery phrase, generate a signing key pair directly with `generate_random_sign_keys`:

```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'
}
```

This API generates 32 random bytes, treats them as an Ed25519 signing secret, and derives the public key from that secret. The returned `secret` is a 64-symbol hex string, that is, 32 bytes.

The lower-level NaCl helper `nacl_sign_keypair_from_secret_key` has a different return format: its `secret` is `secret || public`, 64 bytes / 128 hex symbols, as expected by NaCl signing functions. Use `generate_random_sign_keys` when you need a regular SDK `KeyPair` for ABI signing.

## Keys derivation

### Master (root) key

To derive a key by path manually, first generate an extended master private key from the mnemonic with `hdkey_xprv_from_mnemonic`.

```javascript
const { xprv: hdkRoot } = await client.crypto.hdkey_xprv_from_mnemonic({
    dictionary: SEED_PHRASE_DICTIONARY_ENGLISH,
    word_count: SEED_PHRASE_WORD_COUNT,
    phrase,
});

console.log(`Serialized extended master private key:\n${hdkRoot}`);
```

Result:

```
Serialized extended master private key:
xprv9s21ZrQH143K45hXeaopM1rAUJDszLAcwFkxrZ4njANoGhFPYFsB7rzspWC8wAnWoZ2bPia7covh3mVVboC2nEswu18iEHs5LjVknSWMR2w
```

For BIP-39 mnemonics this function uses PBKDF2-HMAC-SHA512, then creates the master extended private key with HMAC-SHA512 and key `Bitcoin seed`.

### Derived key

Derive the extended private key by path with `hdkey_derive_from_xprv_path`.

```javascript
const HD_PATH = "m/44'/396'/0'/0/0"; // Will switch to 1331 after Acki Nacki is registered in the SLIP-0044 registry via the SatoshiLabs PR

const { xprv: extendedPrKey } = await client.crypto.hdkey_derive_from_xprv_path({
    xprv: hdkRoot,
    path: HD_PATH,
});

console.log(`Serialized derived extended private key:\n${extendedPrKey}`);
```

Result:

```
Serialized derived extended private key:
xprvA45BBKdrZKobCbeFvC316LZ6AVDXbDn8Sa3btCMCcgTRM4CRxX4Tg3fk7sNNXPza9aMiS6mBMp7wfHdmT23bri6YgwHbTJgXqKnJNNHAw98
```

The default derivation path used by `mnemonic_derive_sign_keys` is:

```
m/44'/396'/0'/0/0 // Will switch to 1331 after Acki Nacki is registered in the SLIP-0044 registry via the SatoshiLabs PR
```

The SDK derivation is BIP-32-style derivation over secp256k1/k256 extended private keys. Hardened path elements are marked with `'`. After derivation, the derived 32-byte private key is used as an Ed25519 signing secret. This is the SDK's compatibility flow and is not SLIP-0010 Ed25519 derivation.

To extract the private key bytes from the derived extended key, use `hdkey_secret_from_xprv`.

```javascript
const { secret } = await client.crypto.hdkey_secret_from_xprv({
    xprv: extendedPrKey,
});

console.log(`Derived private key:\n${secret}`);
```

Result:

```
Derived private key:
e90866b307ea6a72c216a34786762e648e9b382779fdfb88cf7b1e900a6bf0e2
```

### Generate keys for signature

To build an Ed25519 signing key pair from a derived 32-byte secret, use `nacl_sign_keypair_from_secret_key` if you need the NaCl key format:

```javascript
const naclKeyPair = await client.crypto.nacl_sign_keypair_from_secret_key({
    secret,
});

console.log("NaCl key pair for signing:");
console.log(naclKeyPair);
```

Result:

```
NaCl key pair for signing:
{
  public: '4085d11b6d607c44ef0e8ddc535786af1a4b1f971e758206cd222ed3eba47d8b',
  secret: 'e90866b307ea6a72c216a34786762e648e9b382779fdfb88cf7b1e900a6bf0e24085d11b6d607c44ef0e8ddc535786af1a4b1f971e758206cd222ed3eba47d8b'
}
```

For ABI message signing, prefer `mnemonic_derive_sign_keys`, because it returns the SDK `KeyPair` format directly:

```javascript
const keyPair = await client.crypto.mnemonic_derive_sign_keys({
    phrase,
    path: HD_PATH,
    dictionary: SEED_PHRASE_DICTIONARY_ENGLISH,
    word_count: SEED_PHRASE_WORD_COUNT,
});
```

You can use this key pair in ABI methods such as `abi.encode_message`, `abi.encode_message_body`, and other functions that accept SDK signing keys.

## Message signing

The SDK signs messages with Ed25519.

For raw user data:

* `crypto.sign` accepts unsigned data in base64 and an SDK `KeyPair`.
* `crypto.nacl_sign` returns signed data in NaCl attached-signature format.
* `crypto.nacl_sign_detached` returns a detached 64-byte signature encoded as hex.

For ABI external inbound messages, the ABI serializer prepares the message body, calculates the representation hash of the bag of cells that must be signed, and signs that hash with Ed25519. The resulting 512-bit signature is placed into the message body according to the ABI signing rules.


# Installation


# Add SDK to your App


# Configuration


# Endpoint Configuration


# Message Expiration


# Message Retry


# Config Reference


# Work with contracts


# Add Contract to your App


# Use your own Sponsor Wallet


# Deploy


# Run on-chain


# Run ABI Get Method


# Run Fift Get Method


# Query messages(events)

How to work with contract event


# Decode Messages(Event)

How to decode messages with ABI


# External Signing


# Emulate Transaction


# Estimate Fees


# Validate address


# Crypto


# Mnemonics and Keys


# Queries


# Use-cases

What data can you get from GraphQL API?


# How to work with net module


# net.query syntax

Write your graphql query in playground, copy it and insert into SDK's net.query function.  Define variables and execute it.


# Data pagination

How to use cursor based pagination of Acki Nacki blocks, transactions and messages


# Query Collection


# 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: TVMClient) {
    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 TVM Client

## JSON Interface to TVM 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 tvm client library in languages others than *Rust*.

Counterparts:

* *Application* – uses native language interface, provided by *binding* library.
* *Binding* – provides native language interface to TVM client library. Uses JSON Interface to directly call TVM client library.
* *Library (or Core)* – provides JSON Interface to all TVM 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 TVM 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

TVM 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](/for-binding-developers/app_objects).


