ault-sdk-ts 0.0.2-alpha.19 → 0.0.2-alpha.21

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,
@@ -600,7 +601,7 @@ var NETWORKS = {
600
601
  rpcUrl: "https://mainnet-rpc-proxy.aultblockchain.xyz/cosmos-rpc",
601
602
  restUrl: "https://mainnet-rpc-proxy.aultblockchain.xyz/rest",
602
603
  evmRpcUrl: "https://mainnet-rpc-proxy.aultblockchain.xyz/evm",
603
- explorerUrl: "https://ault.explorer.xangle.io/home",
604
+ explorerUrl: "https://ault.explorer.xangle.io",
604
605
  isProduction: true
605
606
  },
606
607
  "ault_10904-1": {
@@ -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,13 +705,15 @@ 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
718
  OPEN_ACCOUNT: 96e3,
707
719
  // Staking module (cosmos-sdk standard, NOT fee-free — user pays gas).
@@ -11383,30 +11395,165 @@ function createDexApi(context) {
11383
11395
  };
11384
11396
  }
11385
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
+
11386
11465
  // src/ws/client.ts
11466
+ var import_encoding2 = require("@cosmjs/encoding");
11387
11467
  var NORMAL_CLOSURE = 1e3;
11388
- var WS_OPEN = 1;
11468
+ var WS_READY_STATE_OPEN = 1;
11389
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
+ }
11390
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
+ }
11391
11547
  function getDefaultWebSocketFactory() {
11392
- if (typeof globalThis !== "undefined" && typeof globalThis.WebSocket === "function") {
11393
- return (url, protocols) => {
11394
- const Ctor = globalThis.WebSocket;
11395
- return protocols === void 0 ? new Ctor(url) : new Ctor(url, protocols);
11396
- };
11397
- }
11548
+ const G = currentGlobalCtor();
11549
+ if (G) return wrapCtor(G);
11398
11550
  if (!isowsModulePromise) {
11399
11551
  isowsModulePromise = import("isows");
11400
11552
  }
11401
11553
  return isowsModulePromise.then((mod) => {
11402
- if (typeof globalThis !== "undefined" && typeof globalThis.WebSocket === "function") {
11403
- return (url, protocols) => {
11404
- const Ctor2 = globalThis.WebSocket;
11405
- return protocols === void 0 ? new Ctor2(url) : new Ctor2(url, protocols);
11406
- };
11407
- }
11408
- const Ctor = mod.WebSocket;
11409
- 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);
11410
11557
  });
11411
11558
  }
11412
11559
  var DexWsClient = class {
@@ -11414,7 +11561,12 @@ var DexWsClient = class {
11414
11561
  this.ws = null;
11415
11562
  this.connectionState = "disconnected";
11416
11563
  this.subscriptions = /* @__PURE__ */ new Map();
11417
- 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 = {};
11418
11570
  this.pendingCommands = /* @__PURE__ */ new Map();
11419
11571
  this.reconnectAttempt = 0;
11420
11572
  this.reconnectTimer = null;
@@ -11465,39 +11617,121 @@ var DexWsClient = class {
11465
11617
  this.rejectConnect(err);
11466
11618
  this.rejectPendingCommands(err);
11467
11619
  }
11468
- 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);
11469
11628
  const ttl = options?.ttl;
11470
- this.subscriptions.set(topic, { handlers, ttl });
11471
- 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(
11472
11651
  (resp) => {
11473
11652
  if (resp.success) {
11474
- handlers.onSubscribed?.();
11653
+ handlers.onSubscribed?.(resp.ack);
11475
11654
  } else {
11476
- this.subscriptions.delete(topic);
11655
+ deleteIfOwned();
11477
11656
  handlers.onError?.(new WebSocketError(resp.error ?? "Subscribe failed"));
11478
11657
  }
11479
11658
  },
11480
11659
  (err) => {
11481
- this.subscriptions.delete(topic);
11660
+ deleteIfOwned();
11482
11661
  handlers.onError?.(err);
11483
11662
  }
11484
11663
  );
11485
- return {
11486
- topic,
11487
- 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"
11488
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
+ }
11489
11714
  }
