Thanks to visit codestin.com
Credit goes to github.com

Skip to content

cheqd/sdk

TypeScript SDK for cheqd

GitHub release (latest by date) GitHub Release Date GitHub license

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

GitHub Workflow Status GitHub Workflow Status GitHub 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:

  • βœ… Create a did:cheqd method DID
  • βœ… Update a did:cheqd method DID
  • βœ… Deactivate a did:cheqd method DID
  • βœ… Create or update a DID-Linked Resource

🧰 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';
const wallet = await DirectSecp256k1HdWallet.fromMnemonic('your mnemonic here', { prefix: 'cheqd' }); // replace with your mnemonic, remember to keep it secure

// Set up the SDK options with fee abstraction capabilities
const sdkOptions = {
    modules: [
        FeeabstractionModule as unknown as AbstractCheqdSDKModule,
        // other modules can be added here
    ],
    // other SDK options can be configured here
    rpcUrl: 'https://rpc.cheqd.network', // or your preferred RPC endpoint
    network: CheqdNetwork.Testnet, // or CheqdNetwork.Mainnet
    wallet,
};

// Initialize SDK with fee abstraction support
const sdk = await createCheqdSDK(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 supported
const supportedIBCDenoms = [
  'ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4', // ATOM from Osmosis
  'ibc/14F9BC3E44B8A9C1BE1FB08980FAB87034C9905EF17CF2442BE1FA40E2E5F16', // OSMO from Osmosis
  // Add other supported IBC denominations
];

// Your account should have these IBC tokens available
async function checkIBCBalances(accountAddress: string) {
  const balances = await sdk.querier.bank.allBalances({ address: accountAddress });

  const ibcBalances = balances.balances.filter(balance =>
    balance.denom.startsWith('ibc/')
  );

  console.log('Available IBC tokens:', ibcBalances);
  return ibcBalances;
}

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

πŸ“Š Querying Fee Abstraction Data

Host Chain Configuration

async function queryHostChainConfig() {
  const configResponse = await sdk.querier[defaultFeeabstractionExtensionKey].hostChainConfig({
    // Query parameters can be added here if needed
  });

  console.log('Host chain configuration:', configResponse);
}

Module Balances

async function queryModuleBalances() {
  const balancesResponse = await sdk.querier[defaultFeeabstractionExtensionKey].feeabsModuleBalances({
    // Query parameters can be added here if needed
  });

  console.log('Fee abstraction module balances:', balancesResponse);
}

Osmosis TWAP Data

async function queryOsmosisTWAP() {
  const twapResponse = await sdk.querier[defaultFeeabstractionExtensionKey].osmosisArithmeticTwap({
    poolId: '1', // Pool ID on Osmosis
    baseAsset: 'uosmo',
    quoteAsset: 'ibc/ABC123...',
    startTime: new Date(Date.now() - 24 * 60 * 60 * 1000), // 24 hours ago
    endTime: new Date()
  });

  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';

async function proposeAddHostZone() {
  const hostZoneData: MsgAddHostZone = {
    authority: 'cheqd1gov...', // Governance authority address
    hostChainId: 'osmosis-1',
    connectionId: 'connection-0',
    ibcDenom: 'ibc/ABC123...',
    nativeDenom: 'uosmo',
    transferChannelId: 'channel-0',
    minSwapAmount: '1000'
  };

  const proposalResponse = await sdk.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

async function proposeUpdateHostZone() {
  const updateData = {
    authority: 'cheqd1gov...',
    hostChainId: 'osmosis-1',
    // Updated configuration parameters
    minSwapAmount: '2000' // New minimum swap amount
  };

  const updateResponse = await sdk.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

async function sendTWAPQuery() {
  const twapQueryResponse = await sdk.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

async function completeFeeAbstractionWorkflow() {
  try {
    // 1. Check account has IBC assets available
    const accountAddress = 'cheqd1sender...';
    const ibcBalances = await checkIBCBalances(accountAddress);
    
    if (ibcBalances.length === 0) {
      throw new Error('No IBC tokens available. Please bridge assets from Osmosis first.');
    }

    // 2. Query host chain configuration
    const hostConfig = await sdk.querier[defaultFeeabstractionExtensionKey].hostChainConfig({});
    console.log('Host chain config:', hostConfig);

    // 3. Query current module balances
    const moduleBalances = await sdk.querier[defaultFeeabstractionExtensionKey].feeabsModuleBalances({});
    console.log('Module balances:', moduleBalances);

    // 4. Use IBC tokens for transaction fees directly
    // Fee abstraction automatically handles the conversion behind the scenes
    console.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

async function handleFeeAbstractionErrors() {
  try {
    // Example: Using fee abstraction in a DID operation
    const didCreationResponse = await sdk.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');
    } else if (error.message.includes('invalid denom')) {
      console.error('Invalid IBC denomination provided');
      console.log('Check supported IBC denominations');
    } else if (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:

async function useWithDIDOperations() {
  // Create a DID document using fee abstraction for payment
  const didDocument = {
    // DID document structure
  };

  // Use IBC tokens for fee payment via fee abstraction
  const didCreationResponse = await sdk.createDidDocTx(
    'cheqd1creator...',
    didDocument,
    'key1',
    {
      amount: [{ denom: 'ibc/ABC123...', amount: '100000' }], // Pay with IBC tokens
      gas: '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

Telegram Discord Twitter LinkedIn Medium YouTube

About

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

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Contributors 17

Languages