@cheqd/sdk
Version:
A TypeScript SDK built with CosmJS to interact with the cheqd network ledger
182 lines • 10.8 kB
JavaScript
import { DIDModule } from './modules/did.js';
import { ResourceModule } from './modules/resource.js';
import { FeemarketModule, defaultGasPriceTiers, } from './modules/feemarket.js';
import { applyMixins, instantiateCheqdSDKModule, instantiateCheqdSDKModuleRegistryTypes, instantiateCheqdSDKModuleQuerierExtensionSetup, } from './modules/_.js';
import { createDefaultCheqdRegistry } from './registry.js';
import { CheqdSigningStargateClient } from './signer.js';
import { CheqdNetwork } from './types.js';
import { QueryClient } from '@cosmjs/stargate';
import { CheqdQuerier } from './querier.js';
import { FeeabstractionModule, } from './modules/feeabstraction.js';
/**
* Main CheqdSDK class that provides a comprehensive interface for interacting with the Cheqd blockchain.
* This class orchestrates modules for DID operations, resource management, fee market interactions,
* and fee abstraction functionality.
*/
export class CheqdSDK {
/** Map of available methods from loaded modules */
methods;
/** Signing client for executing transactions on the blockchain */
signer;
/** Query client with extensions for reading blockchain data */
querier;
/** Configuration options passed during SDK initialization */
options;
/** List of method names that are protected from external access */
protectedMethods = ['constructor', 'build', 'loadModules', 'loadRegistry'];
/**
* Constructs a new CheqdSDK instance with the provided configuration options.
*
* @param options - Configuration options for the SDK including wallet, modules, and network settings
* @throws {Error} Throws an error if no wallet is provided in the options
*/
constructor(options) {
if (!options?.wallet) {
throw new Error('No wallet provided');
}
this.options = {
authorizedMethods: [],
network: CheqdNetwork.Testnet,
...options,
};
this.methods = {};
this.signer = new CheqdSigningStargateClient(undefined, this.options.wallet, {});
this.querier = new QueryClient({});
}
/**
* Executes a method from the loaded modules with the provided parameters.
* Only authorized methods can be executed through this interface.
*
* @template P - Type of parameters to pass to the method
* @template R - Return type of the method
* @param method - Name of the method to execute
* @param params - Parameters to pass to the method
* @returns Promise resolving to the method's return value
* @throws {Error} Throws an error if the method is not authorized
*/
async execute(method, ...params) {
if (!Object.keys(this.methods).includes(method)) {
throw new Error(`Method ${method} is not authorized`);
}
return await this.methods[method](...params, { sdk: this });
}
/**
* Loads and instantiates the provided modules, making their methods available for execution.
* This method also applies mixins to make module methods accessible on the SDK instance.
*
* @param modules - Array of modules to load and integrate
* @returns Promise resolving to the CheqdSDK instance with loaded modules
* @private
*/
async loadModules(modules) {
this.options.modules = this.options.modules.map((module) => instantiateCheqdSDKModule(module, this.signer, this.querier, {
sdk: this,
}));
const methods = applyMixins(this, modules);
this.methods = {
...this.methods,
...filterUnauthorizedMethods(methods, this.options.authorizedMethods || [], this.protectedMethods),
};
for (const method of Object.keys(this.methods)) {
// @ts-ignore
this[method] = async (...params) => {
return await this.execute(method, ...params);
};
}
return this;
}
/**
* Creates and configures a registry with types from all loaded modules.
* The registry is used for encoding and decoding blockchain messages.
*
* @returns Configured Registry instance with all module types
* @private
*/
loadRegistry() {
const registryTypes = this.options.modules
.map((module) => instantiateCheqdSDKModuleRegistryTypes(module))
.reduce((acc, types) => {
return [...acc, ...types];
});
return createDefaultCheqdRegistry(registryTypes);
}
/**
* Establishes a connection to the blockchain querier with all necessary extensions.
* Extensions provide specialized query capabilities for different modules.
*
* @returns Promise resolving to a CheqdQuerier instance with all extensions
* @private
*/
async loadQuerierExtensions() {
const querierExtensions = this.options.modules.map((module) => instantiateCheqdSDKModuleQuerierExtensionSetup(module));
const querier = await CheqdQuerier.connectWithExtensions(this.options.rpcUrl, ...querierExtensions);
return querier;
}
/**
* Builds and initializes the complete SDK instance by loading all components:
* registry, querier extensions, modules, gas price configuration, and signing client.
* This method must be called before the SDK can be used for blockchain operations.
*
* @returns Promise resolving to the fully initialized CheqdSDK instance
*/
async build() {
const registry = this.loadRegistry();
this.querier = await this.loadQuerierExtensions();
// ensure feemarket module is loaded, if not already
if (!this.options.modules.find((module) => module instanceof FeemarketModule)) {
this.options.modules.push(FeemarketModule);
}
const sdk = await this.loadModules(this.options.modules);
// define gas price
this.options.gasPrice =
this.options.gasPrice ||
(await this.generateSafeGasPriceWithExponentialBackoff(DIDModule.baseMinimalDenom, defaultGasPriceTiers.Low, undefined, { sdk }));
this.signer = await CheqdSigningStargateClient.connectWithSigner(this.options.rpcUrl, this.options.wallet, {
registry,
gasPrice: this.options.gasPrice,
});
return sdk;
}
}
/**
* Filters methods based on authorization rules and protected method restrictions.
* Returns only methods that are explicitly authorized (if authorization list is provided)
* and excludes protected methods from external access.
*
* @param methods - Map of all available methods from modules
* @param authorizedMethods - List of method names that are explicitly authorized
* @param protectedMethods - List of method names that should be protected from external access
* @returns Filtered map containing only authorized and non-protected methods
*/
export function filterUnauthorizedMethods(methods, authorizedMethods, protectedMethods) {
let _methods = Object.keys(methods);
if (authorizedMethods.length === 0)
return _methods
.filter((method) => !protectedMethods.includes(method))
.reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {});
return _methods
.filter((method) => authorizedMethods.includes(method) && !protectedMethods.includes(method))
.reduce((acc, method) => ({ ...acc, [method]: methods[method] }), {});
}
/**
* Factory function that creates and builds a fully initialized CheqdSDK instance.
* This is the recommended way to create an SDK instance as it handles all initialization steps.
*
* @param options - Configuration options for the SDK including wallet, modules, and network settings
* @returns Promise resolving to a fully initialized and ready-to-use CheqdSDK instance
*/
export async function createCheqdSDK(options) {
return await new CheqdSDK(options).build();
}
export { DIDModule, ResourceModule, FeemarketModule, FeeabstractionModule };
export { AbstractCheqdSDKModule, applyMixins } from './modules/_.js';
export { MsgCreateDidDocResponseEncodeObject, MsgUpdateDidDocEncodeObject, MsgUpdateDidDocResponseEncodeObject, MsgDeactivateDidDocEncodeObject, contexts, defaultDidExtensionKey, protobufLiterals as protobufLiteralsDid, typeUrlMsgCreateDidDoc, typeUrlMsgCreateDidDocResponse, typeUrlMsgUpdateDidDoc, typeUrlMsgUpdateDidDocResponse, typeUrlMsgDeactivateDidDoc, typeUrlMsgDeactivateDidDocResponse, setupDidExtension, isMsgCreateDidDocEncodeObject, isMsgUpdateDidDocEncodeObject, isMsgDeactivateDidDocEncodeObject, } from './modules/did.js';
export { defaultResourceExtensionKey, protobufLiterals as protobufLiteralsResource, typeUrlMsgCreateResource, typeUrlMsgCreateResourceResponse, setupResourceExtension, isMsgCreateResourceEncodeObject, } from './modules/resource.js';
export { defaultFeemarketExtensionKey, defaultGasPriceTiers, protobufLiterals as protobufLiteralsFeemarket, typeUrlGasPriceResponse, typeUrlGasPricesResponse, typeUrlParamsResponse, setupFeemarketExtension, isGasPriceEncodeObject, isGasPricesEncodeObject, isParamsEncodeObject, } from './modules/feemarket.js';
export { defaultFeeabstractionExtensionKey, protobufLiterals as protobufLiteralsFeeabstraction, typeUrlMsgAddHostZone, typeUrlMsgAddHostZoneResponse, typeUrlMsgFundFeeAbsModuleAccount, typeUrlMsgFundFeeAbsModuleAccountResponse, typeUrlMsgRemoveHostZone, typeUrlMsgRemoveHostZoneResponse, typeUrlMsgUpdateHostZone, typeUrlMsgUpdateHostZoneResponse, typeUrlMsgSendQueryIbcDenomTWAP, typeUrlMsgSendQueryIbcDenomTWAPResponse, typeUrlMsgSwapCrossChain, typeUrlMsgSwapCrossChainResponse, typeUrlMsgUpdateParams, typeUrlMsgUpdateParamsResponse, setupFeeabstractionExtension, isMsgAddHostZoneEncodeObject, isMsgAddHostZoneResponseEncodeObject, isMsgFundFeeAbsModuleAccountEncodeObject, isMsgFundFeeAbsModuleAccountResponseEncodeObject, isMsgRemoveHostZoneEncodeObject, isMsgRemoveHostZoneResponseEncodeObject, isMsgUpdateHostZoneEncodeObject, isMsgUpdateHostZoneResponseEncodeObject, isMsgSendQueryIbcDenomTWAPEncodeObject, isMsgSendQueryIbcDenomTWAPResponseEncodeObject, isMsgSwapCrossChainEncodeObject, isMsgSwapCrossChainResponseEncodeObject, isMsgUpdateParamsEncodeObject, isMsgUpdateParamsResponseEncodeObject, } from './modules/feeabstraction.js';
export * from './signer.js';
export * from './querier.js';
export * from './registry.js';
export * from './types.js';
export { TImportableEd25519Key, createKeyPairRaw, createKeyPairBase64, createKeyPairHex, createVerificationKeys, createDidVerificationMethod, createDidPayload, createSignInputsFromImportableEd25519Key, validateSpecCompliantPayload, isEqualKeyValuePair, createCosmosPayerWallet, getCosmosAccount, checkBalance, toMultibaseRaw, } from './utils.js';
//# sourceMappingURL=index.js.map