- Notifications
You must be signed in to change notification settings - Fork1
Nuklai/hyperchain-js-sdk
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The Hyperchain SDK provides a modular and comprehensive interface for interacting with hyperchains(blockchains built using HyperSDK). It is designed to facilitate developers with functions ranging from network configurations to transaction management and complex warp operations.
- Node.js
v20.0.0
or later (for building from source) - Yarn
v1.22.0
or later (for building from source)
Feature | Status |
---|---|
Transaction Management | ✅ |
Continuous Block Monitoring | ✅ |
Fee Calculation | ✅ |
Auth | ✅ |
WebSocket | ✅ |
Creation of Custom Actions | ✅ |
State Management | ✅ |
RPC Services | ✅ |
Multi-Sig Support | 🚧 |
Cross-Chain Operations | 🚧 |
WASM-Based Programs | 🚧 |
✅ - Complete, 🚧 - In Progress
npm install @nuklai/hyperchain-sdk# oryarn add @nuklai/hyperchain-sdk
For building from source:
git clone https://github.com/nuklai/hyperchain-sdk.gitcd hyperchain-sdkyarnyarn build
npm publish --access public
import{HyperchainSDK}from'@nuklai/hyperchain-sdk'constsdk=newHyperchainSDK({baseApiUrl:'https://api-devnet.nuklaivm-dev.net:9650',blockchainId:'JopL8T69GBW1orW4ZkJ1TBRzF97KXaY8e64atDA1v2M12SNqm'})
Checking node health:
consthealthStatus=awaitsdk.rpcService.ping()console.log('Node Ping:',JSON.stringify(healthStatus,null,2))
Fetching network information:
constnetworkInfo=awaitsdk.rpcService.getNetworkInfo()console.log('Network Info:',JSON.stringify(networkInfo,null,2))
Generating key pairs:
import{HyperchainSDK,auth}from'@nuklai/hyperchain-sdk'const{ privateKey, publicKey}=auth.BLSFactory.generateKeyPair()console.log('Generated BLS Private Key:',auth.BLSFactory.privateKeyToHex(privateKey))console.log('Generated BLS Public Key:',auth.BLS.publicKeyToHex(publicKey))
Submitting a transaction:
import{HyperchainSDK,actions,auth,codec,consts,utils}from'@nuklai/hyperchain-sdk'// Initialize SDKconstsdk=newHyperchainSDK({baseApiUrl:'https://api-devnet.nuklaivm-dev.net:9650',blockchainId:'JopL8T69GBW1orW4ZkJ1TBRzF97KXaY8e64atDA1v2M12SNqm'})// Create auth factoryconstauthFactory=auth.getAuthFactory('ed25519','323b1d8f4eed5f0da9da93071b034f2dce9d2d22692c172f3cb252a64ddfafd01b057de320297c29ad0c1f589ea216869cf1938d88c9fbd70d6748323dbf2fa7')// Create transfer actionconsttransfer=newactions.Transfer('nuklai1qqydg3pvjx5f9n8rytn5swyznftupw8lkc240l6apzqdxy4hsgmgkmzazes','NAI',utils.parseBalance(0.0001,9),'Test Memo')// Set up genesis info and registriesconstgenesisInfo={baseUnits:1,storageKeyReadUnits:5,storageValueReadUnits:2,storageKeyAllocateUnits:20,storageValueAllocateUnits:5,storageKeyWriteUnits:10,storageValueWriteUnits:3,validityWindow:60000}constactionRegistry=newcodec.TypeParser()actionRegistry.register(consts.TRANSFER_ID,actions.Transfer.fromBytesCodec,false)constauthRegistry=newcodec.TypeParser()authRegistry.register(consts.BLS_ID,auth.BLS.fromBytesCodec,false)authRegistry.register(consts.ED25519_ID,auth.ED25519.fromBytesCodec,false)authRegistry.register(consts.SECP256R1_ID,auth.SECP256R1.fromBytesCodec,false)// Generate and submit transactionconst{ submit, txSigned, err}=awaitsdk.rpcService.generateTransaction(genesisInfo,actionRegistry,authRegistry,[transfer],authFactory)if(err){throwerr}awaitsubmit()console.log('Transaction ID:',txSigned.id().toString())
import{HyperchainSDK}from'@nuklai/hyperchain-sdk'asyncfunctionlistenForBlocks(){constsdk=newHyperchainSDK({baseApiUrl:'https://api-devnet.nuklaivm-dev.net:9650',blockchainId:'JopL8T69GBW1orW4ZkJ1TBRzF97KXaY8e64atDA1v2M12SNqm'})try{awaitsdk.wsService.connect()consterr=awaitsdk.wsService.registerBlocks()if(err){console.error("Failed to register blocks:",err)return}while(true){try{const{ block, results, prices, err}=awaitsdk.wsService.listenBlock(sdk.actionRegistry,sdk.authRegistry)if(err){console.error('Failed to listen for blocks:',err)continue}console.log('Incoming block:',block.toJSON())console.log('Results:',results)console.log('Prices:',prices)}catch(error){console.error('Error:',error)}}}catch(error){console.error('Error connecting to WebSocket:',error)}finally{awaitsdk.wsService.close()}}listenForBlocks().catch(console.error)
Theexamples directory contains various example code to interact with the Hyperchain SDK.
TheTransaction
class covers the structure and behavior of transactions.
Key methods:
sign(factory: AuthFactory, actionRegistry: ActionRegistry, authRegistry: AuthRegistry): [Transaction, Error?]
toBytes(): [Uint8Array, Error?]
fromBytes(bytes: Uint8Array, actionRegistry: ActionRegistry, authRegistry: AuthRegistry): [Transaction, Error?]
TheStatefulBlock
class represents a block in the blockchain.
Key methods:
id(): Promise<Id>
toBytes(): [Uint8Array, Error?]
fromBytes(bytes: Uint8Array, actionRegistry: ActionRegistry, authRegistry: AuthRegistry): [StatefulBlock, Error?]
TheestimateUnits
function calculates transaction fees based on resource usage:
functionestimateUnits(genesisInfo:Genesis,actions:Action[],authFactory:AuthFactory):Dimension
Key interfaces:
Auth
AuthFactory
Key function:
functiongetAuthFactory(authType:AuthType,privateKeyString:string):AuthFactory
TheWebSocketService
class provides real-time communication with any HyperSDK based blockchains.
Key methods:
connect(): Promise<void>
listenBlock(actionRegistry: ActionRegistry, authRegistry: AuthRegistry): Promise<{ block: StatefulBlock; results: Array<Result>; prices: Dimension; err: Error | undefined; }>
close(): Promise<void>
To implement a custom action:
- Define a new class implementing the
Action
interface. - Implement
toBytes()
,fromBytes()
, and other required methods. - Register the new action type with the
ActionRegistry
.
Most methods in the SDK return a tuple[result, error]
. Always check for errors before using the result:
const[result,error]=awaitsomeSDKMethod()if(error){console.error('An error occurred:',error)// Handle error}else{// Use the result}
- Use secure connections (HTTPS) when connecting to endpoints.
- Validate all inputs, especially those used in transaction creation.
- Use WebSocket connections for real-time updates instead of polling.
- Implement proper error handling and retries for network operations.
- Consider batching multiple actions into a single transaction when appropriate.
Common issues and their solutions:
- Connection errors: Verify network settings and firewall configurations.
- Transaction failures: Check balance, fee estimation, and action validity.
- WebSocket disconnections: Implement reconnection logic with exponential backoff.
For further assistance, please reach out tokiran.pachhai@nukl.ai
orsay@nukl.ai
, or create an issue in this repository.
Contributions to the Hyperchain SDK are welcome! Please ensure that your code adheres to the existing style and include tests for new features.
This SDK is released under theMIT License.
- Author: Kiran Pachhaikiran.pachhai@nukl.ai
- Contributor: Shodipo Ayomidesay@nukl.ai
About
(deprecated)
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.