Skip to main content

Example

image

Example​

This part will help you understand the fundamental steps to integrate Primus Network-JS-SDK and complete a basic data verification process through your application. You can learn about the integration process through this simple demo.

Prerequisites​

Before you begin, ensure you have the following:

Key Features​

1. SDK Initialization​

Connect to specified blockchain networks.

Function Name: init

Parameter Description:​
Parameter NameTypeRequiredDescription
providerProviderYesWeb3 provider, can be:
- An instance of ethers.providers.JsonRpcProvider
- An instance of ethers.providers.Web3Provider
- An instance of ethers.providers.JsonRpcSigner
chainIdnumberYesThe blockchain network ID to connect to. Must be one of the supported chain IDs

2. Task Submission​

Submit tasks to require an attestation from the network.

Function Name: submitTask

Parameter Description:​
Parameter NameTypeRequiredDescription
templateIdstringYesTemplate ID
addressstringYesUser 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 NameTypeRequiredDescription
templateIdstringYesTemplate ID
addressstringYesUser address
taskIdstringYesTask ID
taskTxHashstringYesTask transaction hash
taskAttestors<string>ArrayYesArray of attestor IDs
additionParamsstringNoExtended 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" })
attModestringNoproxytls or mpctls,default is proxytls. you can refer to Overview section for more details.
attConditionsArrayNoBy default, the zkTLS SDK retrieves a plaintext verification result. We offer two types of verification logic to accommodate different requirements:
1.Hashed result const attConditions = [[{field: "YOUR_CUSTOM_DATA_FIELD",op: "SHA256"}]]
2.Conditions result const attConditions = [[{field: "YOUR_CUSTOM_DATA_FIELD",op: ">",value: "YOUR_CUSTOM_TARGET_DATA_VALUE"}]].you can refer to the Verification Logics and zkTLS operations sections for more details.

4. Verify & Poll Task Result​

Verify and poll task results. The function is additonally provided for any use case that requires to double check the validity of an created attestation through Primus contracts.

Function Name: verifyAndPollTaskResult

Parameter Description:​
Parameter NameTypeRequiredDescription
taskIdstringYesThe ID of the task to poll
reportTxHashstringNoReport transaction hash (optional)
intervalMsnumberNoPolling interval in milliseconds, default is 2000
timeoutMsnumberNoTotal timeout duration in milliseconds, default is 1 minute

5. Balance Withdrawal​

Retrieve the fees for unsettled tasks.

Function Name: withdrawBalance

Parameter Description:​
Parameter NameTypeRequiredDescription
tokenSymbolTokenSymbolNoToken type to withdraw, default is ETH
limitnumberNoWithdrawal amount limit, default is 100

6. List of Supported Chains​

Property Name:supportedChainIds

Currently supports Base Sepolia and Base mainnet, 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.

const attestParams = {
...submitTaskParams,
...submitTaskResult,
attConditions: [
[
{
field: "YOUR_FIELD_NAME",
op: "SHA256",
},
],
]
allJsonResponseFlag: 'true',// optional, default is 'false', Must be set to true to allow getAllJsonResponse to return the HTTP response.

};

let attestResult = await primusNetwork.attest(attestParams);

const allJsonResponse = await primusNetwork.getAllJsonResponse(
attestResult[0].taskId
);

Complete Example​

import { PrimusNetwork } from "@primuslabs/network-js-sdk";

async function main() {
const provider = window.ethereum;
const primusNetwork = new PrimusNetwork();
console.log(primusNetwork.supportedChainIds); // [84532, 8453]

try {
// 1. Initialize
await primusNetwork.init(provider, 84532); // The Base chain changes 84532 to 8453
console.log("SDK initialized");

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

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

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

// Optional withdrawal
// const settledTaskIds = await primusNetwork.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.

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 for troubleshooting.