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.js CHANGED
@@ -145,6 +145,14 @@ var TxError = class extends Error {
145
145
  this.confirmed = params.confirmed;
146
146
  }
147
147
  };
148
+ var TxSimulationError = class extends Error {
149
+ constructor(params) {
150
+ super(`Transaction simulation failed: ${params.rawLog}`);
151
+ this.name = "TxSimulationError";
152
+ this.chainCode = params.chainCode;
153
+ this.rawLog = params.rawLog;
154
+ }
155
+ };
148
156
  var TxNotConfirmedError = class extends TxError {
149
157
  constructor(params) {
150
158
  super(
@@ -191,13 +199,14 @@ var WithdrawRewardsPartialError = class extends Error {
191
199
  };
192
200
 
193
201
  // src/core/http.ts
202
+ var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
194
203
  var DEFAULT_OPTIONS = {
195
204
  timeout: 3e4,
196
205
  retries: 3,
197
206
  retryDelay: 1e3,
198
207
  exponentialBackoff: true,
199
208
  retryableMethods: ["GET", "HEAD", "OPTIONS"],
200
- retryableStatuses: [408, 429, 500, 502, 503, 504],
209
+ retryableStatuses: [...DEFAULT_RETRYABLE_STATUSES],
201
210
  retryOnTimeout: false
202
211
  };
203
212
  function ensureFetch(fetchFn) {
@@ -436,6 +445,8 @@ var GAS_CONSTANTS = {
436
445
  DENOM: "aault",
437
446
  /** Chain multiplier applied to min gas to derive max gas (120 = 1.2×). */
438
447
  FEE_FREE_GAS_MULTIPLIER: 120,
448
+ /** Headroom over simulated `gas_used` (130 = 1.3×). */
449
+ SIMULATED_GAS_MULTIPLIER: 130,
439
450
  // License module
440
451
  PER_LICENSE: 2e5,
441
452
  PER_KYC_MEMBER: 2e5,
@@ -466,11 +477,19 @@ var GAS_CONSTANTS = {
466
477
  // Accountx module
467
478
  OPEN_ACCOUNT: 96e3,
468
479
  // Staking module (cosmos-sdk standard, NOT fee-free — user pays gas).
480
+ // Staking gas depends on the delegator's state, so the builders simulate;
481
+ // these are the fallback (×FEE_FREE_GAS_MULTIPLIER) when simulate is down.
469
482
  DELEGATE: 22e4,
470
- UNDELEGATE: 22e4,
471
- BEGIN_REDELEGATE: 28e4,
483
+ UNDELEGATE: 26e4,
484
+ BEGIN_REDELEGATE: 4e5,
472
485
  WITHDRAW_DELEGATOR_REWARD: 22e4
473
486
  };
487
+ function computeSimulatedGas(gasUsed, multiplier = GAS_CONSTANTS.SIMULATED_GAS_MULTIPLIER) {
488
+ if (!Number.isInteger(multiplier) || multiplier < 100) {
489
+ throw new Error(`simulated gas multiplier must be an integer >= 100, got ${multiplier}`);
490
+ }
491
+ return (gasUsed * BigInt(multiplier) / 100n).toString();
492
+ }
474
493
  function computeFeeFreeGas(minGasPerOp, count, multiplier = GAS_CONSTANTS.FEE_FREE_GAS_MULTIPLIER) {
475
494
  return (BigInt(minGasPerOp) * BigInt(count) * BigInt(multiplier) / 100n).toString();
476
495
  }
@@ -15429,253 +15448,6 @@ function buildEip712TypedData(context, msgs, evmChainId) {
15429
15448
  };
15430
15449
  }
15431
15450
 
15432
- // src/rest/feemarket.ts
15433
- async function fetchFeeMarketParams(network, fetchFn, fetchOptions) {
15434
- const data = await fetchJson(
15435
- `${network.restUrl}/cosmos/evm/feemarket/v1/params`,
15436
- {},
15437
- fetchOptions,
15438
- fetchFn
15439
- );
15440
- const raw = data.params ?? {};
15441
- return {
15442
- noBaseFee: raw.noBaseFee ?? raw.no_base_fee ?? false,
15443
- baseFee: raw.baseFee ?? raw.base_fee ?? "0",
15444
- minGasPrice: raw.minGasPrice ?? raw.min_gas_price ?? "0"
15445
- };
15446
- }
15447
- var ONE_E18 = 1000000000000000000n;
15448
- var DEFAULT_FEE_MARGIN_PERCENT = 20;
15449
- function marginFactorScaled(marginPercent) {
15450
- if (!Number.isFinite(marginPercent) || !Number.isInteger(marginPercent)) {
15451
- throw new Error(`marginPercent must be a non-negative integer, got ${marginPercent}`);
15452
- }
15453
- if (marginPercent < 0) {
15454
- throw new Error(`marginPercent must be >= 0, got ${marginPercent}`);
15455
- }
15456
- return BigInt(100 + marginPercent);
15457
- }
15458
- function computeRequiredFee(params, gas, options) {
15459
- const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
15460
- const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
15461
- const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
15462
- const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
15463
- if (effectiveI <= 0n) return "0";
15464
- const gasI = BigInt(gas);
15465
- if (gasI <= 0n) return "0";
15466
- const numerator = effectiveI * gasI * margin;
15467
- const denominator = ONE_E18 * 100n;
15468
- return ((numerator + denominator - 1n) / denominator).toString();
15469
- }
15470
- var DEFAULT_FEE_MARKET_TTL_MS = 3e3;
15471
- function createFeeMarketCache(ttlMs = DEFAULT_FEE_MARKET_TTL_MS) {
15472
- return { ttlMs, entries: /* @__PURE__ */ new Map() };
15473
- }
15474
- async function getCachedFeeMarketParams(cache, network, fetchFn, fetchOptions) {
15475
- const key = network.chainId;
15476
- const now = Date.now();
15477
- if (cache) {
15478
- const existing = cache.entries.get(key);
15479
- if (existing && now - existing.fetchedAt < cache.ttlMs) {
15480
- return existing.params;
15481
- }
15482
- }
15483
- let params;
15484
- try {
15485
- params = await fetchFeeMarketParams(network, fetchFn, fetchOptions);
15486
- } catch (error) {
15487
- if (!isGatewayUnsupportedError(error)) throw error;
15488
- params = null;
15489
- }
15490
- if (cache) {
15491
- cache.entries.set(key, { params, fetchedAt: now });
15492
- }
15493
- return params;
15494
- }
15495
- function isGatewayUnsupportedError(error) {
15496
- return error instanceof ApiError && (error.status === 404 || error.status === 501);
15497
- }
15498
- function computeEvmFeesPerGas(params, options) {
15499
- const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
15500
- const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
15501
- const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
15502
- const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
15503
- if (effectiveI <= 0n) {
15504
- return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n };
15505
- }
15506
- const numerator = effectiveI * margin;
15507
- const denominator = ONE_E18 * 100n;
15508
- const gasPriceWei = (numerator + denominator - 1n) / denominator;
15509
- return { maxFeePerGas: gasPriceWei, maxPriorityFeePerGas: gasPriceWei };
15510
- }
15511
- async function resolveEvmFeesPerGas(network, options) {
15512
- const params = await getCachedFeeMarketParams(
15513
- options?.cache,
15514
- network,
15515
- options?.fetchFn,
15516
- options?.fetchOptions
15517
- );
15518
- if (!params) return null;
15519
- let fees;
15520
- try {
15521
- fees = computeEvmFeesPerGas(params, { marginPercent: options?.marginPercent });
15522
- } catch {
15523
- return null;
15524
- }
15525
- if (fees.maxFeePerGas === 0n && fees.maxPriorityFeePerGas === 0n) return null;
15526
- return fees;
15527
- }
15528
-
15529
- // src/eip712/signers.ts
15530
- import { privateKeyToAccount } from "viem/accounts";
15531
- var AULT_SIGNER_MARKER = /* @__PURE__ */ Symbol.for("ault-sdk:signer");
15532
- function isAultSigner(obj) {
15533
- return typeof obj === "object" && obj !== null && AULT_SIGNER_MARKER in obj && obj[AULT_SIGNER_MARKER] === true;
15534
- }
15535
- function normalizeSigner(input) {
15536
- if (!input) return null;
15537
- if (typeof input === "function") {
15538
- return { signTypedData: input };
15539
- }
15540
- if (typeof input === "object" && typeof input.signTypedData === "function") {
15541
- return input;
15542
- }
15543
- throw new Error("Invalid signer: expected a signer object or signTypedData function.");
15544
- }
15545
- function normalizeSignature(result) {
15546
- if (typeof result === "string") {
15547
- return result;
15548
- }
15549
- if (result && typeof result.signature === "string") {
15550
- return result.signature;
15551
- }
15552
- throw new Error("Invalid signature response: expected hex string or { signature }.");
15553
- }
15554
- async function getSignerAddress(signer) {
15555
- if (typeof signer.address === "string") {
15556
- return signer.address;
15557
- }
15558
- if (typeof signer.getAddress === "function") {
15559
- const address = await signer.getAddress();
15560
- return typeof address === "string" ? address : null;
15561
- }
15562
- return null;
15563
- }
15564
- async function resolveSignerAddress(signer, signerAddress) {
15565
- const raw = signerAddress ?? (signer ? await getSignerAddress(signer) : null);
15566
- if (!raw) {
15567
- throw new Error("signerAddress is required when the signer has no address.");
15568
- }
15569
- if (isValidAultAddress(raw)) {
15570
- return raw;
15571
- }
15572
- if (isValidEvmAddress(raw)) {
15573
- return evmToAult(raw);
15574
- }
15575
- throw new Error(`Invalid signerAddress: ${raw}`);
15576
- }
15577
- function stripEip712Domain(types) {
15578
- const { EIP712Domain: _removed, ...rest } = types;
15579
- return rest;
15580
- }
15581
- function createEip1193Signer(options) {
15582
- const method = options.method ?? "eth_signTypedData_v4";
15583
- return {
15584
- [AULT_SIGNER_MARKER]: true,
15585
- address: options.address,
15586
- signTypedData: async (typedData) => {
15587
- const payload = method === "eth_signTypedData_v4" ? JSON.stringify(typedData) : typedData;
15588
- const signature = await options.provider.request({
15589
- method,
15590
- params: [options.address, payload]
15591
- });
15592
- if (typeof signature !== "string") {
15593
- throw new Error("Provider did not return a signature string.");
15594
- }
15595
- return { signature };
15596
- }
15597
- };
15598
- }
15599
- function createViemSigner(wallet, options) {
15600
- const preferRpc = options?.preferRpc ?? true;
15601
- const getAddress3 = async () => {
15602
- if (wallet.address) return wallet.address;
15603
- if (wallet.getAddresses) {
15604
- const addresses = await wallet.getAddresses();
15605
- if (addresses?.length) return addresses[0];
15606
- }
15607
- return void 0;
15608
- };
15609
- return {
15610
- [AULT_SIGNER_MARKER]: true,
15611
- getAddress: async () => {
15612
- const addr = await getAddress3();
15613
- if (!addr) throw new Error("Viem wallet has no address");
15614
- return addr;
15615
- },
15616
- signTypedData: async (typedData) => {
15617
- if (preferRpc && wallet.request) {
15618
- const address = await getAddress3();
15619
- if (!address) {
15620
- throw new Error("Viem wallet has no address; pass signerAddress explicitly.");
15621
- }
15622
- const signature2 = await wallet.request({
15623
- method: "eth_signTypedData_v4",
15624
- params: [address, JSON.stringify(typedData)]
15625
- });
15626
- if (typeof signature2 !== "string") {
15627
- throw new Error("RPC signer did not return a signature string.");
15628
- }
15629
- return { signature: signature2 };
15630
- }
15631
- if (!wallet.signTypedData) {
15632
- throw new Error("Viem signer does not support signTypedData.");
15633
- }
15634
- const signature = await wallet.signTypedData({
15635
- domain: typedData.domain,
15636
- types: typedData.types,
15637
- primaryType: typedData.primaryType,
15638
- message: typedData.message
15639
- });
15640
- return { signature };
15641
- }
15642
- };
15643
- }
15644
- function createEthersSigner(signer) {
15645
- const sign = signer.signTypedData ?? signer._signTypedData;
15646
- if (!sign) {
15647
- throw new Error("Ethers signer must implement signTypedData or _signTypedData.");
15648
- }
15649
- return {
15650
- [AULT_SIGNER_MARKER]: true,
15651
- getAddress: () => signer.getAddress(),
15652
- signTypedData: async (typedData) => {
15653
- const types = stripEip712Domain(typedData.types);
15654
- const signature = await sign(typedData.domain, types, typedData.message);
15655
- return { signature };
15656
- }
15657
- };
15658
- }
15659
- function createPrivySigner(options) {
15660
- return {
15661
- [AULT_SIGNER_MARKER]: true,
15662
- address: options.address,
15663
- signTypedData: (typedData) => options.signTypedData(typedData, options.address ? { address: options.address } : void 0)
15664
- };
15665
- }
15666
- function createPrivateKeySigner(privateKey) {
15667
- const normalized = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
15668
- const account = privateKeyToAccount(normalized);
15669
- return createViemSigner(account);
15670
- }
15671
-
15672
- // src/utils/tx-hash.ts
15673
- function normalizeTxHash(raw) {
15674
- if (!raw) return raw;
15675
- const stripped = raw.startsWith("0x") || raw.startsWith("0X") ? raw.slice(2) : raw;
15676
- return stripped.toLowerCase();
15677
- }
15678
-
15679
15451
  // src/proto/tx-encode.ts
15680
15452
  var WIRE_VARINT = 0;
15681
15453
  var WIRE_LENGTH_DELIMITED = 2;
@@ -24564,9 +24336,380 @@ var MSG_ENCODERS = {
24564
24336
  ).finish()
24565
24337
  };
24566
24338
 
24567
- // src/eip712/sign-and-broadcast.ts
24568
- async function queryAccount(network, address, fetchFn, fetchOptions) {
24569
- const data = await fetchJson(
24339
+ // src/eip712/simulate.ts
24340
+ var SIMULATE_PATH = "/cosmos/tx/v1beta1/simulate";
24341
+ var SIMULATION_PLACEHOLDER_PUBKEY = new Uint8Array([
24342
+ 2,
24343
+ 121,
24344
+ 190,
24345
+ 102,
24346
+ 126,
24347
+ 249,
24348
+ 220,
24349
+ 187,
24350
+ 172,
24351
+ 85,
24352
+ 160,
24353
+ 98,
24354
+ 149,
24355
+ 206,
24356
+ 135,
24357
+ 11,
24358
+ 7,
24359
+ 2,
24360
+ 155,
24361
+ 252,
24362
+ 219,
24363
+ 45,
24364
+ 206,
24365
+ 40,
24366
+ 217,
24367
+ 89,
24368
+ 242,
24369
+ 129,
24370
+ 91,
24371
+ 22,
24372
+ 248,
24373
+ 23,
24374
+ 152
24375
+ ]);
24376
+ var SIMULATION_PLACEHOLDER_SIGNATURE = new Uint8Array(64);
24377
+ var CHAIN_VERDICT_STATUSES = /* @__PURE__ */ new Set([400, 500]);
24378
+ var CHAIN_VERDICT_CODES = /* @__PURE__ */ new Set([2, 3]);
24379
+ async function simulateTx({
24380
+ network,
24381
+ msgs,
24382
+ memo = "",
24383
+ sequence,
24384
+ pubkeyBase64,
24385
+ placeholderGasLimit,
24386
+ placeholderFee,
24387
+ fetchFn,
24388
+ fetchOptions
24389
+ }) {
24390
+ const encodedMessages = msgs.map((msg2) => {
24391
+ const encoder = MSG_ENCODERS[msg2.typeUrl];
24392
+ if (!encoder) {
24393
+ throw new Error(`No encoder found for message type: ${msg2.typeUrl}`);
24394
+ }
24395
+ return { typeUrl: msg2.typeUrl, value: encoder(msg2.value) };
24396
+ });
24397
+ const pubkeyBytes = pubkeyBase64 ? base64ToBytes(pubkeyBase64) : SIMULATION_PLACEHOLDER_PUBKEY;
24398
+ const txRawBytes = encodeTxRaw({
24399
+ bodyBytes: encodeTxBody({ messages: encodedMessages, memo }),
24400
+ authInfoBytes: encodeAuthInfo({
24401
+ signerInfos: [
24402
+ {
24403
+ publicKey: {
24404
+ typeUrl: "/cosmos.evm.crypto.v1.ethsecp256k1.PubKey",
24405
+ value: encodeEthSecp256k1PubKey(pubkeyBytes)
24406
+ },
24407
+ mode: SIGN_MODE_LEGACY_AMINO_JSON,
24408
+ sequence
24409
+ }
24410
+ ],
24411
+ fee: { amount: [placeholderFee], gasLimit: BigInt(placeholderGasLimit) }
24412
+ }),
24413
+ signatures: [SIMULATION_PLACEHOLDER_SIGNATURE]
24414
+ });
24415
+ const url = `${network.restUrl}${SIMULATE_PATH}`;
24416
+ let response;
24417
+ try {
24418
+ response = await postJson(
24419
+ url,
24420
+ { tx_bytes: bytesToBase64(txRawBytes) },
24421
+ {
24422
+ ...fetchOptions,
24423
+ // 500 carries the verdict; never retry it. The rest of the caller's
24424
+ // policy stays.
24425
+ retryableStatuses: (fetchOptions?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES).filter(
24426
+ (status) => status !== 500
24427
+ )
24428
+ },
24429
+ fetchFn
24430
+ );
24431
+ } catch (error) {
24432
+ const verdict = chainVerdict(error);
24433
+ if (verdict) {
24434
+ throw new TxSimulationError(verdict);
24435
+ }
24436
+ const detail = error instanceof Error ? error.message : String(error);
24437
+ console.warn(`[ault-sdk] tx simulation unavailable (${url}); using static gas: ${detail}`);
24438
+ return null;
24439
+ }
24440
+ const gasUsed = response.gas_info?.gas_used;
24441
+ if (typeof gasUsed !== "string" || !/^\d+$/.test(gasUsed) || gasUsed === "0") {
24442
+ console.warn(`[ault-sdk] tx simulation returned no usable gas_used (${url}); using static gas`);
24443
+ return null;
24444
+ }
24445
+ return { gasUsed: BigInt(gasUsed) };
24446
+ }
24447
+ function chainVerdict(error) {
24448
+ if (!(error instanceof ApiError) || typeof error.status !== "number") return null;
24449
+ if (!CHAIN_VERDICT_STATUSES.has(error.status) || !error.response) return null;
24450
+ let body;
24451
+ try {
24452
+ body = JSON.parse(error.response);
24453
+ } catch {
24454
+ return null;
24455
+ }
24456
+ if (typeof body !== "object" || body === null) return null;
24457
+ const { code, message } = body;
24458
+ if (typeof code !== "number" || !CHAIN_VERDICT_CODES.has(code)) return null;
24459
+ if (typeof message !== "string" || message.length === 0) return null;
24460
+ return { rawLog: message, chainCode: code };
24461
+ }
24462
+
24463
+ // src/rest/feemarket.ts
24464
+ async function fetchFeeMarketParams(network, fetchFn, fetchOptions) {
24465
+ const data = await fetchJson(
24466
+ `${network.restUrl}/cosmos/evm/feemarket/v1/params`,
24467
+ {},
24468
+ fetchOptions,
24469
+ fetchFn
24470
+ );
24471
+ const raw = data.params ?? {};
24472
+ return {
24473
+ noBaseFee: raw.noBaseFee ?? raw.no_base_fee ?? false,
24474
+ baseFee: raw.baseFee ?? raw.base_fee ?? "0",
24475
+ minGasPrice: raw.minGasPrice ?? raw.min_gas_price ?? "0"
24476
+ };
24477
+ }
24478
+ var ONE_E18 = 1000000000000000000n;
24479
+ var DEFAULT_FEE_MARGIN_PERCENT = 20;
24480
+ function marginFactorScaled(marginPercent) {
24481
+ if (!Number.isFinite(marginPercent) || !Number.isInteger(marginPercent)) {
24482
+ throw new Error(`marginPercent must be a non-negative integer, got ${marginPercent}`);
24483
+ }
24484
+ if (marginPercent < 0) {
24485
+ throw new Error(`marginPercent must be >= 0, got ${marginPercent}`);
24486
+ }
24487
+ return BigInt(100 + marginPercent);
24488
+ }
24489
+ function computeRequiredFee(params, gas, options) {
24490
+ const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
24491
+ const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
24492
+ const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
24493
+ const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
24494
+ if (effectiveI <= 0n) return "0";
24495
+ const gasI = BigInt(gas);
24496
+ if (gasI <= 0n) return "0";
24497
+ const numerator = effectiveI * gasI * margin;
24498
+ const denominator = ONE_E18 * 100n;
24499
+ return ((numerator + denominator - 1n) / denominator).toString();
24500
+ }
24501
+ var DEFAULT_FEE_MARKET_TTL_MS = 3e3;
24502
+ function createFeeMarketCache(ttlMs = DEFAULT_FEE_MARKET_TTL_MS) {
24503
+ return { ttlMs, entries: /* @__PURE__ */ new Map() };
24504
+ }
24505
+ async function getCachedFeeMarketParams(cache, network, fetchFn, fetchOptions) {
24506
+ const key = network.chainId;
24507
+ const now = Date.now();
24508
+ if (cache) {
24509
+ const existing = cache.entries.get(key);
24510
+ if (existing && now - existing.fetchedAt < cache.ttlMs) {
24511
+ return existing.params;
24512
+ }
24513
+ }
24514
+ let params;
24515
+ try {
24516
+ params = await fetchFeeMarketParams(network, fetchFn, fetchOptions);
24517
+ } catch (error) {
24518
+ if (!isGatewayUnsupportedError(error)) throw error;
24519
+ params = null;
24520
+ }
24521
+ if (cache) {
24522
+ cache.entries.set(key, { params, fetchedAt: now });
24523
+ }
24524
+ return params;
24525
+ }
24526
+ function isGatewayUnsupportedError(error) {
24527
+ return error instanceof ApiError && (error.status === 404 || error.status === 501);
24528
+ }
24529
+ function computeEvmFeesPerGas(params, options) {
24530
+ const margin = marginFactorScaled(options?.marginPercent ?? DEFAULT_FEE_MARGIN_PERCENT);
24531
+ const minGasPriceI = BigInt(cosmosDecToProtoInt(params.minGasPrice || "0"));
24532
+ const baseFeeI = params.noBaseFee ? 0n : BigInt(cosmosDecToProtoInt(params.baseFee || "0"));
24533
+ const effectiveI = baseFeeI > minGasPriceI ? baseFeeI : minGasPriceI;
24534
+ if (effectiveI <= 0n) {
24535
+ return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n };
24536
+ }
24537
+ const numerator = effectiveI * margin;
24538
+ const denominator = ONE_E18 * 100n;
24539
+ const gasPriceWei = (numerator + denominator - 1n) / denominator;
24540
+ return { maxFeePerGas: gasPriceWei, maxPriorityFeePerGas: gasPriceWei };
24541
+ }
24542
+ async function resolveEvmFeesPerGas(network, options) {
24543
+ const params = await getCachedFeeMarketParams(
24544
+ options?.cache,
24545
+ network,
24546
+ options?.fetchFn,
24547
+ options?.fetchOptions
24548
+ );
24549
+ if (!params) return null;
24550
+ let fees;
24551
+ try {
24552
+ fees = computeEvmFeesPerGas(params, { marginPercent: options?.marginPercent });
24553
+ } catch {
24554
+ return null;
24555
+ }
24556
+ if (fees.maxFeePerGas === 0n && fees.maxPriorityFeePerGas === 0n) return null;
24557
+ return fees;
24558
+ }
24559
+
24560
+ // src/eip712/signers.ts
24561
+ import { privateKeyToAccount } from "viem/accounts";
24562
+ var AULT_SIGNER_MARKER = /* @__PURE__ */ Symbol.for("ault-sdk:signer");
24563
+ function isAultSigner(obj) {
24564
+ return typeof obj === "object" && obj !== null && AULT_SIGNER_MARKER in obj && obj[AULT_SIGNER_MARKER] === true;
24565
+ }
24566
+ function normalizeSigner(input) {
24567
+ if (!input) return null;
24568
+ if (typeof input === "function") {
24569
+ return { signTypedData: input };
24570
+ }
24571
+ if (typeof input === "object" && typeof input.signTypedData === "function") {
24572
+ return input;
24573
+ }
24574
+ throw new Error("Invalid signer: expected a signer object or signTypedData function.");
24575
+ }
24576
+ function normalizeSignature(result) {
24577
+ if (typeof result === "string") {
24578
+ return result;
24579
+ }
24580
+ if (result && typeof result.signature === "string") {
24581
+ return result.signature;
24582
+ }
24583
+ throw new Error("Invalid signature response: expected hex string or { signature }.");
24584
+ }
24585
+ async function getSignerAddress(signer) {
24586
+ if (typeof signer.address === "string") {
24587
+ return signer.address;
24588
+ }
24589
+ if (typeof signer.getAddress === "function") {
24590
+ const address = await signer.getAddress();
24591
+ return typeof address === "string" ? address : null;
24592
+ }
24593
+ return null;
24594
+ }
24595
+ async function resolveSignerAddress(signer, signerAddress) {
24596
+ const raw = signerAddress ?? (signer ? await getSignerAddress(signer) : null);
24597
+ if (!raw) {
24598
+ throw new Error("signerAddress is required when the signer has no address.");
24599
+ }
24600
+ if (isValidAultAddress(raw)) {
24601
+ return raw;
24602
+ }
24603
+ if (isValidEvmAddress(raw)) {
24604
+ return evmToAult(raw);
24605
+ }
24606
+ throw new Error(`Invalid signerAddress: ${raw}`);
24607
+ }
24608
+ function stripEip712Domain(types) {
24609
+ const { EIP712Domain: _removed, ...rest } = types;
24610
+ return rest;
24611
+ }
24612
+ function createEip1193Signer(options) {
24613
+ const method = options.method ?? "eth_signTypedData_v4";
24614
+ return {
24615
+ [AULT_SIGNER_MARKER]: true,
24616
+ address: options.address,
24617
+ signTypedData: async (typedData) => {
24618
+ const payload = method === "eth_signTypedData_v4" ? JSON.stringify(typedData) : typedData;
24619
+ const signature = await options.provider.request({
24620
+ method,
24621
+ params: [options.address, payload]
24622
+ });
24623
+ if (typeof signature !== "string") {
24624
+ throw new Error("Provider did not return a signature string.");
24625
+ }
24626
+ return { signature };
24627
+ }
24628
+ };
24629
+ }
24630
+ function createViemSigner(wallet, options) {
24631
+ const preferRpc = options?.preferRpc ?? true;
24632
+ const getAddress3 = async () => {
24633
+ if (wallet.address) return wallet.address;
24634
+ if (wallet.getAddresses) {
24635
+ const addresses = await wallet.getAddresses();
24636
+ if (addresses?.length) return addresses[0];
24637
+ }
24638
+ return void 0;
24639
+ };
24640
+ return {
24641
+ [AULT_SIGNER_MARKER]: true,
24642
+ getAddress: async () => {
24643
+ const addr = await getAddress3();
24644
+ if (!addr) throw new Error("Viem wallet has no address");
24645
+ return addr;
24646
+ },
24647
+ signTypedData: async (typedData) => {
24648
+ if (preferRpc && wallet.request) {
24649
+ const address = await getAddress3();
24650
+ if (!address) {
24651
+ throw new Error("Viem wallet has no address; pass signerAddress explicitly.");
24652
+ }
24653
+ const signature2 = await wallet.request({
24654
+ method: "eth_signTypedData_v4",
24655
+ params: [address, JSON.stringify(typedData)]
24656
+ });
24657
+ if (typeof signature2 !== "string") {
24658
+ throw new Error("RPC signer did not return a signature string.");
24659
+ }
24660
+ return { signature: signature2 };
24661
+ }
24662
+ if (!wallet.signTypedData) {
24663
+ throw new Error("Viem signer does not support signTypedData.");
24664
+ }
24665
+ const signature = await wallet.signTypedData({
24666
+ domain: typedData.domain,
24667
+ types: typedData.types,
24668
+ primaryType: typedData.primaryType,
24669
+ message: typedData.message
24670
+ });
24671
+ return { signature };
24672
+ }
24673
+ };
24674
+ }
24675
+ function createEthersSigner(signer) {
24676
+ const sign = signer.signTypedData ?? signer._signTypedData;
24677
+ if (!sign) {
24678
+ throw new Error("Ethers signer must implement signTypedData or _signTypedData.");
24679
+ }
24680
+ return {
24681
+ [AULT_SIGNER_MARKER]: true,
24682
+ getAddress: () => signer.getAddress(),
24683
+ signTypedData: async (typedData) => {
24684
+ const types = stripEip712Domain(typedData.types);
24685
+ const signature = await sign(typedData.domain, types, typedData.message);
24686
+ return { signature };
24687
+ }
24688
+ };
24689
+ }
24690
+ function createPrivySigner(options) {
24691
+ return {
24692
+ [AULT_SIGNER_MARKER]: true,
24693
+ address: options.address,
24694
+ signTypedData: (typedData) => options.signTypedData(typedData, options.address ? { address: options.address } : void 0)
24695
+ };
24696
+ }
24697
+ function createPrivateKeySigner(privateKey) {
24698
+ const normalized = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
24699
+ const account = privateKeyToAccount(normalized);
24700
+ return createViemSigner(account);
24701
+ }
24702
+
24703
+ // src/utils/tx-hash.ts
24704
+ function normalizeTxHash(raw) {
24705
+ if (!raw) return raw;
24706
+ const stripped = raw.startsWith("0x") || raw.startsWith("0X") ? raw.slice(2) : raw;
24707
+ return stripped.toLowerCase();
24708
+ }
24709
+
24710
+ // src/eip712/sign-and-broadcast.ts
24711
+ async function queryAccount(network, address, fetchFn, fetchOptions) {
24712
+ const data = await fetchJson(
24570
24713
  `${network.restUrl}/cosmos/auth/v1beta1/accounts/${address}`,
24571
24714
  {},
24572
24715
  fetchOptions,
@@ -24621,6 +24764,9 @@ function createAccountCache() {
24621
24764
  function getNextSequence(sequence) {
24622
24765
  return String(BigInt(sequence) + 1n);
24623
24766
  }
24767
+ function isSequenceMismatch(rawLog) {
24768
+ return rawLog.includes("account sequence mismatch") || rawLog.includes("incorrect account sequence");
24769
+ }
24624
24770
  function clearCachedSequence(cache) {
24625
24771
  if (cache) {
24626
24772
  cache.nextSequence = null;
@@ -24723,6 +24869,8 @@ async function signAndBroadcastEip712({
24723
24869
  feeDenom,
24724
24870
  feeAmount,
24725
24871
  confirmationTimeoutMs,
24872
+ simulateGas = false,
24873
+ simulatedGasMultiplier,
24726
24874
  wait = true,
24727
24875
  fetchFn,
24728
24876
  fetchOptions,
@@ -24749,15 +24897,46 @@ async function signAndBroadcastEip712({
24749
24897
  if (!sequence) {
24750
24898
  throw new Error(`Unable to resolve account sequence for signer ${resolvedSignerAddress}.`);
24751
24899
  }
24752
- const resolvedGas = gasLimit ?? network.eip712GasLimit ?? GAS_CONSTANTS.EIP712_GAS_LIMIT;
24753
- const resolvedFeeAmount = feeAmount ?? network.eip712FeeAmount ?? await resolveDynamicFeeAmount(network, resolvedGas, feeMarketCache, fetchFn, fetchOptions);
24900
+ let resolvedGas = gasLimit ?? network.eip712GasLimit ?? GAS_CONSTANTS.EIP712_GAS_LIMIT;
24901
+ const resolvedFeeDenom = feeDenom ?? network.eip712FeeDenom ?? GAS_CONSTANTS.DENOM;
24902
+ const feeOverride = feeAmount ?? network.eip712FeeAmount;
24903
+ const feeFor = async (gas) => feeOverride ?? await resolveDynamicFeeAmount(network, gas, feeMarketCache, fetchFn, fetchOptions);
24904
+ let resolvedFeeAmount;
24905
+ if (simulateGas) {
24906
+ let simulated;
24907
+ try {
24908
+ simulated = await simulateTx({
24909
+ network,
24910
+ msgs,
24911
+ memo,
24912
+ sequence,
24913
+ pubkeyBase64: cache?.pubkeyBase64 ?? accountInfo?.pubkeyBase64 ?? null,
24914
+ placeholderGasLimit: resolvedGas,
24915
+ placeholderFee: { denom: resolvedFeeDenom, amount: await feeFor(resolvedGas) },
24916
+ fetchFn,
24917
+ fetchOptions
24918
+ });
24919
+ } catch (error) {
24920
+ if (error instanceof TxSimulationError && isSequenceMismatch(error.rawLog)) {
24921
+ clearCachedSequence(cache);
24922
+ }
24923
+ throw error;
24924
+ }
24925
+ if (simulated) {
24926
+ resolvedGas = computeSimulatedGas(
24927
+ simulated.gasUsed,
24928
+ simulatedGasMultiplier ?? GAS_CONSTANTS.SIMULATED_GAS_MULTIPLIER
24929
+ );
24930
+ }
24931
+ }
24932
+ resolvedFeeAmount = await feeFor(resolvedGas);
24754
24933
  const context = {
24755
24934
  chainId: network.chainId,
24756
24935
  accountNumber,
24757
24936
  sequence,
24758
24937
  fee: {
24759
24938
  amount: resolvedFeeAmount,
24760
- denom: feeDenom ?? network.eip712FeeDenom ?? GAS_CONSTANTS.DENOM,
24939
+ denom: resolvedFeeDenom,
24761
24940
  gas: resolvedGas
24762
24941
  },
24763
24942
  memo
@@ -26422,6 +26601,13 @@ function createRewardTxApi({ signerAddress, exec, getGas }) {
26422
26601
  }
26423
26602
 
26424
26603
  // src/high-level/tx/staking.ts
26604
+ function stakingGasOptions(gas, fallbackMinGas, gasLimit) {
26605
+ return {
26606
+ gasLimit: gasLimit ?? computeFeeFreeGas(fallbackMinGas, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26607
+ simulateGas: gasLimit == null,
26608
+ simulatedGasMultiplier: gas.SIMULATED_GAS_MULTIPLIER
26609
+ };
26610
+ }
26425
26611
  function createStakingTxApi({ signerAddress, exec, getGas }) {
26426
26612
  return {
26427
26613
  async delegate({ validatorAddress, amount, gasLimit, feeAmount, memo, confirmationTimeoutMs }) {
@@ -26435,7 +26621,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26435
26621
  })
26436
26622
  ],
26437
26623
  {
26438
- gasLimit: gasLimit ?? computeFeeFreeGas(gas.DELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26624
+ ...stakingGasOptions(gas, gas.DELEGATE, gasLimit),
26439
26625
  feeAmount,
26440
26626
  memo,
26441
26627
  confirmationTimeoutMs
@@ -26460,7 +26646,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26460
26646
  })
26461
26647
  ],
26462
26648
  {
26463
- gasLimit: gasLimit ?? computeFeeFreeGas(gas.UNDELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26649
+ ...stakingGasOptions(gas, gas.UNDELEGATE, gasLimit),
26464
26650
  feeAmount,
26465
26651
  memo,
26466
26652
  confirmationTimeoutMs
@@ -26487,7 +26673,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26487
26673
  })
26488
26674
  ],
26489
26675
  {
26490
- gasLimit: gasLimit ?? computeFeeFreeGas(gas.BEGIN_REDELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
26676
+ ...stakingGasOptions(gas, gas.BEGIN_REDELEGATE, gasLimit),
26491
26677
  feeAmount,
26492
26678
  memo,
26493
26679
  confirmationTimeoutMs
@@ -26506,7 +26692,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26506
26692
  }
26507
26693
  const normalized = validatorAddresses.map(assertValidatorAddress);
26508
26694
  const gas = getGas();
26509
- const resolvedGasLimit = gasLimit ?? computeFeeFreeGas(gas.WITHDRAW_DELEGATOR_REWARD, 1, gas.FEE_FREE_GAS_MULTIPLIER);
26695
+ const gasOptions = stakingGasOptions(gas, gas.WITHDRAW_DELEGATOR_REWARD, gasLimit);
26510
26696
  const results = [];
26511
26697
  const partial = [];
26512
26698
  for (let i = 0; i < normalized.length; i++) {
@@ -26519,7 +26705,7 @@ function createStakingTxApi({ signerAddress, exec, getGas }) {
26519
26705
  validatorAddress
26520
26706
  })
26521
26707
  ],
26522
- { gasLimit: resolvedGasLimit, feeAmount, memo, confirmationTimeoutMs }
26708
+ { ...gasOptions, feeAmount, memo, confirmationTimeoutMs }
26523
26709
  );
26524
26710
  results.push(result);
26525
26711
  partial.push({ txHash: result.txHash, validatorAddress });
@@ -26708,6 +26894,8 @@ function createTxExecutor(options) {
26708
26894
  feeAmount: txOptions?.feeAmount,
26709
26895
  memo: txOptions?.memo ?? defaultMemo,
26710
26896
  confirmationTimeoutMs: txOptions?.confirmationTimeoutMs ?? defaultConfirmationTimeoutMs,
26897
+ simulateGas: txOptions?.simulateGas ?? false,
26898
+ simulatedGasMultiplier: txOptions?.simulatedGasMultiplier,
26711
26899
  wait: txOptions?.wait ?? true,
26712
26900
  fetchFn: options.fetchFn,
26713
26901
  fetchOptions,
@@ -26730,6 +26918,8 @@ function createTxExecutor(options) {
26730
26918
  import { z } from "zod";
26731
26919
  var ManifestGasSchema = z.object({
26732
26920
  FEE_FREE_GAS_MULTIPLIER: z.number().int().positive(),
26921
+ // Under 100% signs less gas than the simulation already burned.
26922
+ SIMULATED_GAS_MULTIPLIER: z.number().int().min(100),
26733
26923
  PER_LICENSE: z.number().int().positive(),
26734
26924
  PER_KYC_MEMBER: z.number().int().positive(),
26735
26925
  PER_DELEGATE_MINING: z.number().int().positive(),
@@ -28437,7 +28627,7 @@ function createDexWs(url, options) {
28437
28627
  }
28438
28628
 
28439
28629
  // src/index.ts
28440
- var SDK_VERSION = "0.7.0";
28630
+ var SDK_VERSION = "0.7.1";
28441
28631
  export {
28442
28632
  AGENT_DEFAULTS,
28443
28633
  AULT_SIGNER_MARKER,
@@ -28447,6 +28637,7 @@ export {
28447
28637
  BondStatus,
28448
28638
  COIN_TYPE,
28449
28639
  DEFAULT_CHAIN_ID,
28640
+ DEFAULT_RETRYABLE_STATUSES,
28450
28641
  DexWsClient,
28451
28642
  EIP712_DOMAIN_TYPE,
28452
28643
  EIP712_MSG_TYPES,
@@ -28522,6 +28713,7 @@ export {
28522
28713
  SDK_VERSION,
28523
28714
  SIGN_MODE_DIRECT,
28524
28715
  SIGN_MODE_LEGACY_AMINO_JSON,
28716
+ SIMULATION_PLACEHOLDER_PUBKEY,
28525
28717
  SearchUDFSymbolsQueryParams,
28526
28718
  SearchUDFSymbolsResponse,
28527
28719
  SearchUDFSymbolsResponseItem,
@@ -28531,6 +28723,7 @@ export {
28531
28723
  TxConfirmationUnavailableError,
28532
28724
  TxError,
28533
28725
  TxNotConfirmedError,
28726
+ TxSimulationError,
28534
28727
  BondStatus as ValidatorStatus,
28535
28728
  WebSocketError,
28536
28729
  WithdrawRewardsPartialError,
@@ -28553,6 +28746,7 @@ export {
28553
28746
  computeFeeFreeGas,
28554
28747
  computeFeeFreeGasCompound,
28555
28748
  computeRequiredFee,
28749
+ computeSimulatedGas,
28556
28750
  cosmosDecToDecimalString,
28557
28751
  cosmosDecToProtoInt,
28558
28752
  createAccountCache,
@@ -28716,6 +28910,7 @@ export {
28716
28910
  resolveSignerAddress,
28717
28911
  signAndBroadcastAgentTx,
28718
28912
  signAndBroadcastEip712,
28913
+ simulateTx,
28719
28914
  stripEip712Domain,
28720
28915
  toViemChain,
28721
28916
  validateEip712FieldOrder,