11490
- unsubscribe(topic) {
11491
- 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
+ }
11492
11723
  if (this.connectionState === "connected") {
11493
- this.send({ action: "unsubscribe", topic });
11724
+ this.send({
11725
+ method: "unsubscribe",
11726
+ subscription: buildSubscriptionPayload(subscription)
11727
+ });
11494
11728
  }
11495
11729
  }
11496
11730
  on(event, handler) {
11497
- let set = this.listeners.get(event);
11731
+ let set = this.listeners[event];
11498
11732
  if (!set) {
11499
11733
  set = /* @__PURE__ */ new Set();
11500
- this.listeners.set(event, set);
11734
+ this.listeners[event] = set;
11501
11735
  }
11502
11736
  set.add(handler);
11503
11737
  return () => set.delete(handler);
@@ -11576,58 +11810,126 @@ var DexWsClient = class {
11576
11810
  return;
11577
11811
  }
11578
11812
  this.emit("message", msg2);
11579
- if (msg2.event === "response") {
11580
- const resp = msg2.data;
11581
- 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);
11582
11832
  const pending = this.pendingCommands.get(key);
11583
11833
  if (pending) {
11584
11834
  clearTimeout(pending.timer);
11585
11835
  this.pendingCommands.delete(key);
11586
- pending.resolve(resp);
11836
+ pending.reject(err);
11837
+ return;
11587
11838
  }
11588
- return;
11589
- }
11590
- if (msg2.event === "subscription_expired") {
11591
- const sub2 = this.subscriptions.get(msg2.topic);
11592
- if (sub2) {
11593
- this.subscriptions.delete(msg2.topic);
11594
- 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;
11595
11844
  }
11845
+ this.emit("error", err);
11596
11846
  return;
11597
11847
  }
11598
- 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);
11599
11876
  if (sub) {
11600
- try {
11601
- sub.handlers.onData(msg2.data, msg2);
11602
- } catch (err) {
11603
- sub.handlers.onError?.(err instanceof Error ? err : new Error(String(err)));
11604
- }
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)));
11605
11902
  }
11606
11903
  }
11607
11904
  send(data) {
11608
- if (this.ws?.readyState === WS_OPEN) {
11905
+ if (this.ws?.readyState === WS_READY_STATE_OPEN) {
11609
11906
  this.ws.send(JSON.stringify(data));
11610
11907
  }
11611
11908
  }
11612
- sendCommand(cmd) {
11909
+ sendSubscribe(sub, ttl) {
11613
11910
  if (this.connectionState !== "connected") {
11614
11911
  return Promise.reject(new WebSocketError("Not connected"));
11615
11912
  }
11616
11913
  return new Promise((resolve, reject) => {
11617
- const action = cmd.action;
11618
- const topic = cmd.topic ?? "";
11619
- 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
+ }
11620
11920
  const timer = setTimeout(() => {
11921
+ if (this.pendingCommands.get(key) !== entry) return;
11621
11922
  this.pendingCommands.delete(key);
11622
- reject(new WebSocketError(`Command timed out: ${action}`));
11923
+ reject(new WebSocketError("Command timed out: subscribe"));
11623
11924
  }, COMMAND_TIMEOUT_MS);
11624
- this.pendingCommands.set(key, { resolve, reject, timer });
11625
- 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
+ });
11626
11931
  });
11627
11932
  }
