Skip to content

Repository files navigation

CESS SDK

CESS SDK implementation for TypeScript.

Installation

npm install @cessnetwork/api @cessnetwork/util @cessnetwork/types

Overview

Complete Workflow with All Three Packages

This workflow demonstrates how all three packages work together:

  • @cessnetwork/api provides the main client and gateway operations
  • @cessnetwork/util provides essential utility functions like signing
  • @cessnetwork/types provides all the type definitions needed for type safety

This section explains how to use all three CESS packages (@cessnetwork/api, @cessnetwork/util, and @cessnetwork/types) together to perform a complete gateway workflow for file storage operations on the CESS network.

Step 1: Initialize CESS Client

import{CESS,CESSConfig,downloadFile,ExtendedDownloadOptions,GenGatewayAccessToken,isKeyringReady,SDKError,uploadFile}from'@cessnetwork/api';import{safeSignUnixTime,}from'@cessnetwork/util';import{GatewayConfig,OssAuthorityList,OssDetail,UploadResponse}from"@cessnetwork/types";import{u8aToHex}from"@polkadot/util";constconfig: CESSConfig={rpcs: ["wss://pm-rpc.cess.network/ws/"],privateKey: process.env.CESS_PRIVATE_KEY||"",}constcess=awaitCESS.newClient(config);console.log('Connected to network:',cess.getNetworkEnv());console.log('Chain Metadata:',cess.getMetadata());if(isKeyringReady(cess.keyring)){console.log('Account address:',cess.getSignatureAcc());console.log('Account balance:',cess.getBalances());}else{thrownewSDKError('Keyring Pair is required','INVALID_KEYRING');}

Step 2: Sign Message for Gateway Authentication

Using @cessnetwork/util's signing utilities to authenticate with the gateway:

constsign_message=Date.now().toString();constsignature=safeSignUnixTime(sign_message,getMnemonic());console.log("signature:",signature);

Step 3: Create Storage Territory (if needed)

// Check if territory exists, if not create oneletterritoryTokenconstmyTerritory="default"constterritory=awaitcess.queryTerritory(accountAddress,myTerritory)asTerritory;constcurBlockHeight=awaitcess.queryBlockNumberByHash()console.log('Current Block Height:',curBlockHeight);if(!territory){try{constresult=awaitcess.mintTerritory(1,// gibCountmyTerritory,30,// days);if(result.success){console.log('✅ Mint successful!',{txHash: result.txHash,blockHash: result.blockHash});// Wait and query the minted territoryconsole.log('Waiting 6 seconds before querying territory...');awaitnewPromise(resolve=>setTimeout(resolve,6000));constterritory=awaitcess.queryTerritory(accountAddress,myTerritory)asTerritory;territoryToken=territory?.tokenconsole.log('Territory details:',territory);console.log('Territory Token:',territoryToken);}else{console.error('❌ Territory minting failed:',result.error);}}catch(error){console.error('❌ Error during territory minting:',error);}}elseif(territory.deadline-curBlockHeight<=100800){// 100800 block means 7 daysconstrenewalRes=awaitcess.renewalTerritory(myTerritory,10)console.log('renew territory successfully:',renewalRes.blockHash);}elseif(territory.state!="Active"||curBlockHeight>=territory.deadline){// data will be reset when re-activate territoryconstreactivateRes=awaitcess.reactivateTerritory(myTerritory,30)console.log('reactivate territory successfully:',reactivateRes.blockHash);}elseif(territory.remainingSpace<=1024*1024*1024){// remaining space <= 1GiBconstexpandRes=awaitcess.expandingTerritory(myTerritory,1)console.log('expand territory successfully:',expandRes.blockHash);}else{console.log("territory exist: ",territory)}

Step 4: Authorize Gateway Access

letgatewayAcc=""// get oss public acc by domain nameconstossAccList=awaitcess.queryOssByAccountId()asunknownasOssDetail[]for(leti=0;i<ossAccList.length;i++){if(ossAccList[i].ossInfo.domain==gatewayUrl){gatewayAcc=ossAccList[i].accountbreak;}}if(!gatewayAcc){console.error("gateway not found.");return;}// auth my territory to gateway accconstauthList=awaitcess.queryAuthorityListByAccountId(gatewayAcc)asunknownasOssAuthorityList[]constauthorizedAccounts: string[]=authList.map(item=>item.authorizedAcc);if(!authorizedAccounts.indexOf(accountAddress)){try{console.log("start to auth")constresult=awaitcess.authorize(gatewayAcc);if(result.success){console.log('✅ Authorization successful!',{txHash: result.txHash,blockHash: result.blockHash});}else{console.error('❌ Authorization failed:',result.error);}}catch(error){console.error('❌ Error during authorization:',error);}}else{console.log("already auth")}

Step 5: Obtain Gateway Token

consttoken=awaitGenGatewayAccessToken(gatewayUrl,{account: cess.getSignatureAcc(),message: sign_message,sign: u8aToHex(signature),// Convert signature to hex formatexpire: 1// Token expiration in hours});

Step 6: Upload File to Gateway

// Configure gateway connectionconstgatewayConfig: GatewayConfigType={baseUrl: gatewayUrl,token: token};// Upload file to the gatewayletuploadResult: UploadResponse;uploadResult=awaitupload(gatewayConfig,"./path/to/your/file.txt",{territory: myTerritory,uploadFileWithProgress: (progress)=>{console.log(`\rUpload progress: ${progress.percentage}% (${progress.loaded}/${progress.total} bytes) - ${progress.file}`);}});if(uploadResult.code==200){constfid=uploadResult.data;// File ID returned by the gatewayconsole.log("File ID (FID): ",fid);}else{thrownewError("Failed to upload file: "+uploadResult.error);}

Step 7: Download File from Gateway

// Define download optionsconstdownloadOptions: ExtendedDownloadOptions={fid: fid,// The file ID from the upload stepsavePath: "./path/to/downloaded/file.txt",// Local path to save the fileoverwrite: true,createDirectories: true,};// Download the file from the gatewayconstdownloadResult=awaitdownloadFile(gatewayConfig,downloadOptions);if(downloadResult.success){console.log("Download result: ",downloadResult.data);}else{thrownewError("Failed to download file: "+(downloadResult.error||"Unknown error"));}console.log("Download result:",downloadResult);

Step 8: Query File Status on the Blockchain

// Check if the file is being processed by storage miners or already storedconstdealMap=awaitcess.queryDealMap(fid);if(dealMap){console.log("Storage order details: ",dealMap);console.log("File is being distributed to storage miners");}else{console.log("File has been stored on storage nodes");constfileMeta=awaitcess.queryFileByFid(fid);console.log("File metadata: ",fileMeta);}awaitcess.close()

Documentation

For more detailed documentation, please visit CESS official documentation.

License

This project is licensed under the Apache-2.0 License.

About

CESS Chain Interface Implementation in TypeScript

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages