# Example

This part will help you understand the fundamental steps to integrate NexaID Network-JS-SDK and complete a basic data verification process through your application.

### Prerequisites

Before you begin, ensure you have the following:

* A valid Template ID (obtainable from the [NexaID Developer Hub](https://testnet-nexaid.hashkeychain.net/))
* The SDK installed (see the [Installation Guide](/nexaid/build-on-nexaid/dapp-integration/installation.md) for instructions)

### Key Features

#### **1. SDK Initialization**

Connect to specified blockchain networks.

Function Name: `init`

**Parameter Description:**

| Parameter Name | Type       | Required | Description                                                                                                                                                                                                                    |
| -------------- | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `provider`     | `Provider` | Yes      | <p>Web3 provider, can be:<br>- An instance of <code>ethers.providers.JsonRpcProvider</code><br>- An instance of <code>ethers.providers.Web3Provider</code><br>- An instance of <code>ethers.providers.JsonRpcSigner</code></p> |
| `chainId`      | `number`   | Yes      | The blockchain network ID to connect to. Must be one of [the supported chain IDs](#6-list-of-supported-chains)                                                                                                                 |

#### **2. Task Submission**

Submit tasks to require an attestation from the network.

Function Name: `submitTask`

**Parameter Description:**

| Parameter Name | Type     | Required | Description  |
| -------------- | -------- | -------- | ------------ |
| `templateId`   | `string` | Yes      | Template ID  |
| `address`      | `string` | Yes      | User address |

#### **3. Attestation Execution**

Execute the zkTLS protocol with the network attestor node, and return an attestation issued by the attestor node.

Function Name: `attest`

**Parameter Description:**

| Parameter Name   | Type       | Required | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ---------------- | ---------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `templateId`     | `string`   | Yes      | Template ID                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `address`        | `string`   | Yes      | User address                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `taskId`         | `string`   | Yes      | Task ID                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `taskTxHash`     | `string`   | Yes      | Task transaction hash                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `taskAttestors`  | `string[]` | Yes      | Array of attestor IDs                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `additionParams` | `string`   | No       | Extended parameters in JSON format. Developers can include custom business parameters (e.g., user IDs, session info),These parameters will be returned with the final results `const additionParams = JSON.stringify({ YOUR_CUSTOM_KEY: "YOUR_CUSTOM_VALUE" })`                                                                                                                                                                                                                                           |
| `attMode`        | `string`   | No       | <p>proxytls or mpctls,default is proxytls. You can refer to <a href="/pages/esQudXIiLa17xIXmlviy">Overview</a><br>section for more details.</p>                                                                                                                                                                                                                                                                                                                                                           |
| `attConditions`  | `Array`    | No       | By default, the zkTLS SDK returns plaintext verification results. You can also define verification logics for hashed results or condition-based results. Example hashed result: `const attConditions = [[{ field: "YOUR_CUSTOM_DATA_FIELD", op: "SHA256" }]]`. Example condition result: `const attConditions = [[{ field: "YOUR_CUSTOM_DATA_FIELD", op: ">", value: "YOUR_CUSTOM_TARGET_DATA_VALUE" }]]`. For the full explanation, see [zkTLS Operations](/nexaid/build-on-nexaid/zktls-operations.md). |

#### **4. Verify & Poll Task Result**

Verify and poll task results. The function is additionally provided for any use case that requires checking the validity of a created attestation through NexaID contracts.

Function Name: `verifyAndPollTaskResult`

**Parameter Description:**

| Parameter Name | Type     | Required | Description                                                 |
| -------------- | -------- | -------- | ----------------------------------------------------------- |
| `taskId`       | `string` | Yes      | The ID of the task to poll                                  |
| `reportTxHash` | `string` | No       | Report transaction hash (optional)                          |
| `intervalMs`   | `number` | No       | Polling interval in milliseconds, default is 2000           |
| `timeoutMs`    | `number` | No       | Total timeout duration in milliseconds, default is 1 minute |

#### **5. Balance Withdrawal**

Retrieve the fees for unsettled tasks.

Function Name: `withdrawBalance`

**Parameter Description:**

| Parameter Name | Type          | Required | Description                             |
| -------------- | ------------- | -------- | --------------------------------------- |
| `tokenSymbol`  | `TokenSymbol` | No       | Token type to withdraw, default is ETH  |
| `limit`        | `number`      | No       | Withdrawal amount limit, default is 100 |

#### **6. List of Supported Chains**

Property Name：`supportedChainIds`

Currently supports **HashKey Chain Testnet**, additional chains will be added in upcoming releases.

### Using Attestations in zkVM

To retrieve a proof validated using hashed verification logic, you may use **getAllJsonResponse** to collect the associated HTTP response payloads. These two components — the attestation (***hashed data***) and the HTTP responses (***raw data***) — can then be jointly submitted to the zkVM for further computation and verification. For more details about hashed and condition-based logic, see [zkTLS Operations](/nexaid/build-on-nexaid/zktls-operations.md).

```javascript
const attestParams = {
  ...submitTaskParams,
  ...submitTaskResult,
  attConditions: [
    [
      {
        field: "YOUR_FIELD_NAME",
        op: "SHA256",
      },
    ],
  ],
  allJsonResponseFlag: "true", // optional, default is "false"
};

const attestResult = await nexaIDNetwork.attest(attestParams);
const allJsonResponse = await nexaIDNetwork.getAllJsonResponse(
  attestResult[0].taskId
);
```

## Complete Example

```javascript
import { NexaIDNetwork } from "@nexaid/network-js-sdk";

async function main() {
  const provider = window.ethereum;
  const nexaIDNetwork = new NexaIDNetwork();

  console.log(nexaIDNetwork.supportedChainIds); // [133]

  try {
    // 1. Initialize
    await nexaIDNetwork.init(provider, 133); // HashKey Chain Testnet
    console.log("SDK initialized");

    // 2. Submit task, set TemplateID and user address
    const submitTaskParams = {
      templateId: "YOUR_TEMPLATEID",
      address: "YOUR_USER_ADDRESS",
    };
    const submitTaskResult = await nexaIDNetwork.submitTask(submitTaskParams);
    console.log("Task submitted:", submitTaskResult);

    // 3. Perform attestation
    const attestParams = {
      ...submitTaskParams,
      ...submitTaskResult,
      // extendedParams: JSON.stringify({ attUrlOptimization: true }),
      // Optional: optimize the URL of attestation.
    };
    const attestResult = await nexaIDNetwork.attest(attestParams);
    console.log("Attestation completed:", attestResult);

    // 4. Verify and poll task result
    const verifyAndPollTaskResultParams = {
      taskId: attestResult[0].taskId,
      reportTxHash: attestResult[0].reportTxHash,
    };
    const taskResult = await nexaIDNetwork.verifyAndPollTaskResult(
      verifyAndPollTaskResultParams
    );
    console.log("Final result:", taskResult);

    // Optional withdrawal
    // const settledTaskIds = await nexaIDNetwork.withdrawBalance();
    // console.log("Withdrawn:", settledTaskIds);
  } catch (error) {
    console.error("Main flow error:", error);
  }
}

main();
```

### Understanding the Attestation Structure

When a successful data verification process is completed, you will receive an zkTLS attestation (proof) from the attestor.

For more information about the attestation structure, see the [section](/nexaid/build-on-nexaid/misc/attestation-structure.md) .

### Error Codes

We have defined several error codes in the SDK. If an error occurs during the data verification process, you can refer to the [error code list](/nexaid/build-on-nexaid/misc/error-code.md) for troubleshooting.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nexaid.gitbook.io/nexaid/build-on-nexaid/dapp-integration/example.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
