ault-sdk-ts 0.0.2-alpha.18 → 0.0.2-alpha.20

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
@@ -118,6 +118,7 @@ __export(index_exports, {
118
118
  WebSocketError: () => WebSocketError,
119
119
  WithdrawRewardsPartialError: () => WithdrawRewardsPartialError,
120
120
  _resetIndexingCache: () => _resetIndexingCache,
121
+ addressBytes: () => addressBytes,
121
122
  addressEquals: () => addressEquals,
122
123
  applyGasOverrides: () => applyGasOverrides,
123
124
  applyNetworkOverrides: () => applyNetworkOverrides,
@@ -680,6 +681,15 @@ var GAS_CONSTANTS = {
680
681
  DENOM: "aault",
681
682
  /** Chain multiplier applied to min gas to derive max gas (120 = 1.2×). */
682
683
  FEE_FREE_GAS_MULTIPLIER: 120,
684
+ /**
685
+ * EIP-712 ante overhead, in gas. The chain's per-message MinGasLimit values
686
+ * (mirrored below) measure the *handler* cost only; a fee-free EIP-712 tx
687
+ * additionally burns ante gas (sig verification + typed-data decode + tx
688
+ * size) that counts against gasWanted. For small-base ops (cancel) the 1.2×
689
+ * buffer doesn't cover it, so the high-level (EIP-712) path adds this on top.
690
+ * The agent path is capped at MinGasLimit×1.2 and must not add it.
691
+ */
692
+ EIP712_ANTE_GAS: 3e4,
683
693
  // License module
684
694
  PER_LICENSE: 2e5,
685
695
  PER_KYC_MEMBER: 2e5,
@@ -695,15 +705,22 @@ var GAS_CONSTANTS = {
695
705
  REVOKE_BUILDER: 57e3,
696
706
  SET_REFERRAL_CODE: 76e3,
697
707
  SET_REFERRAL: 9e4,
698
- // CLOB module
699
- LIMIT_ORDER: 124e3,
700
- MARKET_ORDER: 116e3,
708
+ // CLOB module — mirror the chain's x/clob MinGasLimit* (agent_msg.go) exactly:
709
+ // the agent ante enforces MinGasLimit ≤ gas ≤ MinGasLimit×1.2, so any drift
710
+ // makes the SDK over- or under-shoot that window.
711
+ LIMIT_ORDER: 125e3,
712
+ MARKET_ORDER: 119e3,
701
713
  SCALE_ORDER_BASE: 115e3,
702
- SCALE_ORDER_PER_SUB: 11e3,
703
- CANCEL_ORDER_BASE: 49e3,
704
- CANCEL_ORDER_PER_ID: 22e3,
714
+ SCALE_ORDER_PER_SUB: 13e3,
715
+ CANCEL_ORDER_BASE: 5e4,
716
+ CANCEL_ORDER_PER_ID: 19e3,
705
717
  // Accountx module
706
- OPEN_ACCOUNT: 96e3
718
+ OPEN_ACCOUNT: 96e3,
719
+ // Staking module (cosmos-sdk standard, NOT fee-free — user pays gas).
720
+ DELEGATE: 22e4,
721
+ UNDELEGATE: 22e4,
722
+ BEGIN_REDELEGATE: 28e4,
723
+ WITHDRAW_DELEGATOR_REWARD: 22e4
707
724
  };
708
725
  function computeFeeFreeGas(minGasPerOp, count, multiplier = GAS_CONSTANTS.FEE_FREE_GAS_MULTIPLIER) {
709
726
  return (BigInt(minGasPerOp) * BigInt(count) * BigInt(multiplier) / 100n).toString();
@@ -11378,30 +11395,165 @@ function createDexApi(context) {
11378
11395
  };
11379
11396
  }
11380
11397
 
11398
+ // src/utils/address.ts
11399
+ var import_encoding = require("@cosmjs/encoding");
11400
+ var import_viem2 = require("viem");
11401
+ function evmToAult(evmAddress) {
11402
+ const hex = evmAddress.toLowerCase().replace("0x", "");
11403
+ const bytes = (0, import_encoding.fromHex)(hex);
11404
+ return (0, import_encoding.toBech32)("ault", bytes);
11405
+ }
11406
+ function aultToEvm(aultAddress) {
11407
+ const { data } = (0, import_encoding.fromBech32)(aultAddress);
11408
+ return (0, import_viem2.getAddress)(`0x${(0, import_encoding.toHex)(data)}`);
11409
+ }
11410
+ function isValidAultAddress(address) {
11411
+ try {
11412
+ const { prefix, data } = (0, import_encoding.fromBech32)(address);
11413
+ return prefix === "ault" && data.length === 20;
11414
+ } catch {
11415
+ return false;
11416
+ }
11417
+ }
11418
+ function isValidEvmAddress(address) {
11419
+ if (!/^0[xX][a-fA-F0-9]{40}$/.test(address)) return false;
11420
+ const normalized = `0x${address.slice(2)}`;
11421
+ const body = normalized.slice(2);
11422
+ const allLower = body === body.toLowerCase();
11423
+ const allUpper = body === body.toUpperCase();
11424
+ if (allLower || allUpper) return true;
11425
+ return (0, import_viem2.isAddress)(normalized, { strict: true });
11426
+ }
11427
+ function addressEquals(a, b) {
11428
+ const ab = addressBytes(a);
11429
+ const bb = addressBytes(b);
11430
+ if (!ab || !bb || ab.length !== bb.length) return false;
11431
+ for (let i = 0; i < ab.length; i++) {
11432
+ if (ab[i] !== bb[i]) return false;
11433
+ }
11434
+ return true;
11435
+ }
11436
+ function addressBytes(s) {
11437
+ if (!s) return null;
11438
+ if (s.startsWith("0x") || s.startsWith("0X")) {
11439
+ const body = s.slice(2);
11440
+ if (!/^[a-fA-F0-9]+$/.test(body) || body.length !== 40) return null;
11441
+ return (0, import_encoding.fromHex)(body.toLowerCase());
11442
+ }
11443
+ try {
11444
+ const { data } = (0, import_encoding.fromBech32)(s);
11445
+ return data;
11446
+ } catch {
11447
+ return null;
11448
+ }
11449
+ }
11450
+ function isValidValidatorAddress(address) {
11451
+ try {
11452
+ const { prefix, data } = (0, import_encoding.fromBech32)(address);
11453
+ return prefix === "aultvaloper" && data.length === 20;
11454
+ } catch {
11455
+ return false;
11456
+ }
11457
+ }
11458
+ function assertValidatorAddress(address) {
11459
+ if (isValidValidatorAddress(address)) {
11460
+ return address;
11461
+ }
11462
+ throw new Error(`Invalid validator address format: ${address}`);
11463
+ }
11464
+
11381
11465
  // src/ws/client.ts
11466
+ var import_encoding2 = require("@cosmjs/encoding");
11382
11467
  var NORMAL_CLOSURE = 1e3;
11383
- var WS_OPEN = 1;
11468
+ var WS_READY_STATE_OPEN = 1;
11384
11469
  var COMMAND_TIMEOUT_MS = 1e4;
11470
+ var USER_AMBIGUOUS_CHANNELS = /* @__PURE__ */ new Set(["orderUpdates", "userEvents"]);
11471
+ var MARKET_CHANNELS = /* @__PURE__ */ new Set([
11472
+ "l2Book",
11473
+ "bbo",
11474
+ "trades",
11475
+ "candle",
11476
+ "activeAssetCtx"
11477
+ ]);
11478
+ var USER_CHANNELS = /* @__PURE__ */ new Set([
11479
+ "orderUpdates",
11480
+ "openOrders",
11481
+ "userFills",
11482
+ "userEvents",
11483
+ "spotState"
11484
+ ]);
11485
+ var CHANNEL_SUBSCRIPTION_RESPONSE = "subscriptionResponse";
11486
+ var CHANNEL_ERROR = "error";
11487
+ var CHANNEL_SUBSCRIPTION_EXPIRED = "subscriptionExpired";
11488
+ function topicKey(sub) {
11489
+ const parts = [sub.type];
11490
+ if (sub.coin) parts.push(sub.coin);
11491
+ if (sub.user) parts.push(canonicalUser(sub.user));
11492
+ if (sub.interval) parts.push(sub.interval);
11493
+ return parts.join("|");
11494
+ }
11495
+ function canonicalUser(user) {
11496
+ const bytes = addressBytes(user);
11497
+ return bytes ? (0, import_encoding2.toHex)(bytes).toLowerCase() : user.toLowerCase();
11498
+ }
11499
+ function buildSubscriptionPayload(sub, ttl) {
11500
+ const out = { type: sub.type };
11501
+ if (sub.coin) out.coin = sub.coin;
11502
+ if (sub.user) out.user = sub.user;
11503
+ if (sub.interval) out.interval = sub.interval;
11504
+ if (ttl !== void 0) out.ttl = ttl;
11505
+ return out;
11506
+ }
11507
+ function isRecord(value) {
11508
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11509
+ }
11510
+ function frameMatches(sub, data) {
11511
+ switch (sub.type) {
11512
+ case "l2Book":
11513
+ case "bbo":
11514
+ case "activeAssetCtx":
11515
+ return isRecord(data) && data.coin === sub.coin;
11516
+ case "trades": {
11517
+ if (!Array.isArray(data) || data.length === 0) return false;
11518
+ const first = data[0];
11519
+ return first?.coin === sub.coin;
11520
+ }
11521
+ case "candle": {
11522
+ if (!Array.isArray(data) || data.length === 0) return false;
11523
+ const first = data[0];
11524
+ return first?.s === sub.coin && first?.i === sub.interval;
11525
+ }
11526
+ case "openOrders":
11527
+ case "userFills":
11528
+ case "spotState":
11529
+ return isRecord(data) && typeof data.user === "string" && !!sub.user && addressEquals(data.user, sub.user);
11530
+ case "orderUpdates":
11531
+ case "userEvents":
11532
+ return true;
11533
+ case "allMids":
11534
+ case "chainBlock":
11535
+ return true;
11536
+ default:
11537
+ return false;
11538
+ }
11539
+ }
11385
11540
  var isowsModulePromise = null;
11541
+ function wrapCtor(Ctor) {
11542
+ return (url, protocols) => protocols === void 0 ? new Ctor(url) : new Ctor(url, protocols);
11543
+ }
11544
+ function currentGlobalCtor() {
11545
+ return typeof globalThis !== "undefined" && typeof globalThis.WebSocket === "function" ? globalThis.WebSocket : null;
11546
+ }
11386
11547
  function getDefaultWebSocketFactory() {
11387
- if (typeof globalThis !== "undefined" && typeof globalThis.WebSocket === "function") {
11388
- return (url, protocols) => {
11389
- const Ctor = globalThis.WebSocket;
11390
- return protocols === void 0 ? new Ctor(url) : new Ctor(url, protocols);
11391
- };
11392
- }
11548
+ const G = currentGlobalCtor();
11549
+ if (G) return wrapCtor(G);
11393
11550
  if (!isowsModulePromise) {
11394
11551
  isowsModulePromise = import("isows");
11395
11552
  }
11396
11553
  return isowsModulePromise.then((mod) => {
11397
- if (typeof globalThis !== "undefined" && typeof globalThis.WebSocket === "function") {
11398
- return (url, protocols) => {
11399
- const Ctor2 = globalThis.WebSocket;
11400
- return protocols === void 0 ? new Ctor2(url) : new Ctor2(url, protocols);
11401
- };
11402
- }
11403
- const Ctor = mod.WebSocket;
11404
- return (url, protocols) => protocols === void 0 ? new Ctor(url) : new Ctor(url, protocols);
11554
+ const G2 = currentGlobalCtor();
11555
+ if (G2) return wrapCtor(G2);
11556
+ return wrapCtor(mod.WebSocket);
11405
11557
  });
11406
11558
  }
11407
11559
  var DexWsClient = class {
@@ -11409,7 +11561,12 @@ var DexWsClient = class {
11409
11561
  this.ws = null;
11410
11562
  this.connectionState = "disconnected";
11411
11563
  this.subscriptions = /* @__PURE__ */ new Map();
11412
- this.listeners = /* @__PURE__ */ new Map();
11564
+ // Per-event handler sets keyed by event name. Typed against the event map so
11565
+ // each set holds exactly that event's handler signature — no `Function`/`any`
11566
+ // erasure. `on`/`emit` index it generically; the lone cast at insertion (in
11567
+ // `on`) is sound because the public `on<E>` overload pins `handler` to
11568
+ // `DexWsEventMap[E]` at the boundary.
11569
+ this.listeners = {};
11413
11570
  this.pendingCommands = /* @__PURE__ */ new Map();
11414
11571
  this.reconnectAttempt = 0;
11415
11572
  this.reconnectTimer = null;
@@ -11460,39 +11617,121 @@ var DexWsClient = class {
11460
11617
  this.rejectConnect(err);
11461
11618
  this.rejectPendingCommands(err);
11462
11619
  }
11463
- subscribe(topic, handlers, options) {
11620
+ /**
11621
+ * Subscribe to a channel. `handlers.onData` receives every frame (snapshot
11622
+ * and deltas alike); the SDK makes no assumption that the first frame is a
11623
+ * delta. Returns a handle whose `unsubscribe()` tears the subscription down.
11624
+ */
11625
+ subscribe(subscription, handlers, options) {
11626
+ this.assertRequiredKey(subscription);
11627
+ this.assertNoUserAmbiguity(subscription);
11464
11628
  const ttl = options?.ttl;
11465
- this.subscriptions.set(topic, { handlers, ttl });
11466
- this.sendCommand({ action: "subscribe", topic, ttl }).then(
11629
+ const key = topicKey(subscription);
11630
+ const active = { subscription, handlers, ttl };
11631
+ this.subscriptions.set(key, active);
11632
+ this.dispatchSubscribe(active);
11633
+ return {
11634
+ subscription,
11635
+ unsubscribe: () => this.unsubscribe(subscription)
11636
+ };
11637
+ }
11638
+ /**
11639
+ * Send a subscribe for an already-registered active subscription and wire its
11640
+ * ack/error/onSubscribed handling. Shared by the initial subscribe and the
11641
+ * reconnect replay so both paths surface failures via onError instead of
11642
+ * leaving a silent dead subscription.
11643
+ */
11644
+ dispatchSubscribe(active) {
11645
+ const { subscription, handlers, ttl } = active;
11646
+ const key = topicKey(subscription);
11647
+ const deleteIfOwned = () => {
11648
+ if (this.subscriptions.get(key) === active) this.subscriptions.delete(key);
11649
+ };
11650
+ this.sendSubscribe(subscription, ttl).then(
11467
11651
  (resp) => {
11468
11652
  if (resp.success) {
11469
- handlers.onSubscribed?.();
11653
+ handlers.onSubscribed?.(resp.ack);
11470
11654
  } else {
11471
- this.subscriptions.delete(topic);
11655
+ deleteIfOwned();
11472
11656
  handlers.onError?.(new WebSocketError(resp.error ?? "Subscribe failed"));
11473
11657
  }
11474
11658
  },
11475
11659
  (err) => {
11476
- this.subscriptions.delete(topic);
11660
+ deleteIfOwned();
11477
11661
  handlers.onError?.(err);
11478
11662
  }
11479
11663
  );
11480
- return {
11481
- topic,
11482
- unsubscribe: () => this.unsubscribe(topic)
11664
+ }
11665
+ /**
11666
+ * Enforce the per-channel required key at runtime. The `WsSubscription` union
11667
+ * already encodes this at compile time, but a caller can cast through it (e.g.
11668
+ * `type` via `as never` for a not-yet-typed channel). Registering a partial
11669
+ * sub is unsafe: a user channel with no `user` would match every frame on that
11670
+ * channel (frameMatches returns true for orderUpdates/userEvents) until the
11671
+ * async server reject lands. Throw before `subscriptions.set` instead.
11672
+ */
11673
+ assertRequiredKey(sub) {
11674
+ const isMarket = MARKET_CHANNELS.has(sub.type);
11675
+ const isUser = USER_CHANNELS.has(sub.type);
11676
+ if (isMarket && !sub.coin) {
11677
+ throw new WebSocketError(`"${sub.type}" requires a "coin"`);
11678
+ }
11679
+ if (sub.type === "candle" && !sub.interval) {
11680
+ throw new WebSocketError(`"candle" requires an "interval"`);
11681
+ }
11682
+ if (isUser && !sub.user) {
11683
+ throw new WebSocketError(`"${sub.type}" requires a "user"`);
11684
+ }
11685
+ const allowed = {
11686
+ coin: isMarket,
11687
+ user: isUser,
11688
+ interval: sub.type === "candle"
11483
11689
  };
11690
+ for (const field of ["coin", "user", "interval"]) {
11691
+ if (sub[field] !== void 0 && !allowed[field]) {
11692
+ throw new WebSocketError(`"${sub.type}" does not accept a "${field}" field`);
11693
+ }
11694
+ }
11695
+ }
11696
+ /**
11697
+ * Guard against multiplexing two different users across a user-ambiguous
11698
+ * channel (orderUpdates/userEvents) on one connection. Their frames carry no
11699
+ * `user`, so a second user's subscription would fan out into the first's
11700
+ * handler and vice-versa, leaking private order flow. Re-subscribing the same
11701
+ * user is allowed (it just refreshes handlers/ttl).
11702
+ */
11703
+ assertNoUserAmbiguity(sub) {
11704
+ if (!USER_AMBIGUOUS_CHANNELS.has(sub.type)) return;
11705
+ for (const active of this.subscriptions.values()) {
11706
+ if (active.subscription.type !== sub.type) continue;
11707
+ const existingUser = active.subscription.user;
11708
+ if (!existingUser || !sub.user || !addressEquals(existingUser, sub.user)) {
11709
+ throw new WebSocketError(
11710
+ `Cannot subscribe a second user to "${sub.type}" on a shared connection: this channel carries no user field, so frames cannot be disambiguated. Use a separate DexWsClient per user.`
11711
+ );
11712
+ }
11713
+ }
11484
11714
  }
11485
- unsubscribe(topic) {
11486
- this.subscriptions.delete(topic);
11715
+ unsubscribe(subscription) {
11716
+ const key = topicKey(subscription);
11717
+ this.subscriptions.delete(key);
11718
+ const pending = this.pendingCommands.get(key);
11719
+ if (pending) {
11720
+ clearTimeout(pending.timer);
11721
+ this.pendingCommands.delete(key);
11722
+ }
11487
11723
  if (this.connectionState === "connected") {
11488
- this.send({ action: "unsubscribe", topic });
11724
+ this.send({
11725
+ method: "unsubscribe",
11726
+ subscription: buildSubscriptionPayload(subscription)
11727
+ });
11489
11728
  }
11490
11729
  }
11491
11730
  on(event, handler) {
11492
- let set = this.listeners.get(event);
11731
+ let set = this.listeners[event];
11493
11732
  if (!set) {
11494
11733
  set = /* @__PURE__ */ new Set();
11495
- this.listeners.set(event, set);
11734
+ this.listeners[event] = set;
11496
11735
  }
11497
11736
  set.add(handler);
11498
11737
  return () => set.delete(handler);
@@ -11571,58 +11810,126 @@ var DexWsClient = class {
11571
11810
  return;
11572
11811
  }
11573
11812
  this.emit("message", msg2);
11574
- if (msg2.event === "response") {
11575
- const resp = msg2.data;
11576
- const key = this.commandKey(resp.action, resp.topic ?? msg2.topic);
11813
+ switch (msg2.channel) {
11814
+ case CHANNEL_SUBSCRIPTION_RESPONSE:
11815
+ this.handleAck(msg2.data);
11816
+ return;
11817
+ case CHANNEL_ERROR:
11818
+ this.handleChannelError(msg2.data);
11819
+ return;
11820
+ case CHANNEL_SUBSCRIPTION_EXPIRED:
11821
+ this.handleExpired(msg2.data);
11822
+ return;
11823
+ default:
11824
+ this.dispatchData(msg2);
11825
+ }
11826
+ }
11827
+ handleChannelError(data) {
11828
+ const err = new WebSocketError(data?.message ?? "WebSocket error");
11829
+ const sub = data?.subscription;
11830
+ if (sub) {
11831
+ const key = topicKey(sub);
11577
11832
  const pending = this.pendingCommands.get(key);
11578
11833
  if (pending) {
11579
11834
  clearTimeout(pending.timer);
11580
11835
  this.pendingCommands.delete(key);
11581
- pending.resolve(resp);
11836
+ pending.reject(err);
11837
+ return;
11582
11838
  }
11583
- return;
11584
- }
11585
- if (msg2.event === "subscription_expired") {
11586
- const sub2 = this.subscriptions.get(msg2.topic);
11587
- if (sub2) {
11588
- this.subscriptions.delete(msg2.topic);
11589
- sub2.handlers.onExpired?.();
11839
+ const active = this.subscriptions.get(key);
11840
+ if (active) {
11841
+ this.subscriptions.delete(key);
11842
+ active.handlers.onError?.(err);
11843
+ return;
11590
11844
  }
11845
+ this.emit("error", err);
11591
11846
  return;
11592
11847
  }
11593
- const sub = this.subscriptions.get(msg2.topic);
11848
+ this.emit("error", err);
11849
+ }
11850
+ // The ack echoes the subscription (type/coin/user/interval) plus the
11851
+ // effective ttl and/or an error. It carries no `method`, so subscribe and
11852
+ // unsubscribe acks are indistinguishable on the wire — only subscribe
11853
+ // registers a pending command, and unsubscribe drops its pending eagerly, so
11854
+ // there is never a collision on the topic key.
11855
+ handleAck(ack) {
11856
+ const key = topicKey({
11857
+ type: ack.type,
11858
+ coin: ack.coin,
11859
+ user: ack.user,
11860
+ interval: ack.interval
11861
+ });
11862
+ const pending = this.pendingCommands.get(key);
11863
+ if (!pending) return;
11864
+ clearTimeout(pending.timer);
11865
+ this.pendingCommands.delete(key);
11866
+ pending.resolve({
11867
+ success: !ack.error,
11868
+ error: ack.error,
11869
+ ttl: ack.ttl,
11870
+ ack
11871
+ });
11872
+ }
11873
+ handleExpired(data) {
11874
+ const key = topicKey(data.subscription);
11875
+ const sub = this.subscriptions.get(key);
11594
11876
  if (sub) {
11595
- try {
11596
- sub.handlers.onData(msg2.data, msg2);
11597
- } catch (err) {
11598
- sub.handlers.onError?.(err instanceof Error ? err : new Error(String(err)));
11599
- }
11877
+ this.subscriptions.delete(key);
11878
+ sub.handlers.onExpired?.();
11879
+ }
11880
+ }
11881
+ dispatchData(msg2) {
11882
+ const mappedType = msg2.channel === "user" ? "userEvents" : msg2.channel;
11883
+ const channelSubs = [...this.subscriptions.values()].filter(
11884
+ (s) => s.subscription.type === mappedType
11885
+ );
11886
+ if (channelSubs.length === 0) return;
11887
+ const isUnattributableEmpty = (mappedType === "trades" || mappedType === "candle") && Array.isArray(msg2.data) && msg2.data.length === 0;
11888
+ if (isUnattributableEmpty) {
11889
+ for (const sub of channelSubs) this.deliver(sub, msg2);
11890
+ return;
11891
+ }
11892
+ for (const sub of channelSubs) {
11893
+ if (!frameMatches(sub.subscription, msg2.data)) continue;
11894
+ this.deliver(sub, msg2);
11895
+ }
11896
+ }
11897
+ deliver(sub, msg2) {
11898
+ try {
11899
+ sub.handlers.onData(msg2.data, msg2);
11900
+ } catch (err) {
11901
+ sub.handlers.onError?.(err instanceof Error ? err : new Error(String(err)));
11600
11902
  }
11601
11903
  }
11602
11904
  send(data) {
11603
- if (this.ws?.readyState === WS_OPEN) {
11905
+ if (this.ws?.readyState === WS_READY_STATE_OPEN) {
11604
11906
  this.ws.send(JSON.stringify(data));
11605
11907
  }
11606
11908
  }
11607
- sendCommand(cmd) {
11909
+ sendSubscribe(sub, ttl) {
11608
11910
  if (this.connectionState !== "connected") {
11609
11911
  return Promise.reject(new WebSocketError("Not connected"));
11610
11912
  }
11611
11913
  return new Promise((resolve, reject) => {
11612
- const action = cmd.action;
11613
- const topic = cmd.topic ?? "";
11614
- const key = this.commandKey(action, topic);
11914
+ const key = topicKey(sub);
11915
+ const existing = this.pendingCommands.get(key);
11916
+ if (existing) {
11917
+ clearTimeout(existing.timer);
11918
+ existing.reject(new WebSocketError("Subscribe superseded by a newer subscribe"));
11919
+ }
11615
11920
  const timer = setTimeout(() => {
11921
+ if (this.pendingCommands.get(key) !== entry) return;
11616
11922
  this.pendingCommands.delete(key);
11617
- reject(new WebSocketError(`Command timed out: ${action}`));
11923
+ reject(new WebSocketError("Command timed out: subscribe"));
11618
11924
  }, COMMAND_TIMEOUT_MS);
11619
- this.pendingCommands.set(key, { resolve, reject, timer });
11620
- this.send(cmd);
11925
+ const entry = { resolve, reject, timer };
11926
+ this.pendingCommands.set(key, entry);
11927
+ this.send({
11928
+ method: "subscribe",
11929
+ subscription: buildSubscriptionPayload(sub, ttl)
11930
+ });
11621
11931
  });
11622
11932
  }
11623
- commandKey(action, topic) {
11624
- return `${action}:${topic}`;
11625
- }
11626
11933
  scheduleReconnect() {
11627
11934
  if (this.reconnectAttempt >= this.options.maxReconnectAttempts) {
11628
11935
  this.connectionState = "disconnected";
@@ -11654,8 +11961,8 @@ var DexWsClient = class {
11654
11961
  }
11655
11962
  resubscribeAll() {
11656
11963
  this.emit("reconnected");
11657
- for (const [topic, sub] of this.subscriptions) {
11658
- this.send({ action: "subscribe", topic, ttl: sub.ttl });
11964
+ for (const sub of [...this.subscriptions.values()]) {
11965
+ this.dispatchSubscribe(sub);
11659
11966
  }
11660
11967
  }
11661
11968
  resolveConnect() {
@@ -11682,9 +11989,9 @@ var DexWsClient = class {
11682
11989
  this.pendingCommands.clear();
11683
11990
  }
11684
11991
  emit(event, ...args) {
11685
- const set = this.listeners.get(event);
11992
+ const set = this.listeners[event];
11686
11993
  if (!set) return;
11687
- for (const fn of set) {
11994
+ for (const fn of [...set]) {
11688
11995
  try {
11689
11996
  fn(...args);
11690
11997
  } catch {
@@ -14158,75 +14465,6 @@ async function resolveEvmFeesPerGas(network, options) {
14158
14465
 
14159
14466
  // src/eip712/signers.ts
14160
14467
  var import_accounts = require("viem/accounts");
14161
-
14162
- // src/utils/address.ts
14163
- var import_encoding = require("@cosmjs/encoding");
14164
- var import_viem2 = require("viem");
14165
- function evmToAult(evmAddress) {
14166
- const hex = evmAddress.toLowerCase().replace("0x", "");
14167
- const bytes = (0, import_encoding.fromHex)(hex);
14168
- return (0, import_encoding.toBech32)("ault", bytes);
14169
- }
14170
- function aultToEvm(aultAddress) {
14171
- const { data } = (0, import_encoding.fromBech32)(aultAddress);
14172
- return (0, import_viem2.getAddress)(`0x${(0, import_encoding.toHex)(data)}`);
14173
- }
14174
- function isValidAultAddress(address) {
14175
- try {
14176
- const { prefix, data } = (0, import_encoding.fromBech32)(address);
14177
- return prefix === "ault" && data.length === 20;
14178
- } catch {
14179
- return false;
14180
- }
14181
- }
14182
- function isValidEvmAddress(address) {
14183
- if (!/^0[xX][a-fA-F0-9]{40}$/.test(address)) return false;
14184
- const normalized = `0x${address.slice(2)}`;
14185
- const body = normalized.slice(2);
14186
- const allLower = body === body.toLowerCase();
14187
- const allUpper = body === body.toUpperCase();
14188
- if (allLower || allUpper) return true;
14189
- return (0, import_viem2.isAddress)(normalized, { strict: true });
14190
- }
14191
- function addressEquals(a, b) {
14192
- const ab = addressBytes(a);
14193
- const bb = addressBytes(b);
14194
- if (!ab || !bb || ab.length !== bb.length) return false;
14195
- for (let i = 0; i < ab.length; i++) {
14196
- if (ab[i] !== bb[i]) return false;
14197
- }
14198
- return true;
14199
- }
14200
- function addressBytes(s) {
14201
- if (!s) return null;
14202
- if (s.startsWith("0x") || s.startsWith("0X")) {
14203
- const body = s.slice(2);
14204
- if (!/^[a-fA-F0-9]+$/.test(body) || body.length !== 40) return null;
14205
- return (0, import_encoding.fromHex)(body.toLowerCase());
14206
- }
14207
- try {
14208
- const { data } = (0, import_encoding.fromBech32)(s);
14209
- return data;
14210
- } catch {
14211
- return null;
14212
- }
14213
- }
14214
- function isValidValidatorAddress(address) {
14215
- try {
14216
- const { prefix, data } = (0, import_encoding.fromBech32)(address);
14217
- return prefix === "aultvaloper" && data.length === 20;
14218
- } catch {
14219
- return false;
14220
- }
14221
- }
14222
- function assertValidatorAddress(address) {
14223
- if (isValidValidatorAddress(address)) {
14224
- return address;
14225
- }
14226
- throw new Error(`Invalid validator address format: ${address}`);
14227
- }
14228
-
14229
- // src/eip712/signers.ts
14230
14468
  var AULT_SIGNER_MARKER = /* @__PURE__ */ Symbol.for("ault-sdk:signer");
14231
14469
  function isAultSigner(obj) {
14232
14470
  return typeof obj === "object" && obj !== null && AULT_SIGNER_MARKER in obj && obj[AULT_SIGNER_MARKER] === true;
@@ -22045,13 +22283,16 @@ function createClobTxApi({ signerAddress, exec, getGas }) {
22045
22283
  },
22046
22284
  async cancelOrders({ orderIds, gasLimit, feeAmount, memo, confirmationTimeoutMs }) {
22047
22285
  const gas = getGas();
22048
- return exec([buildCancelOrdersMsg(signerAddress, orderIds)], {
22049
- gasLimit: gasLimit ?? computeFeeFreeGasCompound(
22286
+ const cancelGas = gasLimit ?? (BigInt(
22287
+ computeFeeFreeGasCompound(
22050
22288
  gas.CANCEL_ORDER_BASE,
22051
22289
  gas.CANCEL_ORDER_PER_ID,
22052
22290
  orderIds.length,
22053
22291
  gas.FEE_FREE_GAS_MULTIPLIER
22054
- ),
22292
+ )
22293
+ ) + BigInt(gas.EIP712_ANTE_GAS)).toString();
22294
+ return exec([buildCancelOrdersMsg(signerAddress, orderIds)], {
22295
+ gasLimit: cancelGas,
22055
22296
  feeAmount,
22056
22297
  memo,
22057
22298
  confirmationTimeoutMs
@@ -22790,9 +23031,10 @@ function createRewardTxApi({ signerAddress, exec, getGas }) {
22790
23031
  }
22791
23032
 
22792
23033
  // src/high-level/tx/staking.ts
22793
- function createStakingTxApi({ signerAddress, exec }) {
23034
+ function createStakingTxApi({ signerAddress, exec, getGas }) {
22794
23035
  return {
22795
23036
  async delegate({ validatorAddress, amount, gasLimit, feeAmount, memo, confirmationTimeoutMs }) {
23037
+ const gas = getGas();
22796
23038
  return exec(
22797
23039
  [
22798
23040
  msg.staking.delegate({
@@ -22801,7 +23043,12 @@ function createStakingTxApi({ signerAddress, exec }) {
22801
23043
  amount
22802
23044
  })
22803
23045
  ],
22804
- { gasLimit, feeAmount, memo, confirmationTimeoutMs }
23046
+ {
23047
+ gasLimit: gasLimit ?? computeFeeFreeGas(gas.DELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
23048
+ feeAmount,
23049
+ memo,
23050
+ confirmationTimeoutMs
23051
+ }
22805
23052
  );
22806
23053
  },
22807
23054
  async undelegate({
@@ -22812,6 +23059,7 @@ function createStakingTxApi({ signerAddress, exec }) {
22812
23059
  memo,
22813
23060
  confirmationTimeoutMs
22814
23061
  }) {
23062
+ const gas = getGas();
22815
23063
  return exec(
22816
23064
  [
22817
23065
  msg.staking.undelegate({
@@ -22820,7 +23068,12 @@ function createStakingTxApi({ signerAddress, exec }) {
22820
23068
  amount
22821
23069
  })
22822
23070
  ],
22823
- { gasLimit, feeAmount, memo, confirmationTimeoutMs }
23071
+ {
23072
+ gasLimit: gasLimit ?? computeFeeFreeGas(gas.UNDELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
23073
+ feeAmount,
23074
+ memo,
23075
+ confirmationTimeoutMs
23076
+ }
22824
23077
  );
22825
23078
  },
22826
23079
  async redelegate({
@@ -22832,6 +23085,7 @@ function createStakingTxApi({ signerAddress, exec }) {
22832
23085
  memo,
22833
23086
  confirmationTimeoutMs
22834
23087
  }) {
23088
+ const gas = getGas();
22835
23089
  return exec(
22836
23090
  [
22837
23091
  msg.staking.beginRedelegate({
@@ -22841,7 +23095,12 @@ function createStakingTxApi({ signerAddress, exec }) {
22841
23095
  amount
22842
23096
  })
22843
23097
  ],
22844
- { gasLimit, feeAmount, memo, confirmationTimeoutMs }
23098
+ {
23099
+ gasLimit: gasLimit ?? computeFeeFreeGas(gas.BEGIN_REDELEGATE, 1, gas.FEE_FREE_GAS_MULTIPLIER),
23100
+ feeAmount,
23101
+ memo,
23102
+ confirmationTimeoutMs
23103
+ }
22845
23104
  );
22846
23105
  },
22847
23106
  async withdrawRewards({
@@ -22855,6 +23114,8 @@ function createStakingTxApi({ signerAddress, exec }) {
22855
23114
  throw new Error("validatorAddresses must include at least one validator address.");
22856
23115
  }
22857
23116
  const normalized = validatorAddresses.map(assertValidatorAddress);
23117
+ const gas = getGas();
23118
+ const resolvedGasLimit = gasLimit ?? computeFeeFreeGas(gas.WITHDRAW_DELEGATOR_REWARD, 1, gas.FEE_FREE_GAS_MULTIPLIER);
22858
23119
  const results = [];
22859
23120
  const partial = [];
22860
23121
  for (let i = 0; i < normalized.length; i++) {
@@ -22867,7 +23128,7 @@ function createStakingTxApi({ signerAddress, exec }) {
22867
23128
  validatorAddress
22868
23129
  })
22869
23130
  ],
22870
- { gasLimit, feeAmount, memo, confirmationTimeoutMs }
23131
+ { gasLimit: resolvedGasLimit, feeAmount, memo, confirmationTimeoutMs }
22871
23132
  );
22872
23133
  results.push(result);
22873
23134
  partial.push({ txHash: result.txHash, validatorAddress });
@@ -23025,7 +23286,11 @@ var ManifestGasSchema = import_zod.z.object({
23025
23286
  SCALE_ORDER_PER_SUB: import_zod.z.number().int().positive(),
23026
23287
  CANCEL_ORDER_BASE: import_zod.z.number().int().positive(),
23027
23288
  CANCEL_ORDER_PER_ID: import_zod.z.number().int().positive(),
23028
- OPEN_ACCOUNT: import_zod.z.number().int().positive()
23289
+ OPEN_ACCOUNT: import_zod.z.number().int().positive(),
23290
+ DELEGATE: import_zod.z.number().int().positive(),
23291
+ UNDELEGATE: import_zod.z.number().int().positive(),
23292
+ BEGIN_REDELEGATE: import_zod.z.number().int().positive(),
23293
+ WITHDRAW_DELEGATOR_REWARD: import_zod.z.number().int().positive()
23029
23294
  }).partial();
23030
23295
  var positiveIntegerString = import_zod.z.string().regex(/^[1-9]\d*$/, "must be a positive integer string (chain-side BigInt, > 0)");
23031
23296
  var nonNegativeIntegerString = import_zod.z.string().regex(/^\d+$/, "must be a non-negative integer string (chain-side BigInt)");
@@ -23118,6 +23383,7 @@ function applyGasOverrides(gas) {
23118
23383
  EIP712_FEE_AMOUNT: _ignoredFee,
23119
23384
  EIP712_GAS_LIMIT: _ignoredGas,
23120
23385
  DENOM: _ignoredDenom,
23386
+ EIP712_ANTE_GAS: _ignoredAnte,
23121
23387
  ...rest
23122
23388
  } = gas;
23123
23389
  const safeRest = {};
@@ -23228,7 +23494,7 @@ function createStaticResolver(optsOrNetwork, legacyManifest) {
23228
23494
  // src/agent/attach.ts
23229
23495
  var import_secp256k12 = require("@noble/curves/secp256k1");
23230
23496
  var import_viem6 = require("viem");
23231
- var import_encoding2 = require("@cosmjs/encoding");
23497
+ var import_encoding3 = require("@cosmjs/encoding");
23232
23498
 
23233
23499
  // src/agent/sign-and-broadcast.ts
23234
23500
  var import_secp256k1 = require("@noble/curves/secp256k1");
@@ -23485,7 +23751,7 @@ function deriveAgentAddress(privateKeyHex) {
23485
23751
  const uncompressedPubkey = import_secp256k12.secp256k1.getPublicKey(privKeyBytes, false);
23486
23752
  const pubkeyHash = (0, import_viem6.hexToBytes)((0, import_viem6.keccak256)(uncompressedPubkey.slice(1)));
23487
23753
  const evmAddressBytes = pubkeyHash.slice(12);
23488
- const evmHex = `0x${(0, import_encoding2.toHex)(evmAddressBytes)}`;
23754
+ const evmHex = `0x${(0, import_encoding3.toHex)(evmAddressBytes)}`;
23489
23755
  return evmToAult(evmHex);
23490
23756
  }
23491
23757
  function buildAgentSurface(options, ctx) {
@@ -24363,7 +24629,7 @@ function createDexWs(url, options) {
24363
24629
  }
24364
24630
 
24365
24631
  // src/index.ts
24366
- var SDK_VERSION = "0.0.2-alpha.18";
24632
+ var SDK_VERSION = "0.0.2-alpha.20";
24367
24633
  // Annotate the CommonJS export names for ESM import in node:
24368
24634
  0 && (module.exports = {
24369
24635
  AGENT_DEFAULTS,
@@ -24454,6 +24720,7 @@ var SDK_VERSION = "0.0.2-alpha.18";
24454
24720
  WebSocketError,
24455
24721
  WithdrawRewardsPartialError,
24456
24722
  _resetIndexingCache,
24723
+ addressBytes,
24457
24724
  addressEquals,
24458
24725
  applyGasOverrides,
24459
24726
  applyNetworkOverrides,