11628
- commandKey(action, topic) {
11629
- return `${action}:${topic}`;
11630
- }
11631
11933
  scheduleReconnect() {
11632
11934
  if (this.reconnectAttempt >= this.options.maxReconnectAttempts) {
11633
11935
  this.connectionState = "disconnected";
@@ -11659,8 +11961,8 @@ var DexWsClient = class {
11659
11961
  }
11660
11962
  resubscribeAll() {
11661
11963
  this.emit("reconnected");
11662
- for (const [topic, sub] of this.subscriptions) {
11663
- this.send({ action: "subscribe", topic, ttl: sub.ttl });
11964
+ for (const sub of [...this.subscriptions.values()]) {
11965
+ this.dispatchSubscribe(sub);
11664
11966
  }
11665
11967
  }
11666
11968
  resolveConnect() {
@@ -11687,9 +11989,9 @@ var DexWsClient = class {
11687
11989
  this.pendingCommands.clear();
11688
11990
  }
11689
11991
  emit(event, ...args) {
11690
- const set = this.listeners.get(event);
11992
+ const set = this.listeners[event];
11691
11993
  if (!set) return;
11692
- for (const fn of set) {
11994
+ for (const fn of [...set]) {
11693
11995
  try {
11694
11996
  fn(...args);
11695
11997
  } catch {
@@ -14163,75 +14465,6 @@ async function resolveEvmFeesPerGas(network, options) {
14163
14465
 
14164
14466
  // src/eip712/signers.ts
14165
14467
  var import_accounts = require("viem/accounts");
14166
-
14167
- // src/utils/address.ts
14168
- var import_encoding = require("@cosmjs/encoding");
14169
- var import_viem2 = require("viem");
14170
- function evmToAult(evmAddress) {
14171
- const hex = evmAddress.toLowerCase().replace("0x", "");
14172
- const bytes = (0, import_encoding.fromHex)(hex);
14173
- return (0, import_encoding.toBech32)("ault", bytes);
14174
- }
14175
- function aultToEvm(aultAddress) {
14176
- const { data } = (0, import_encoding.fromBech32)(aultAddress);
14177
- return (0, import_viem2.getAddress)(`0x${(0, import_encoding.toHex)(data)}`);
14178
- }
14179
- function isValidAultAddress(address) {
14180
- try {
14181
- const { prefix, data } = (0, import_encoding.fromBech32)(address);
14182
- return prefix === "ault" && data.length === 20;
14183
- } catch {
14184
- return false;
14185
- }
14186
- }
14187
- function isValidEvmAddress(address) {
14188
- if (!/^0[xX][a-fA-F0-9]{40}$/.test(address)) return false;
14189
- const normalized = `0x${address.slice(2)}`;
14190
- const body = normalized.slice(2);
14191
- const allLower = body === body.toLowerCase();
14192
- const allUpper = body === body.toUpperCase();
14193
- if (allLower || allUpper) return true;
14194
- return (0, import_viem2.isAddress)(normalized, { strict: true });
14195
- }
14196
- function addressEquals(a, b) {
14197
- const ab = addressBytes(a);
14198
- const bb = addressBytes(b);
14199
- if (!ab || !bb || ab.length !== bb.length) return false;
14200
- for (let i = 0; i < ab.length; i++) {
14201
- if (ab[i] !== bb[i]) return false;
14202
- }
14203
- return true;
14204
- }
14205
- function addressBytes(s) {
14206
- if (!s) return null;
14207
- if (s.startsWith("0x") || s.startsWith("0X")) {
14208
- const body = s.slice(2);
14209
- if (!/^[a-fA-F0-9]+$/.test(body) || body.length !== 40) return null;
14210
- return (0, import_encoding.fromHex)(body.toLowerCase());
14211
- }
14212
- try {
14213
- const { data } = (0, import_encoding.fromBech32)(s);
14214
- return data;
14215
- } catch {
14216
- return null;
14217
- }
14218
- }
14219
- function isValidValidatorAddress(address) {
14220
- try {
14221
- const { prefix, data } = (0, import_encoding.fromBech32)(address);
14222
- return prefix === "aultvaloper" && data.length === 20;
14223
- } catch {
14224
- return false;
14225
- }
14226
- }
14227
- function assertValidatorAddress(address) {
14228
- if (isValidValidatorAddress(address)) {
14229
- return address;
14230
- }
14231
- throw new Error(`Invalid validator address format: ${address}`);
14232
- }
14233
-
14234
- // src/eip712/signers.ts
14235
14468
  var AULT_SIGNER_MARKER = /* @__PURE__ */ Symbol.for("ault-sdk:signer");
14236
14469
  function isAultSigner(obj) {
14237
14470
  return typeof obj === "object" && obj !== null && AULT_SIGNER_MARKER in obj && obj[AULT_SIGNER_MARKER] === true;
@@ -22050,13 +22283,16 @@ function createClobTxApi({ signerAddress, exec, getGas }) {
22050
22283
  },
22051
22284
  async cancelOrders({ orderIds, gasLimit, feeAmount, memo, confirmationTimeoutMs }) {
22052
22285
  const gas = getGas();
22053
- return exec([buildCancelOrdersMsg(signerAddress, orderIds)], {
22054
- gasLimit: gasLimit ?? computeFeeFreeGasCompound(
22286
+ const cancelGas = gasLimit ?? (BigInt(
22287
+ computeFeeFreeGasCompound(
22055
22288
  gas.CANCEL_ORDER_BASE,
22056
22289
  gas.CANCEL_ORDER_PER_ID,
22057
22290
  orderIds.length,
22058
22291
  gas.FEE_FREE_GAS_MULTIPLIER
22059
- ),
22292
+ )
22293
+ ) + BigInt(gas.EIP712_ANTE_GAS)).toString();
22294
+ return exec([buildCancelOrdersMsg(signerAddress, orderIds)], {
22295
+ gasLimit: cancelGas,
22060
22296
  feeAmount,
22061
22297
  memo,
22062
22298
  confirmationTimeoutMs
@@ -23147,6 +23383,7 @@ function applyGasOverrides(gas) {
23147
23383
  EIP712_FEE_AMOUNT: _ignoredFee,
23148
23384
  EIP712_GAS_LIMIT: _ignoredGas,
23149
23385
  DENOM: _ignoredDenom,
23386
+ EIP712_ANTE_GAS: _ignoredAnte,
23150
23387
  ...rest
23151
23388
  } = gas;
23152
23389
  const safeRest = {};
@@ -23257,7 +23494,7 @@ function createStaticResolver(optsOrNetwork, legacyManifest) {
23257
23494
  // src/agent/attach.ts
23258
23495
  var import_secp256k12 = require("@noble/curves/secp256k1");
23259
23496
  var import_viem6 = require("viem");
23260
- var import_encoding2 = require("@cosmjs/encoding");
23497
+ var import_encoding3 = require("@cosmjs/encoding");
23261
23498
 
23262
23499
  // src/agent/sign-and-broadcast.ts
23263
23500
  var import_secp256k1 = require("@noble/curves/secp256k1");
@@ -23514,7 +23751,7 @@ function deriveAgentAddress(privateKeyHex) {
23514
23751
  const uncompressedPubkey = import_secp256k12.secp256k1.getPublicKey(privKeyBytes, false);
23515
23752
  const pubkeyHash = (0, import_viem6.hexToBytes)((0, import_viem6.keccak256)(uncompressedPubkey.slice(1)));
23516
23753
  const evmAddressBytes = pubkeyHash.slice(12);
23517
- const evmHex = `0x${(0, import_encoding2.toHex)(evmAddressBytes)}`;
23754
+ const evmHex = `0x${(0, import_encoding3.toHex)(evmAddressBytes)}`;
23518
23755
  return evmToAult(evmHex);
23519
23756
  }
23520
23757
  function buildAgentSurface(options, ctx) {
@@ -24392,7 +24629,7 @@ function createDexWs(url, options) {
24392
24629
  }
24393
24630
 
24394
24631
  // src/index.ts
24395
- var SDK_VERSION = "0.0.2-alpha.19";
24632
+ var SDK_VERSION = "0.0.2-alpha.21";
24396
24633
  // Annotate the CommonJS export names for ESM import in node:
24397
24634
  0 && (module.exports = {
24398
24635
  AGENT_DEFAULTS,
@@ -24483,6 +24720,7 @@ var SDK_VERSION = "0.0.2-alpha.19";
24483
24720
  WebSocketError,
24484
24721
  WithdrawRewardsPartialError,
24485
24722
  _resetIndexingCache,
24723
+ addressBytes,
24486
24724
  addressEquals,
24487
24725
  applyGasOverrides,
24488
24726
  applyNetworkOverrides,