@cheqd/sdk
Version:
A TypeScript SDK built with CosmJS to interact with the cheqd network ledger
305 lines • 13.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FeemarketModule = exports.setupFeemarketExtension = exports.defaultGasPriceTiers = exports.typeUrlParamsResponse = exports.typeUrlGasPricesResponse = exports.typeUrlGasPriceResponse = exports.protobufLiterals = exports.defaultFeemarketExtensionKey = void 0;
exports.isGasPriceEncodeObject = isGasPriceEncodeObject;
exports.isGasPricesEncodeObject = isGasPricesEncodeObject;
exports.isParamsEncodeObject = isParamsEncodeObject;
const index_js_1 = require("@cheqd/ts-proto-cjs/feemarket/feemarket/v1/index.js");
const stargate_cjs_1 = require("@cosmjs/stargate-cjs");
const _1 = require("./_");
const utils_1 = require("../utils");
const math_cjs_1 = require("@cosmjs/math-cjs");
/** Default extension key for fee market-related query operations */
exports.defaultFeemarketExtensionKey = 'feemarket';
/**
* Protobuf message type literals for fee market operations.
* Used for consistent message type identification across the module.
*/
exports.protobufLiterals = {
/** Gas price response message type */
GasPriceResponse: 'GasPriceResponse',
/** Gas prices response message type */
GasPricesResponse: 'GasPricesResponse',
/** Parameters response message type */
ParamsResponse: 'ParamsResponse',
};
/** Type URL for GasPriceResponse messages */
exports.typeUrlGasPriceResponse = `/${index_js_1.protobufPackage}.${exports.protobufLiterals.GasPriceResponse}`;
/** Type URL for GasPricesResponse messages */
exports.typeUrlGasPricesResponse = `/${index_js_1.protobufPackage}.${exports.protobufLiterals.GasPricesResponse}`;
/** Type URL for ParamsResponse messages */
exports.typeUrlParamsResponse = `/${index_js_1.protobufPackage}.${exports.protobufLiterals.ParamsResponse}`;
/**
* Default gas price tier names for fee calculation.
* Provides predefined tiers for different transaction priority levels.
*/
exports.defaultGasPriceTiers = {
/** Low priority tier with lowest gas prices */
Low: 'DefaultLowTier',
/** Average priority tier with moderate gas prices */
Avg: 'DefaultAvgTier',
/** High priority tier with highest gas prices */
High: 'DefaultHighTier',
};
/**
* Type guard function to check if an object is a GasPriceEncodeObject.
*
* @param obj - EncodeObject to check
* @returns True if the object is a GasPriceEncodeObject
*/
function isGasPriceEncodeObject(obj) {
return obj.typeUrl === exports.typeUrlGasPriceResponse;
}
/**
* Type guard function to check if an object is a GasPricesEncodeObject.
*
* @param obj - EncodeObject to check
* @returns True if the object is a GasPricesEncodeObject
*/
function isGasPricesEncodeObject(obj) {
return obj.typeUrl === exports.typeUrlGasPricesResponse;
}
/**
* Type guard function to check if an object is a ParamsEncodeObject.
*
* @param obj - EncodeObject to check
* @returns True if the object is a ParamsEncodeObject
*/
function isParamsEncodeObject(obj) {
return obj.typeUrl === exports.typeUrlParamsResponse;
}
/**
* Sets up the fee market extension for the querier client.
* Creates and configures the fee market-specific query methods.
*
* @param base - Base QueryClient to extend
* @returns Configured fee market extension with query methods
*/
const setupFeemarketExtension = (base) => {
const rpc = (0, stargate_cjs_1.createProtobufRpcClient)(base);
const queryService = new index_js_1.QueryClientImpl(rpc);
return {
[exports.defaultFeemarketExtensionKey]: {
gasPrice: async (denom) => {
return queryService.GasPrice({ denom });
},
gasPrices: async () => {
return queryService.GasPrices({});
},
params: async () => {
return queryService.Params({});
},
},
};
};
exports.setupFeemarketExtension = setupFeemarketExtension;
/**
* Fee Market Module class providing comprehensive fee market functionality.
* Handles gas price queries, dynamic fee calculation, and fee market parameter management.
*/
class FeemarketModule extends _1.AbstractCheqdSDKModule {
//@ts-expect-error underlying type `GeneratedType` is intentionally wider
static registryTypes = [
[exports.typeUrlGasPriceResponse, index_js_1.GasPriceResponse],
[exports.typeUrlGasPricesResponse, index_js_1.GasPricesResponse],
[exports.typeUrlParamsResponse, index_js_1.ParamsResponse],
];
/**
* Default gas prices for different priority tiers.
* Used as fallback when live gas price queries are unavailable.
*/
static defaultGasPrices = {
[exports.defaultGasPriceTiers.Low]: { amount: '5000', denom: 'ncheq' },
[exports.defaultGasPriceTiers.Avg]: { amount: '7500', denom: 'ncheq' },
[exports.defaultGasPriceTiers.High]: { amount: '10000', denom: 'ncheq' },
};
/** Gas offset factor used for adjusting live gas prices */
static gasOffsetFactor = 10 ** 4;
/** Address of the fee collector account that receives transaction fees */
static feeCollectorAddress = 'cheqd13pxn9n3qw79e03844rdadagmg0nshmwfszqu0g';
/** Address of the fee market module account */
static moduleAccountAddress = 'cheqd1el68mjnzv87uurqks8u29tec0cj3297047g2dl';
/** Querier extension setup function for fee market operations */
static querierExtensionSetup = exports.setupFeemarketExtension;
/** Querier instance with fee market extension capabilities */
/** Querier instance with fee market extension capabilities */
querier;
/**
* Constructs a new fee market module instance.
*
* @param signer - Signing client for blockchain transactions
* @param querier - Querier client with fee market extension for data retrieval
*/
constructor(signer, querier) {
super(signer, querier);
this.querier = querier;
this.methods = {
queryGasPrice: this.queryGasPrice.bind(this),
queryGasPrices: this.queryGasPrices.bind(this),
queryParams: this.queryParams.bind(this),
generateGasPrice: this.generateGasPrice.bind(this),
generateOfflineGasPrice: this.generateOfflineGasPrice.bind(this),
generateSafeGasPrice: this.generateSafeGasPrice.bind(this),
generateSafeGasPriceWithExponentialBackoff: this.generateSafeGasPriceWithExponentialBackoff.bind(this),
};
}
/**
* Gets the registry types for fee market message encoding/decoding.
*
* @returns Iterable of [typeUrl, GeneratedType] pairs for the registry
*/
getRegistryTypes() {
return FeemarketModule.registryTypes;
}
/**
* Gets the querier extension setup for fee market operations.
*
* @returns Query extension setup function for fee market functionality
*/
getQuerierExtensionSetup() {
return FeemarketModule.querierExtensionSetup;
}
/**
* Queries the current gas price for a specific denomination.
* Retrieves live gas price data from the fee market module.
*
* @param denom - Token denomination to query gas price for
* @param context - Optional SDK context for accessing clients
* @returns Promise resolving to the gas price response
*/
async queryGasPrice(denom, context) {
if (!this.querier)
this.querier = context.sdk.querier;
return this.querier[exports.defaultFeemarketExtensionKey].gasPrice(denom);
}
/**
* Queries all available gas prices from the fee market.
* Retrieves comprehensive gas pricing information for all denominations.
*
* @param context - Optional SDK context for accessing clients
* @returns Promise resolving to the gas prices response
*/
async queryGasPrices(context) {
if (!this.querier)
this.querier = context.sdk.querier;
return this.querier[exports.defaultFeemarketExtensionKey].gasPrices();
}
/**
* Queries the fee market module parameters.
* Retrieves configuration settings for the fee market functionality.
*
* @param context - Optional SDK context for accessing clients
* @returns Promise resolving to the parameters response
*/
async queryParams(context) {
if (!this.querier)
this.querier = context.sdk.querier;
return this.querier[exports.defaultFeemarketExtensionKey].params();
}
/**
* Generates gas price for a denomination by live polling the fee market.
* Queries current gas prices and adjusts them using the gas offset factor.
* Throws an error if live polling fails.
*
* @param denom - Token denomination to generate gas price for
* @param context - Optional SDK context for accessing clients
* @returns Promise resolving to the calculated gas price
* @throws Error if live poll for gas price fails or returns invalid data
*/
async generateGasPrice(denom, context) {
if (!this.querier)
this.querier = context.sdk.querier;
// query gas price, bubble up error, no catch
const gasPrice = await this.queryGasPrice(denom, context);
// validate gas price
if (!gasPrice.price)
throw new Error('Invalid gas price: live poll for gas price failed');
// convert gas price through offset factor
const adjustedGasPrice = math_cjs_1.Decimal.fromAtomics(gasPrice.price.amount, 18)
.multiply(math_cjs_1.Uint32.fromString(FeemarketModule.gasOffsetFactor.toString()))
.toString();
// safe convert gas price to string
return stargate_cjs_1.GasPrice.fromString(`${adjustedGasPrice}${gasPrice.price.denom}`);
}
/**
* Generates offline gas price for a denomination using static tier pricing.
* Uses predefined gas prices as fallback when live polling is unavailable.
*
* @param denom - Token denomination to generate gas price for
* @param tier - Priority tier for gas price calculation (defaults to Low)
* @returns Promise resolving to the static gas price
* @throws Error if denomination or tier is invalid
*/
async generateOfflineGasPrice(denom, tier = exports.defaultGasPriceTiers.Low) {
// validate denom against default
if (!Object.values(FeemarketModule.defaultGasPrices).some((gp) => gp.denom === denom))
throw new Error(`Invalid denom: ${denom}`);
// validate tier against default
if (!Object.keys(FeemarketModule.defaultGasPrices).includes(tier))
throw new Error(`Invalid tier: ${tier}`);
// generate gas price
const gasPrice = FeemarketModule.defaultGasPrices[tier];
// safe convert gas price to string
return stargate_cjs_1.GasPrice.fromString(`${gasPrice.amount}${gasPrice.denom}`);
}
/**
* Generates safe gas price with automatic fallback to offline pricing.
* Attempts live polling first, falls back to static tier pricing if it fails.
*
* @param denom - Token denomination to generate gas price for
* @param tier - Priority tier for fallback gas price calculation (defaults to Low)
* @param context - Optional SDK context for accessing clients
* @returns Promise resolving to the gas price (live or fallback)
*/
async generateSafeGasPrice(denom, tier = exports.defaultGasPriceTiers.Low, context) {
if (!this.querier)
this.querier = context.sdk.querier;
try {
// generate gas price
return await this.generateGasPrice(denom, context);
}
catch (error) {
// generate offline gas price
return await this.generateOfflineGasPrice(denom, tier);
}
}
/**
* Generates safe gas price with exponential backoff retry mechanism.
* Retries live polling with exponential backoff before falling back to offline pricing.
*
* @param denom - Token denomination to generate gas price for
* @param tier - Priority tier for fallback gas price calculation (defaults to Low)
* @param backoffOptions - Retry configuration options (defaults to DefaultBackoffOptions)
* @param context - Optional SDK context for accessing clients
* @returns Promise resolving to the gas price (live with retries or fallback)
*/
async generateSafeGasPriceWithExponentialBackoff(denom, tier = exports.defaultGasPriceTiers.Low, backoffOptions = utils_1.DefaultBackoffOptions, context) {
if (!this.querier)
this.querier = context.sdk.querier;
// live poll for gas price
const gasPrice = await (0, utils_1.retry)(() => this.generateGasPrice(denom, context), backoffOptions);
// return, if applicable
if (gasPrice)
return gasPrice;
// otherwise, generate offline gas price
return await this.generateOfflineGasPrice(denom, tier);
}
/**
* Generates transaction fees from a given gas price.
* Calculates the total fee amount based on gas price and gas limit.
*
* @param gasPrice - Gas price to use for fee calculation
* @param payer - Address of the account paying the transaction fees
* @param gas - Gas limit for the transaction (defaults to '200000')
* @returns Standard fee configuration for the transaction
*/
static generateFeesFromGasPrice(gasPrice, payer, gas = '200000') {
return {
amount: [{ denom: gasPrice.denom, amount: gasPrice.amount.multiply(math_cjs_1.Uint32.fromString(gas)).toString() }],
gas,
payer,
};
}
}
exports.FeemarketModule = FeemarketModule;
//# sourceMappingURL=feemarket.js.map