ault-sdk-ts 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -38,6 +38,7 @@ __export(index_exports, {
38
38
  BondStatus: () => BondStatus,
39
39
  COIN_TYPE: () => COIN_TYPE,
40
40
  DEFAULT_CHAIN_ID: () => DEFAULT_CHAIN_ID,
41
+ DEFAULT_RETRYABLE_STATUSES: () => DEFAULT_RETRYABLE_STATUSES,
41
42
  DexWsClient: () => DexWsClient,
42
43
  EIP712_DOMAIN_TYPE: () => EIP712_DOMAIN_TYPE,
43
44
  EIP712_MSG_TYPES: () => EIP712_MSG_TYPES,
@@ -113,6 +114,7 @@ __export(index_exports, {
113
114
  SDK_VERSION: () => SDK_VERSION,
114
115
  SIGN_MODE_DIRECT: () => SIGN_MODE_DIRECT,
115
116
  SIGN_MODE_LEGACY_AMINO_JSON: () => SIGN_MODE_LEGACY_AMINO_JSON,
117
+ SIMULATION_PLACEHOLDER_PUBKEY: () => SIMULATION_PLACEHOLDER_PUBKEY,
116
118
  SearchUDFSymbolsQueryParams: () => SearchUDFSymbolsQueryParams,
117
119
  SearchUDFSymbolsResponse: () => SearchUDFSymbolsResponse,
118
120
  SearchUDFSymbolsResponseItem: () => SearchUDFSymbolsResponseItem,
@@ -122,6 +124,7 @@ __export(index_exports, {
122
124
  TxConfirmationUnavailableError: () => TxConfirmationUnavailableError,
123
125
  TxError: () => TxError,
124
126
  TxNotConfirmedError: () => TxNotConfirmedError,
127
+ TxSimulationError: () => TxSimulationError,
125
128
  ValidatorStatus: () => BondStatus,
126
129
  WebSocketError: () => WebSocketError,
127
130
  WithdrawRewardsPartialError: () => WithdrawRewardsPartialError,
@@ -144,6 +147,7 @@ __export(index_exports, {
144
147
  computeFeeFreeGas: () => computeFeeFreeGas,
145
148
  computeFeeFreeGasCompound: () => computeFeeFreeGasCompound,
146
149
  computeRequiredFee: () => computeRequiredFee,
150
+ computeSimulatedGas: () => computeSimulatedGas,
147
151
  cosmosDecToDecimalString: () => cosmosDecToDecimalString,
148
152
  cosmosDecToProtoInt: () => cosmosDecToProtoInt,
149
153
  createAccountCache: () => createAccountCache,
@@ -307,6 +311,7 @@ __export(index_exports, {
307
311
  resolveSignerAddress: () => resolveSignerAddress,
308
312
  signAndBroadcastAgentTx: () => signAndBroadcastAgentTx,
309
313
  signAndBroadcastEip712: () => signAndBroadcastEip712,
314
+ simulateTx: () => simulateTx,
310
315
  stripEip712Domain: () => stripEip712Domain,
311
316
  toViemChain: () => toViemChain,
312
317
  validateEip712FieldOrder: () => validateEip712FieldOrder,
@@ -455,6 +460,14 @@ var TxError = class extends Error {
455
460
  this.confirmed = params.confirmed;
456
461
  }
457
462
  };
463
+ var TxSimulationError = class extends Error {
464
+ constructor(params) {
465
+ super(`Transaction simulation failed: ${params.rawLog}`);
466
+ this.name = "TxSimulationError";
467
+ this.chainCode = params.chainCode;
468
+ this.rawLog = params.rawLog;
469
+ }
470
+ };
458
471
  var TxNotConfirmedError = class extends TxError {
459
472
  constructor(params) {
460
473
  super(
@@ -501,13 +514,14 @@ var WithdrawRewardsPartialError = class extends Error {
501
514
  };
502
515
 
503
516
  // src/core/http.ts
517
+ var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
504
518
  var DEFAULT_OPTIONS = {
505
519
  timeout: 3e4,
506
520
  retries: 3,
507
521
  retryDelay: 1e3,
508
522
  exponentialBackoff: true,
509
523
  retryableMethods: ["GET", "HEAD", "OPTIONS"],
510
- retryableStatuses: [408, 429, 500, 502, 503, 504],
524
+ retryableStatuses: [...DEFAULT_RETRYABLE_STATUSES],
511
525
  retryOnTimeout: false
512
526
  };
513
527
  function ensureFetch(fetchFn) {
@@ -746,6 +760,8 @@ var GAS_CONSTANTS = {
746
760
  DENOM: "aault",
747
761
  /** Chain multiplier applied to min gas to derive max gas (120 = 1.2×). */
748
762
  FEE_FREE_GAS_MULTIPLIER: 120,
763
+ /** Headroom over simulated `gas_used` (130 = 1.3×). */
764
+ SIMULATED_GAS_MULTIPLIER: 130,
749
765
  // License module
750
766
  PER_LICENSE: 2e5,
751
767
  PER_KYC_MEMBER: 2e5,
@@ -776,11 +792,19 @@ var GAS_CONSTANTS = {
776
792
  // Accountx module
777
793
  OPEN_ACCOUNT: 96e3,
778
794
  // Staking module (cosmos-sdk standard, NOT fee-free — user pays gas).
795
+ // Staking gas depends on the delegator's state, so the builders simulate;
796
+ // these are the fallback (×FEE_FREE_GAS_MULTIPLIER) when simulate is down.
779
797
  DELEGATE: 22e4,
780
- UNDELEGATE: 22e4,
781
- BEGIN_REDELEGATE: 28e4,
798
+ UNDELEGATE: 26e4,
799
+ BEGIN_REDELEGATE: 4e5,
782
800
  WITHDRAW_DELEGATOR_REWARD: 22e4
783
801
  };
802
+ function computeSimulatedGas(gasUsed, multiplier = GAS_CONSTANTS.SIMULATED_GAS_MULTIPLIER) {
803
+ if (!Number.isInteger(multiplier) || multiplier < 100) {
804
+ throw new Error(`simulated gas multiplier must be an integer >= 100, got ${multiplier}`);
805
+ }
806
+ return (gasUsed * BigInt(multiplier) / 100n).toString();
807
+ }
784
808
  function computeFeeFreeGas(minGasPerOp, count, multiplier = GAS_CONSTANTS.FEE_FREE_GAS_MULTIPLIER) {
785
809
  return (BigInt(minGasPerOp) * BigInt(count) * BigInt(multiplier) / 100n).toString();
786
810
  }
@@ -15739,253 +15763,6 @@ function buildEip712TypedData(context, msgs, evmChainId) {
15739
15763
  };
15740
15764
  }
15741
15765
 
15742
- // src/rest/feemarket.ts
15743
- async function fetchFeeMarketParams(network, fetchFn, fetchOptions) {
15744
- const data = await fetchJson(
15745
- `${network.restUrl}/cosmos/evm/feemarket/v1/params`,
15746
- {},
15747
- fetchOptions,
15748
- fetchFn
15749
- );
15750
- const raw = data.params ?? {};
15751
- return {
15752
- noBaseFee: raw.noBaseFee ?? raw.no_base_fee ?? false,
15753
- baseFee: raw.baseFee ?? raw.base_fee ?? "0",
15754
- minGasPrice: raw.minGasPrice ?? raw.min_gas_price ?? "0"
15755
- };
15756
- }
15757
- var ONE_E18 = 1000000000000000000n;
15758
- var DEFAULT_FEE_MARGIN_PERCENT = 20;
15759
- function marginFactorScaled(marginPercent) {
15760
- if (!Number.isFinite(marginPercent) || !Number.isInteger(marginPercent)) {
15761
- throw new Error(`marginPercent must be a non-negative integer, got ${marginPercent}`);
15762
- }
15763
- if (marginPercent < 0) {
15764
- throw new Error(`marginPercent must be >= 0, got ${marginPercent}`);
15765
- }
15766
- return BigInt(100 + marginPercent);
15767
- }
15768
- function computeRequiredFee(params, gas, options) {
15769
- const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
15770
- const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
15771
- const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
15772
- const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
15773
- if (effectiveI <= 0n) return "0";
15774
- const gasI = BigInt(gas);
15775
- if (gasI <= 0n) return "0";
15776
- const numerator = effectiveI * gasI * margin;
15777
- const denominator = ONE_E18 * 100n;
15778
- return ((numerator + denominator - 1n) / denominator).toString();
15779
- }
15780
- var DEFAULT_FEE_MARKET_TTL_MS = 3e3;
15781
- function createFeeMarketCache(ttlMs = DEFAULT_FEE_MARKET_TTL_MS) {
15782
- return { ttlMs, entries: /* @__PURE__ */ new Map() };
15783
- }
15784
- async function getCachedFeeMarketParams(cache, network, fetchFn, fetchOptions) {
15785
- const key = network.chainId;
15786
- const now = Date.now();
15787
- if (cache) {
15788
- const existing = cache.entries.get(key);
15789
- if (existing && now - existing.fetchedAt < cache.ttlMs) {
15790
- return existing.params;
15791
- }
15792
- }
15793
- let params;
15794
- try {
15795
- params = await fetchFeeMarketParams(network, fetchFn, fetchOptions);
15796
- } catch (error) {
15797
- if (!isGatewayUnsupportedError(error)) throw error;
15798
- params = null;
15799
- }
15800
- if (cache) {
15801
- cache.entries.set(key, { params, fetchedAt: now });
15802
- }
15803
- return params;
15804
- }
15805
- function isGatewayUnsupportedError(error) {
15806
- return error instanceof ApiError && (error.status === 404 || error.status === 501);
15807
- }
15808
- function computeEvmFeesPerGas(params, options) {
15809
- const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
15810
- const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
15811
- const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
15812
- const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
15813
- if (effectiveI <= 0n) {
15814
- return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n };
15815
- }
15816
- const numerator = effectiveI * margin;
15817
- const denominator = ONE_E18 * 100n;
15818
- const gasPriceWei = (numerator + denominator - 1n) / denominator;
15819
- return { maxFeePerGas: gasPriceWei, maxPriorityFeePerGas: gasPriceWei };
15820
- }
15821
- async function resolveEvmFeesPerGas(network, options) {
15822
- const params = await getCachedFeeMarketParams(
15823
- options?.cache,
15824
- network,
15825
- options?.fetchFn,
15826
- options?.fetchOptions
15827
- );
15828
- if (!params) return null;
15829
- let fees;
15830
- try {
15831
- fees = computeEvmFeesPerGas(params, { marginPercent: options?.marginPercent });
15832
- } catch {
15833
- return null;
15834
- }
15835
- if (fees.maxFeePerGas === 0n && fees.maxPriorityFeePerGas === 0n) return null;
15836
- return fees;
15837
- }
15838
-
15839
- // src/eip712/signers.ts
15840
- var import_accounts = require("viem/accounts");
15841
- var AULT_SIGNER_MARKER = /* @__PURE__ */ Symbol.for("ault-sdk:signer");
15842
- function isAultSigner(obj) {
15843
- return typeof obj === "object" && obj !== null && AULT_SIGNER_MARKER in obj && obj[AULT_SIGNER_MARKER] === true;
15844
- }
15845
- function normalizeSigner(input) {
15846
- if (!input) return null;
15847
- if (typeof input === "function") {
15848
- return { signTypedData: input };
15849
- }
15850
- if (typeof input === "object" && typeof input.signTypedData === "function") {
15851
- return input;
15852
- }
15853
- throw new Error("Invalid signer: expected a signer object or signTypedData function.");
15854
- }
15855
- function normalizeSignature(result) {
15856
- if (typeof result === "string") {
15857
- return result;
15858
- }
15859
- if (result && typeof result.signature === "string") {
15860
- return result.signature;
15861
- }
15862
- throw new Error("Invalid signature response: expected hex string or { signature }.");
15863
- }
15864
- async function getSignerAddress(signer) {
15865
- if (typeof signer.address === "string") {
15866
- return signer.address;
15867
- }
15868
- if (typeof signer.getAddress === "function") {
15869
- const address = await signer.getAddress();
15870
- return typeof address === "string" ? address : null;
15871
- }
15872
- return null;
15873
- }
15874
- async function resolveSignerAddress(signer, signerAddress) {
15875
- const raw = signerAddress ?? (signer ? await getSignerAddress(signer) : null);
15876
- if (!raw) {
15877
- throw new Error("signerAddress is required when the signer has no address.");
15878
- }
15879
- if (isValidAultAddress(raw)) {
15880
- return raw;
15881
- }
15882
- if (isValidEvmAddress(raw)) {
15883
- return evmToAult(raw);
15884
- }
15885
- throw new Error(`Invalid signerAddress: ${raw}`);
15886
- }
15887
- function stripEip712Domain(types) {
15888
- const { EIP712Domain: _removed, ...rest } = types;
15889
- return rest;
15890
- }
15891
- function createEip1193Signer(options) {
15892
- const method = options.method ?? "eth_signTypedData_v4";
15893
- return {
15894
- [AULT_SIGNER_MARKER]: true,
15895
- address: options.address,
15896
- signTypedData: async (typedData) => {
15897
- const payload = method === "eth_signTypedData_v4" ? JSON.stringify(typedData) : typedData;
15898
- const signature = await options.provider.request({
15899
- method,
15900
- params: [options.address, payload]
15901
- });
15902
- if (typeof signature !== "string") {
15903
- throw new Error("Provider did not return a signature string.");
15904
- }
15905
- return { signature };
15906
- }
15907
- };
15908
- }
15909
- function createViemSigner(wallet, options) {
15910
- const preferRpc = options?.preferRpc ?? true;
15911
- const getAddress3 = async () => {
15912
- if (wallet.address) return wallet.address;
15913
- if (wallet.getAddresses) {
15914
- const addresses = await wallet.getAddresses();
15915
- if (addresses?.length) return addresses[0];
15916
- }
15917
- return void 0;
15918
- };
15919
- return {
15920
- [AULT_SIGNER_MARKER]: true,
15921
- getAddress: async () => {
15922
- const addr = await getAddress3();
15923
- if (!addr) throw new Error("Viem wallet has no address");
15924
- return addr;
15925
- },
15926
- signTypedData: async (typedData) => {
15927
- if (preferRpc && wallet.request) {
15928
- const address = await getAddress3();
15929
- if (!address) {
15930
- throw new Error("Viem wallet has no address; pass signerAddress explicitly.");
15931
- }
15932
- const signature2 = await wallet.request({
15933
- method: "eth_signTypedData_v4",
15934
- params: [address, JSON.stringify(typedData)]
15935
- });
15936
- if (typeof signature2 !== "string") {
15937
- throw new Error("RPC signer did not return a signature string.");
15938
- }
15939
- return { signature: signature2 };
15940
- }
15941
- if (!wallet.signTypedData) {
15942
- throw new Error("Viem signer does not support signTypedData.");
15943
- }
15944
- const signature = await wallet.signTypedData({
15945
- domain: typedData.domain,
15946
- types: typedData.types,
15947
- primaryType: typedData.primaryType,
15948
- message: typedData.message
15949
- });
15950
- return { signature };
15951
- }
15952
- };
15953
- }
15954
- function createEthersSigner(signer) {
15955
- const sign = signer.signTypedData ?? signer._signTypedData;
15956
- if (!sign) {
15957
- throw new Error("Ethers signer must implement signTypedData or _signTypedData.");
15958
- }
15959
- return {
15960
- [AULT_SIGNER_MARKER]: true,
15961
- getAddress: () => signer.getAddress(),
15962
- signTypedData: async (typedData) => {
15963
- const types = stripEip712Domain(typedData.types);
15964
- const signature = await sign(typedData.domain, types, typedData.message);
15965
- return { signature };
15966
- }
15967
- };
15968
- }
15969
- function createPrivySigner(options) {
15970
- return {
15971
- [AULT_SIGNER_MARKER]: true,
15972
- address: options.address,
15973
- signTypedData: (typedData) => options.signTypedData(typedData, options.address ? { address: options.address } : void 0)
15974
- };
15975
- }
15976
- function createPrivateKeySigner(privateKey) {
15977
- const normalized = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
15978
- const account = (0, import_accounts.privateKeyToAccount)(normalized);
15979
- return createViemSigner(account);
15980
- }
15981
-
15982
- // src/utils/tx-hash.ts
15983
- function normalizeTxHash(raw) {
15984
- if (!raw) return raw;
15985
- const stripped = raw.startsWith("0x") || raw.startsWith("0X") ? raw.slice(2) : raw;
15986
- return stripped.toLowerCase();
15987
- }
15988
-
15989
15766
  // src/proto/tx-encode.ts
15990
15767
  var WIRE_VARINT = 0;
15991
15768
  var WIRE_LENGTH_DELIMITED = 2;
@@ -24874,9 +24651,380 @@ var MSG_ENCODERS = {
24874
24651
  ).finish()
24875
24652
  };
24876
24653
 
24877
- // src/eip712/sign-and-broadcast.ts
24878
- async function queryAccount(network, address, fetchFn, fetchOptions) {
24879
- const data = await fetchJson(
24654
+ // src/eip712/simulate.ts
24655
+ var SIMULATE_PATH = "/cosmos/tx/v1beta1/simulate";
24656
+ var SIMULATION_PLACEHOLDER_PUBKEY = new Uint8Array([
24657
+ 2,
24658
+ 121,
24659
+ 190,
24660
+ 102,
24661
+ 126,
24662
+ 249,
24663
+ 220,
24664
+ 187,
24665
+ 172,
24666
+ 85,
24667
+ 160,
24668
+ 98,
24669
+ 149,
24670
+ 206,
24671
+ 135,
24672
+ 11,
24673
+ 7,
24674
+ 2,
24675
+ 155,
24676
+ 252,
24677
+ 219,
24678
+ 45,
24679
+ 206,
24680
+ 40,
24681
+ 217,
24682
+ 89,
24683
+ 242,
24684
+ 129,
24685
+ 91,
24686
+ 22,
24687
+ 248,
24688
+ 23,
24689
+ 152
24690
+ ]);
24691
+ var SIMULATION_PLACEHOLDER_SIGNATURE = new Uint8Array(64);
24692
+ var CHAIN_VERDICT_STATUSES = /* @__PURE__ */ new Set([400, 500]);
24693
+ var CHAIN_VERDICT_CODES = /* @__PURE__ */ new Set([2, 3]);
24694
+ async function simulateTx({
24695
+ network,
24696
+ msgs,
24697
+ memo = "",
24698
+ sequence,
24699
+ pubkeyBase64,
24700
+ placeholderGasLimit,
24701
+ placeholderFee,
24702
+ fetchFn,
24703
+ fetchOptions
24704
+ }) {
24705
+ const encodedMessages = msgs.map((msg2) => {
24706
+ const encoder = MSG_ENCODERS[msg2.typeUrl];
24707
+ if (!encoder) {
24708
+ throw new Error(`No encoder found for message type: ${msg2.typeUrl}`);
24709
+ }
24710
+ return { typeUrl: msg2.typeUrl, value: encoder(msg2.value) };
24711
+ });
24712
+ const pubkeyBytes = pubkeyBase64 ? base64ToBytes(pubkeyBase64) : SIMULATION_PLACEHOLDER_PUBKEY;
24713
+ const txRawBytes = encodeTxRaw({
24714
+ bodyBytes: encodeTxBody({ messages: encodedMessages, memo }),
24715
+ authInfoBytes: encodeAuthInfo({
24716
+ signerInfos: [
24717
+ {
24718
+ publicKey: {
24719
+ typeUrl: "/cosmos.evm.crypto.v1.ethsecp256k1.PubKey",
24720
+ value: encodeEthSecp256k1PubKey(pubkeyBytes)
24721
+ },
24722
+ mode: SIGN_MODE_LEGACY_AMINO_JSON,
24723
+ sequence
24724
+ }
24725
+ ],
24726
+ fee: { amount: [placeholderFee], gasLimit: BigInt(placeholderGasLimit) }
24727
+ }),
24728
+ signatures: [SIMULATION_PLACEHOLDER_SIGNATURE]
24729
+ });
24730
+ const url = `${network.restUrl}${SIMULATE_PATH}`;
24731
+ let response;
24732
+ try {
24733
+ response = await postJson(
24734
+ url,
24735
+ { tx_bytes: bytesToBase64(txRawBytes) },
24736
+ {
24737
+ ...fetchOptions,
24738
+ // 500 carries the verdict; never retry it. The rest of the caller's
24739
+ // policy stays.
24740
+ retryableStatuses: (fetchOptions?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES).filter(
24741
+ (status) => status !== 500
24742
+ )
24743
+ },
24744
+ fetchFn
24745
+ );
24746
+ } catch (error) {
24747
+ const verdict = chainVerdict(error);
24748
+ if (verdict) {
24749
+ throw new TxSimulationError(verdict);
24750
+ }
24751
+ const detail = error instanceof Error ? error.message : String(error);
24752
+ console.warn(`[ault-sdk] tx simulation unavailable (${url}); using static gas: ${detail}`);
24753
+ return null;
24754
+ }
24755
+ const gasUsed = response.gas_info?.gas_used;
24756
+ if (typeof gasUsed !== "string" || !/^\d+$/.test(gasUsed) || gasUsed === "0") {
24757
+ console.warn(`[ault-sdk] tx simulation returned no usable gas_used (${url}); using static gas`);
24758
+ return null;
24759
+ }
24760
+ return { gasUsed: BigInt(gasUsed) };
24761
+ }
24762
+ function chainVerdict(error) {
24763
+ if (!(error instanceof ApiError) || typeof error.status !== "number") return null;
24764
+ if (!CHAIN_VERDICT_STATUSES.has(error.status) || !error.response) return null;
24765
+ let body;
24766
+ try {
24767
+ body = JSON.parse(error.response);
24768
+ } catch {
24769
+ return null;
24770
+ }
24771
+ if (typeof body !== "object" || body === null) return null;
24772
+ const { code, message } = body;
24773
+ if (typeof code !== "number" || !CHAIN_VERDICT_CODES.has(code)) return null;
24774
+ if (typeof message !== "string" || message.length === 0) return null;
24775
+ return { rawLog: message, chainCode: code };
24776
+ }
24777
+
24778
+ // src/rest/feemarket.ts
24779
+ async function fetchFeeMarketParams(network, fetchFn, fetchOptions) {
24780
+ const data = await fetchJson(
24781
+ `${network.restUrl}/cosmos/evm/feemarket/v1/params`,
24782
+ {},
24783
+ fetchOptions,
24784
+ fetchFn
24785
+ );
24786
+ const raw = data.params ?? {};
24787
+ return {
24788
+ noBaseFee: raw.noBaseFee ?? raw.no_base_fee ?? false,
24789
+ baseFee: raw.baseFee ?? raw.base_fee ?? "0",
24790
+ minGasPrice: raw.minGasPrice ?? raw.min_gas_price ?? "0"
24791
+ };
24792
+ }
24793
+ var ONE_E18 = 1000000000000000000n;
24794
+ var DEFAULT_FEE_MARGIN_PERCENT = 20;
24795
+ function marginFactorScaled(marginPercent) {
24796
+ if (!Number.isFinite(marginPercent) || !Number.isInteger(marginPercent)) {
24797
+ throw new Error(`marginPercent must be a non-negative integer, got ${marginPercent}`);
24798
+ }
24799
+ if (marginPercent < 0) {
24800
+ throw new Error(`marginPercent must be >= 0, got ${marginPercent}`);
24801
+ }
24802
+ return BigInt(100 + marginPercent);
24803
+ }
24804
+ function computeRequiredFee(params, gas, options) {
24805
+ const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
24806
+ const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
24807
+ const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
24808
+ const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
24809
+ if (effectiveI <= 0n) return "0";
24810
+ const gasI = BigInt(gas);
24811
+ if (gasI <= 0n) return "0";
24812
+ const numerator = effectiveI * gasI * margin;
24813
+ const denominator = ONE_E18 * 100n;
24814
+ return ((numerator + denominator - 1n) / denominator).toString();
24815
+ }
24816
+ var DEFAULT_FEE_MARKET_TTL_MS = 3e3;
24817
+ function createFeeMarketCache(ttlMs = DEFAULT_FEE_MARKET_TTL_MS) {
24818
+ return { ttlMs, entries: /* @__PURE__ */ new Map() };
24819
+ }
24820
+ async function getCachedFeeMarketParams(cache, network, fetchFn, fetchOptions) {
24821
+ const key = network.chainId;
24822
+ const now = Date.now();
24823
+ if (cache) {
24824
+ const existing = cache.entries.get(key);
24825
+ if (existing && now - existing.fetchedAt < cache.ttlMs) {
24826
+ return existing.params;
24827
+ }
24828
+ }
24829
+ let params;
24830
+ try {
24831
+ params = await fetchFeeMarketParams(network, fetchFn, fetchOptions);
24832
+ } catch (error) {
24833
+ if (!isGatewayUnsupportedError(error)) throw error;
24834
+ params = null;
24835
+ }
24836
+ if (cache) {
24837
+ cache.entries.set(key, { params, fetchedAt: now });
24838
+ }
24839
+ return params;
24840
+ }
24841
+ function isGatewayUnsupportedError(error) {
24842
+ return error instanceof ApiError && (error.status === 404 || error.status === 501);
24843
+ }
24844
+ function computeEvmFeesPerGas(params, options) {
24845
+ const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
24846
+ const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
24847
+ const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
24848
+ const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
24849
+ if (effectiveI <= 0n) {
24850
+ return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n };
24851
+ }
24852
+ const numerator = effectiveI * margin;
24853
+ const denominator = ONE_E18 * 100n;
24854
+ const gasPriceWei = (numerator + denominator - 1n) / denominator;
24855
+ return { maxFeePerGas: gasPriceWei, maxPriorityFeePerGas: gasPriceWei };
24856
+ }
24857
+ async function resolveEvmFeesPerGas(network, options) {
24858
+ const params = await getCachedFeeMarketParams(
24859
+ options?.cache,
24860
+ network,
24861
+ options?.fetchFn,
24862
+ options?.fetchOptions
24863
+ );
24864
+ if (!params) return null;
24865
+ let fees;
24866
+ try {
24867
+ fees = computeEvmFeesPerGas(params, { marginPercent: options?.marginPercent });
24868
+ } catch {
24869
+ return null;
24870
+ }
24871
+ if (fees.maxFeePerGas === 0n && fees.maxPriorityFeePerGas === 0n) return null;
24872
+ return fees;
24873
+ }
24874
+
24875
+ // src/eip712/signers.ts
24876
+ var import_accounts = require("viem/accounts");
24877
+ var AULT_SIGNER_MARKER = /* @__PURE__ */ Symbol.for("ault-sdk:signer");
24878
+ function isAultSigner(obj) {
24879
+ return typeof obj === "object" && obj !== null && AULT_SIGNER_MARKER in obj && obj[AULT_SIGNER_MARKER] === true;
24880
+ }
24881
+ function normalizeSigner(input) {
24882
+ if (!input) return null;
24883
+ if (typeof input === "function") {
24884
+ return { signTypedData: input };
24885
+ }
24886
+ if (typeof input === "object" && typeof input.signTypedData === "function") {
24887
+ return input;
24888
+ }
24889
+ throw new Error("Invalid signer: expected a signer object or signTypedData function.");
24890
+ }
24891
+ function normalizeSignature(result) {
24892
+ if (typeof result === "string") {
24893
+ return result;
24894
+ }
24895
+ if (result && typeof result.signature === "string") {
24896
+ return result.signature;
24897
+ }
24898
+ throw new Error("Invalid signature response: expected hex string or { signature }.");
24899
+ }
24900
+ async function getSignerAddress(signer) {
24901
+ if (typeof signer.address === "string") {
24902
+ return signer.address;
24903
+ }
24904
+ if (typeof signer.getAddress === "function") {
24905
+ const address = await signer.getAddress();
24906
+ return typeof address === "string" ? address : null;
24907
+ }
24908
+ return null;
24909
+ }
24910
+ async function resolveSignerAddress(signer, signerAddress) {
24911
+ const raw = signerAddress ?? (signer ? await getSignerAddress(signer) : null);
24912
+ if (!raw) {
24913
+ throw new Error("signerAddress is required when the signer has no address.");
24914
+ }
24915
+ if (isValidAultAddress(raw)) {
24916
+ return raw;
24917
+ }
24918
+ if (isValidEvmAddress(raw)) {
24919
+ return evmToAult(raw);
24920
+ }
24921
+ throw new Error(`Invalid signerAddress: ${raw}`);
24922
+ }
24923
+ function stripEip712Domain(types) {
24924
+ const { EIP712Domain: _removed, ...rest } = types;
24925
+ return rest;
24926
+ }
24927
+ function createEip1193Signer(options) {
24928
+ const method = options.method ?? "eth_signTypedData_v4";
24929
+ return {
24930
+ [AULT_SIGNER_MARKER]: true,
24931
+ address: options.address,
24932
+ signTypedData: async (typedData) => {
24933
+ const payload = method === "eth_signTypedData_v4" ? JSON.stringify(typedData) : typedData;
24934
+ const signature = await options.provider.request({
24935
+ method,
24936
+ params: [options.address, payload]
24937
+ });
24938
+ if (typeof signature !== "string") {
24939
+ throw new Error("Provider did not return a signature string.");
24940
+ }
24941
+ return { signature };
24942
+ }
24943
+ };
24944
+ }
24945
+ function createViemSigner(wallet, options) {
24946
+ const preferRpc = options?.preferRpc ?? true;
24947
+ const getAddress3 = async () => {
24948
+ if (wallet.address) return wallet.address;
24949
+ if (wallet.getAddresses) {
24950
+ const addresses = await wallet.getAddresses();
24951
+ if (addresses?.length) return addresses[0];
24952
+ }
24953
+ return void 0;
24954
+ };
24955
+ return {
24956
+ [AULT_SIGNER_MARKER]: true,
24957
+ getAddress: async () => {
24958
+ const addr = await getAddress3();
24959
+ if (!addr) throw new Error("Viem wallet has no address");
24960
+ return addr;
24961
+ },
24962
+ signTypedData: async (typedData) => {
24963
+ if (preferRpc && wallet.request) {
24964
+ const address = await getAddress3();
24965
+ if (!address) {
24966
+ throw new Error("Viem wallet has no address; pass signerAddress explicitly.");
24967
+ }
24968
+ const signature2 = await wallet.request({
24969
+ method: "eth_signTypedData_v4",
24970
+ params: [address, JSON.stringify(typedData)]
24971
+ });
24972
+ if (typeof signature2 !== "string") {
24973
+ throw new Error("RPC signer did not return a signature string.");
24974
+ }
24975
+ return { signature: signature2 };
24976
+ }
24977
+ if (!wallet.signTypedData) {
24978
+ throw new Error("Viem signer does not support signTypedData.");
24979
+ }
24980
+ const signature = await wallet.signTypedData({
24981
+ domain: typedData.domain,
24982
+ types: typedData.types,
24983
+ primaryType: typedData.primaryType,
24984
+ message: typedData.message
24985
+ });
24986
+ return { signature };
24987
+ }
24988
+ };
24989
+ }
24990
+ function createEthersSigner(signer) {
24991
+ const sign = signer.signTypedData ?? signer._signTypedData;
24992
+ if (!sign) {
24993
+ throw new Error("Ethers signer must implement signTypedData or _signTypedData.");
24994
+ }
24995
+ return {
24996
+ [AULT_SIGNER_MARKER]: true,
24997
+ getAddress: () => signer.getAddress(),
24998
+ signTypedData: async (typedData) => {
24999
+ const types = stripEip712Domain(typedData.types);
25000
+ const signature = await sign(typedData.domain, types, typedData.message);
25001
+ return { signature };
25002
+ }
25003
+ };
25004
+ }
25005
+ function createPrivySigner(options) {
25006
+ return {
25007
+ [AULT_SIGNER_MARKER]: true,
25008
+ address: options.address,
25009
+ signTypedData: (typedData) => options.signTypedData(typedData, options.address ? { address: options.address } : void 0)
25010
+ };
25011
+ }
25012
+ function createPrivateKeySigner(privateKey) {
25013
+ const normalized = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
25014
+ const account = (0, import_accounts.privateKeyToAccount)(normalized);
25015
+ return createViemSigner(account);
25016
+ }
25017
+
25018
+ // src/utils/tx-hash.ts
25019
+ function normalizeTxHash(raw) {
25020
+ if (!raw) return raw;
25021
+ const stripped = raw.startsWith("0x") || raw.startsWith("0X") ? raw.slice(2) : raw;
25022
+ return stripped.toLowerCase();
25023
+ }
25024
+
25025
+ // src/eip712/sign-and-broadcast.ts
25026
+ async function queryAccount(network, address, fetchFn, fetchOptions) {
25027
+ const data = await fetchJson(
24880
25028
  `${network.restUrl}/cosmos/auth/v1beta1/accounts/${address}`,
24881
25029
  {},
24882
25030
  fetchOptions,
@@ -24931,6 +25079,9 @@ function createAccountCache() {
24931
25079
  function getNextSequence(sequence) {
24932
25080
  return String(BigInt(sequence) + 1n);
24933
25081
  }
25082
+ function isSequenceMismatch(rawLog) {
25083
+ return rawLog.includes("account sequence mismatch") || rawLog.includes("incorrect account sequence");
25084
+ }
24934
25085
  function clearCachedSequence(cache) {
24935
25086
  if (cache) {
24936
25087
  cache.nextSequence = null;
@@ -25033,6 +25184,8 @@ async function signAndBroadcastEip712({
25033
25184
  feeDenom,
25034
25185
  feeAmount,
25035
25186
  confirmationTimeoutMs,
25187
+ simulateGas = false,
25188
+ simulatedGasMultiplier,
25036
25189
  wait = true,
25037
25190
  fetchFn,
25038
25191
  fetchOptions,
@@ -25059,15 +25212,46 @@ async function signAndBroadcastEip712({
25059
25212
  if (!sequence) {
25060
25213
  throw new Error(`Unable to resolve account sequence for signer ${resolvedSignerAddress}.`);
25061
25214
  }
25062
- const resolvedGas = gasLimit ?? network.eip712GasLimit ?? GAS_CONSTANTS.EIP712_GAS_LIMIT;
25063
- const resolvedFeeAmount = feeAmount ?? network.eip712FeeAmount ?? await resolveDynamicFeeAmount(network, resolvedGas, feeMarketCache, fetchFn, fetchOptions);
25215
+ let resolvedGas = gasLimit ?? network.eip712GasLimit ?? GAS_CONSTANTS.EIP712_GAS_LIMIT;
25216
+ const resolvedFeeDenom = feeDenom ?? network.eip712FeeDenom ?? GAS_CONSTANTS.DENOM;
25217
+ const feeOverride = feeAmount ?? network.eip712FeeAmount;
25218
+ const feeFor = async (gas) => feeOverride ?? await resolveDynamicFeeAmount(network, gas, feeMarketCache, fetchFn, fetchOptions);
25219
+ let resolvedFeeAmount;
25220
+ if (simulateGas) {
25221
+ let simulated;
25222
+ try {
25223
+ simulated = await simulateTx({
25224
+ network,
25225
+ msgs,
25226
+ memo,
25227
+ sequence,
25228
+ pubkeyBase64: cache?.pubkeyBase64 ?? accountInfo?.pubkeyBase64 ?? null,
25229
+ placeholderGasLimit: resolvedGas,
25230
+ placeholderFee: { denom: resolvedFeeDenom, amount: await feeFor(resolvedGas) },
25231
+ fetchFn,
25232
+ fetchOptions
25233
+ });
25234
+ } catch (error) {
25235
+ if (error instanceof TxSimulationError && isSequenceMismatch(error.rawLog)) {
25236
+ clearCachedSequence(cache);
25237
+ }
25238
+ throw error;
25239
+ }
25240
+ if (simulated) {
25241
+ resolvedGas = computeSimulatedGas(
25242
+ simulated.gasUsed,
25243
+ simulatedGasMultiplier ?? GAS_CONSTANTS.SIMULATED_GAS_MULTIPLIER
25244
+ );
25245
+ }
25246
+ }
25247
+ resolvedFeeAmount = await feeFor(resolvedGas);
25064
25248
  const context = {
25065
25249
  chainId: network.chainId,
25066
25250
  accountNumber,
25067
25251
  sequence,
25068
25252
  fee: {
25069
25253
  amount: resolvedFeeAmount,
25070
- denom: feeDenom ?? network.eip712FeeDenom ?? GAS_CONSTANTS.DENOM,
25254
+ denom: resolvedFeeDenom,
25071
25255
  gas: resolvedGas
25072
25256
  },
25073
25257
  memo
@@ -26732,6 +26916,13 @@ function createRewardTxApi({ signerAddress, exec, getGas }) {
26732
26916
  }
26733
26917
 
26734
26918
  // src/high-level/tx/staking.ts
26919
+ function stakingGasOptions(gas, fallbackMinGas, gasLimit) {
26920
+ return {
26921
+ gasLimit: gasLimit ?? computeFeeFreeGas(fallbackMinGas, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26922
+ simulateGas: gasLimit == null,
26923
+ simulatedGasMultiplier: gas.SIMULATED_GAS_MULTIPLIER
26924
+ };
26925
+ }
26735
26926
  function createStakingTxApi({ signerAddress, exec, getGas }) {
26736
26927
  return {
26737
26928
  async delegate({ validatorAddress, amount, gasLimit, feeAmount, memo, confirmationTimeoutMs }) {
@@ -26745,7 +26936,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26745
26936
  })
26746
26937
  ],
26747
26938
  {
26748
- gasLimit: gasLimit ?? computeFeeFreeGas(gas.DELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26939
+ ...stakingGasOptions(gas, gas.DELEGATE, gasLimit),
26749
26940
  feeAmount,
26750
26941
  memo,
26751
26942
  confirmationTimeoutMs
@@ -26770,7 +26961,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26770
26961
  })
26771
26962
  ],
26772
26963
  {
26773
- gasLimit: gasLimit ?? computeFeeFreeGas(gas.UNDELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26964
+ ...stakingGasOptions(gas, gas.UNDELEGATE, gasLimit),
26774
26965
  feeAmount,
26775
26966
  memo,
26776
26967
  confirmationTimeoutMs
@@ -26797,7 +26988,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26797
26988
  })
26798
26989
  ],
26799
26990
  {
26800
- gasLimit: gasLimit ?? computeFeeFreeGas(gas.BEGIN_REDELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26991
+ ...stakingGasOptions(gas, gas.BEGIN_REDELEGATE, gasLimit),
26801
26992
  feeAmount,
26802
26993
  memo,
26803
26994
  confirmationTimeoutMs
@@ -26816,7 +27007,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26816
27007
  }
26817
27008
  const normalized = validatorAddresses.map(assertValidatorAddress);
26818
27009
  const gas = getGas();
26819
- const resolvedGasLimit = gasLimit ?? computeFeeFreeGas(gas.WITHDRAW_DELEGATOR_REWARD, 1, gas.FEE_FREE_GAS_MULTIPLIER);
27010
+ const gasOptions = stakingGasOptions(gas, gas.WITHDRAW_DELEGATOR_REWARD, gasLimit);
26820
27011
  const results = [];
26821
27012
  const partial = [];
26822
27013
  for (let i = 0; i < normalized.length; i++) {
@@ -26829,7 +27020,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26829
27020
  validatorAddress
26830
27021
  })
26831
27022
  ],
26832
- { gasLimit: resolvedGasLimit, feeAmount, memo, confirmationTimeoutMs }
27023
+ { ...gasOptions, feeAmount, memo, confirmationTimeoutMs }
26833
27024
  );
26834
27025
  results.push(result);
26835
27026
  partial.push({ txHash: result.txHash, validatorAddress });
@@ -27018,6 +27209,8 @@ function createTxExecutor(options) {
27018
27209
  feeAmount: txOptions?.feeAmount,
27019
27210
  memo: txOptions?.memo ?? defaultMemo,
27020
27211
  confirmationTimeoutMs: txOptions?.confirmationTimeoutMs ?? defaultConfirmationTimeoutMs,
27212
+ simulateGas: txOptions?.simulateGas ?? false,
27213
+ simulatedGasMultiplier: txOptions?.simulatedGasMultiplier,
27021
27214
  wait: txOptions?.wait ?? true,
27022
27215
  fetchFn: options.fetchFn,
27023
27216
  fetchOptions,
@@ -27040,6 +27233,8 @@ function createTxExecutor(options) {
27040
27233
  var import_zod = require("zod");
27041
27234
  var ManifestGasSchema = import_zod.z.object({
27042
27235
  FEE_FREE_GAS_MULTIPLIER: import_zod.z.number().int().positive(),
27236
+ // Under 100% signs less gas than the simulation already burned.
27237
+ SIMULATED_GAS_MULTIPLIER: import_zod.z.number().int().min(100),
27043
27238
  PER_LICENSE: import_zod.z.number().int().positive(),
27044
27239
  PER_KYC_MEMBER: import_zod.z.number().int().positive(),
27045
27240
  PER_DELEGATE_MINING: import_zod.z.number().int().positive(),
@@ -28747,7 +28942,7 @@ function createDexWs(url, options) {
28747
28942
  }
28748
28943
 
28749
28944
  // src/index.ts
28750
- var SDK_VERSION = "0.7.0";
28945
+ var SDK_VERSION = "0.7.1";
28751
28946
  // Annotate the CommonJS export names for ESM import in node:
28752
28947
  0 && (module.exports = {
28753
28948
  AGENT_DEFAULTS,
@@ -28758,6 +28953,7 @@ var SDK_VERSION = "0.7.0";
28758
28953
  BondStatus,
28759
28954
  COIN_TYPE,
28760
28955
  DEFAULT_CHAIN_ID,
28956
+ DEFAULT_RETRYABLE_STATUSES,
28761
28957
  DexWsClient,
28762
28958
  EIP712_DOMAIN_TYPE,
28763
28959
  EIP712_MSG_TYPES,
@@ -28833,6 +29029,7 @@ var SDK_VERSION = "0.7.0";
28833
29029
  SDK_VERSION,
28834
29030
  SIGN_MODE_DIRECT,
28835
29031
  SIGN_MODE_LEGACY_AMINO_JSON,
29032
+ SIMULATION_PLACEHOLDER_PUBKEY,
28836
29033
  SearchUDFSymbolsQueryParams,
28837
29034
  SearchUDFSymbolsResponse,
28838
29035
  SearchUDFSymbolsResponseItem,
@@ -28842,6 +29039,7 @@ var SDK_VERSION = "0.7.0";
28842
29039
  TxConfirmationUnavailableError,
28843
29040
  TxError,
28844
29041
  TxNotConfirmedError,
29042
+ TxSimulationError,
28845
29043
  ValidatorStatus,
28846
29044
  WebSocketError,
28847
29045
  WithdrawRewardsPartialError,
@@ -28864,6 +29062,7 @@ var SDK_VERSION = "0.7.0";
28864
29062
  computeFeeFreeGas,
28865
29063
  computeFeeFreeGasCompound,
28866
29064
  computeRequiredFee,
29065
+ computeSimulatedGas,
28867
29066
  cosmosDecToDecimalString,
28868
29067
  cosmosDecToProtoInt,
28869
29068
  createAccountCache,
@@ -29027,6 +29226,7 @@ var SDK_VERSION = "0.7.0";
29027
29226
  resolveSignerAddress,
29028
29227
  signAndBroadcastAgentTx,
29029
29228
  signAndBroadcastEip712,
29229
+ simulateTx,
29030
29230
  stripEip712Domain,
29031
29231
  toViemChain,
29032
29232
  validateEip712FieldOrder,