Skip to content

Repository files navigation

TypeScript SDK for cheqd

GitHub release (latest by date)GitHub Release DateGitHub license

GitHub release (latest by date including pre-releases)GitHub commits since latest release (by date)GitHub contributors

GitHub Workflow StatusGitHub Workflow StatusGitHub repo size

ℹ️ Overview

The purpose of this @cheqd/sdk NPM package is to provide base functionality for interacting with cheqd network. It combines the Decentralized Identifier (DID) and DID-Linked Resources modules, putting them into a Cosmos transaction wrapper using CosmJS.

This package is consumed by other SDKs/libraries such as Veramo SDK for cheqd and Credo to add cheqd network support.

This package includes:

🆔 Features

Our identity documentation site provides tutorials for utilising the identity features on cheqd network.

With this SDK, developers are able to:

🧰 Tooling

  • Raw payload creator: Enables users to generate a valid raw DID payload which is ready to be populated, depending on the use case. For example, did-provider-cheqd leverages this helper in the CLI application.
  • Identity key converter: Enables users to convert specific key formats from different kinds of SDKs, by transforming the input keys into valid sign inputs for a cheqd specific DID transaction (e.g. createDidDocTx, updateDidDocTx). For example, the Veramo SDK for cheqd uses this helper to enable users to pass a key in a Veramo SDK specific format to a cheqd sign input keys interface.

💰 Fee Abstraction

The Cheqd SDK provides comprehensive fee abstraction functionality that allows users to pay transaction fees using IBC tokens from other chains instead of native CHEQ tokens. This feature enables cross-chain interoperability and improved user experience by allowing users to transact without holding native tokens.

Overview

Fee abstraction on Cheqd enables:

  • Cross-chain fee payments: Pay transaction fees using tokens from other Cosmos chains
  • Host zone management: Add and configure supported chains for fee abstraction
  • Automatic token swaps: Convert IBC tokens to CHEQ for fee payment behind the scenes
  • Module account funding: Provide liquidity for fee abstraction operations

📁 Module Files

The fee abstraction functionality is implemented in the following files:

CJS (CommonJS):

ESM (ECMAScript Modules):

🚀 Basic Usage

Setting up Fee Abstraction

import{createCheqdSDK,CheqdNetwork}from'@cheqd/sdk';// Create wallet instance (e.g., using DirectSecp256k1HdWallet from CosmJS)import{DirectSecp256k1HdWallet}from'@cosmjs/proto-signing';constwallet=awaitDirectSecp256k1HdWallet.fromMnemonic('your mnemonic here',{prefix: 'cheqd'});// replace with your mnemonic, remember to keep it secure// Set up the SDK options with fee abstraction capabilitiesconstsdkOptions={modules: [FeeabstractionModuleasunknownasAbstractCheqdSDKModule,// other modules can be added here],// other SDK options can be configured hererpcUrl: 'https://rpc.cheqd.network',// or your preferred RPC endpointnetwork: CheqdNetwork.Testnet,// or CheqdNetwork.Mainnet
wallet,};// Initialize SDK with fee abstraction supportconstsdk=awaitcreateCheqdSDK(sdkOptions);

💳 IBC Asset Requirements

Before using fee abstraction functionality, ensure that your account has the necessary IBC assets bridged from supported chains like Osmosis:

Bridging Assets from Osmosis

To use fee abstraction, you'll need to have IBC tokens in your Cheqd account that were bridged from Osmosis:

// Example IBC denominations that might be supportedconstsupportedIBCDenoms=['ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4',// ATOM from Osmosis'ibc/14F9BC3E44B8A9C1BE1FB08980FAB87034C9905EF17CF2442BE1FA40E2E5F16',// OSMO from Osmosis// Add other supported IBC denominations];// Your account should have these IBC tokens availableasyncfunctioncheckIBCBalances(accountAddress: string){constbalances=awaitsdk.querier.bank.allBalances({address: accountAddress});constibcBalances=balances.balances.filter(balance=>balance.denom.startsWith('ibc/'));console.log('Available IBC tokens:',ibcBalances);returnibcBalances;}

Note: To bridge assets from Osmosis to Cheqd, you can use:

📊 Querying Fee Abstraction Data

Host Chain Configuration

asyncfunctionqueryHostChainConfig(){constconfigResponse=awaitsdk.querier[defaultFeeabstractionExtensionKey].hostChainConfig({// Query parameters can be added here if needed});console.log('Host chain configuration:',configResponse);}

Module Balances

asyncfunctionqueryModuleBalances(){constbalancesResponse=awaitsdk.querier[defaultFeeabstractionExtensionKey].feeabsModuleBalances({// Query parameters can be added here if needed});console.log('Fee abstraction module balances:',balancesResponse);}

Osmosis TWAP Data

asyncfunctionqueryOsmosisTWAP(){consttwapResponse=awaitsdk.querier[defaultFeeabstractionExtensionKey].osmosisArithmeticTwap({poolId: '1',// Pool ID on OsmosisbaseAsset: 'uosmo',quoteAsset: 'ibc/ABC123...',startTime: newDate(Date.now()-24*60*60*1000),// 24 hours agoendTime: newDate()});console.log('TWAP data:',twapResponse);}

🏛️ Governance Operations

Fee abstraction supports governance proposals for configuration changes:

Adding a Host Zone

import{MsgAddHostZone}from'@cheqd/ts-proto/feeabstraction/feeabs/v1beta1/index';asyncfunctionproposeAddHostZone(){consthostZoneData: MsgAddHostZone={authority: 'cheqd1gov...',// Governance authority addresshostChainId: 'osmosis-1',connectionId: 'connection-0',ibcDenom: 'ibc/ABC123...',nativeDenom: 'uosmo',transferChannelId: 'channel-0',minSwapAmount: '1000'};constproposalResponse=awaitsdk.addHostZoneProposal(hostZoneData,'Add Osmosis as Host Zone',// Proposal title[{denom: 'ncheq',amount: '10000000000'}],// Deposit'cheqd1proposer...',// Proposer address{amount: [{denom: 'ncheq',amount: '5000'}],gas: '300000'});console.log('Host zone proposal submitted:',proposalResponse.transactionHash);}

Updating Host Zone Configuration

asyncfunctionproposeUpdateHostZone(){constupdateData={authority: 'cheqd1gov...',hostChainId: 'osmosis-1',// Updated configuration parametersminSwapAmount: '2000'// New minimum swap amount};constupdateResponse=awaitsdk.updateHostZoneProposal(updateData,'Update Osmosis Host Zone Configuration',[{denom: 'ncheq',amount: '10000000000'}],'cheqd1proposer...',{amount: [{denom: 'ncheq',amount: '5000'}],gas: '300000'});console.log('Update proposal submitted:',updateResponse.transactionHash);}

🔧 Advanced Configuration

TWAP Query for Price Data

asyncfunctionsendTWAPQuery(){consttwapQueryResponse=awaitsdk.sendQueryIbcDenomTWAP('cheqd1sender...','ibc/ABC123...',// IBC denomination{amount: [{denom: 'ncheq',amount: '5000'}],gas: '200000'},'Query TWAP for price data');console.log('TWAP query sent:',twapQueryResponse);}

Complete Fee Abstraction Workflow

asyncfunctioncompleteFeeAbstractionWorkflow(){try{// 1. Check account has IBC assets availableconstaccountAddress='cheqd1sender...';constibcBalances=awaitcheckIBCBalances(accountAddress);if(ibcBalances.length===0){thrownewError('No IBC tokens available. Please bridge assets from Osmosis first.');}// 2. Query host chain configurationconsthostConfig=awaitsdk.querier[defaultFeeabstractionExtensionKey].hostChainConfig({});console.log('Host chain config:',hostConfig);// 3. Query current module balancesconstmoduleBalances=awaitsdk.querier[defaultFeeabstractionExtensionKey].feeabsModuleBalances({});console.log('Module balances:',moduleBalances);// 4. Use IBC tokens for transaction fees directly// Fee abstraction automatically handles the conversion behind the scenesconsole.log('Fee abstraction is ready for use with IBC tokens');console.log('Fee abstraction workflow completed successfully');}catch(error){console.error('Fee abstraction workflow failed:',error);}}

📋 Error Handling

asyncfunctionhandleFeeAbstractionErrors(){try{// Example: Using fee abstraction in a DID operationconstdidCreationResponse=awaitsdk.createDidDocTx('cheqd1sender...',didDocument,'key1',{amount: [{denom: 'ibc/ABC123...',amount: '100000'}],gas: '300000'});}catch(error){if(error.message.includes('insufficient funds')){console.error('Account has insufficient IBC tokens');console.log('Please bridge more assets from Osmosis');}elseif(error.message.includes('invalid denom')){console.error('Invalid IBC denomination provided');console.log('Check supported IBC denominations');}elseif(error.message.includes('host zone not found')){console.error('Host zone not configured for this IBC token');}else{console.error('Unexpected fee abstraction error:',error);}}}

🔗 Integration with Other Modules

Fee abstraction can be used alongside other Cheqd SDK modules:

asyncfunctionuseWithDIDOperations(){// Create a DID document using fee abstraction for paymentconstdidDocument={// DID document structure};// Use IBC tokens for fee payment via fee abstractionconstdidCreationResponse=awaitsdk.createDidDocTx('cheqd1creator...',didDocument,'key1',{amount: [{denom: 'ibc/ABC123...',amount: '100000'}],// Pay with IBC tokensgas: '300000'});console.log('DID created with fee abstraction:',didCreationResponse.transactionHash);}

💡 Best Practices

  1. Bridge IBC Assets First: Ensure you have bridged the required IBC tokens from Osmosis before attempting to use fee abstraction
  2. Check Account Balances: Verify your account has sufficient IBC token balances before transactions
  3. Handle IBC Delays: Account for IBC token transfer delays in your application flow
  4. Validate Host Zones: Always verify that host zones are properly configured before using IBC tokens
  5. Error Recovery: Implement robust error handling for network and token-related issues
  6. Gas Estimation: Use appropriate gas limits for transactions using fee abstraction
  7. Monitor Supported Denominations: Keep track of which IBC denominations are supported for fee abstraction

For more detailed information about fee abstraction concepts and implementation, visit our fee abstraction documentation.

🧑‍💻 Developer Guide

Installing in ESM projects

To install this NPM package in a project that needs ESM builds, use our latest release channel to install the stable version:

npm install @cheqd/sdk@latest

To install beta releases instead, use our -develop releases from the beta channel:

npm install @cheqd/sdk@beta

Installing in CommonJS projects

To install this NPM package in a project that needs CommonJS builds, use our cjs release channel to install the latest stable CommonJS version:

npm install @cheqd/sdk@cjs

📖 Documentation

Our product documentation site explains how @cheqd/sdk is consumed in Veramo SDK for cheqd (as an example of how this package can be consumed).

💬 Community

Our Discord server is the primary chat channel for our open-source community, software developers, and node operators.

Please reach out to us there for discussions, help, and feedback on the project.

🙋 Find us elsewhere

TelegramDiscordTwitterLinkedInMediumYouTube

About

A TypeScript SDK built with CosmJS to interact with cheqd network ledger

Topics

Resources

Code of conduct

Security policy

Stars

8 stars

Watchers

5 watching

Forks

Releases

Used by

Contributors

Languages

Generated from cheqd/.github