@hyperbridge/sdk 2.8.0 → 2.8.3

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.
@@ -7,7 +7,7 @@ import { baseSepolia, optimismSepolia, arbitrumSepolia, soneium, gnosis, optimis
7
7
  import { TronWeb } from 'tronweb';
8
8
  import { flatten, zip, capitalize, maxBy, isNil } from 'lodash-es';
9
9
  import { match } from 'ts-pattern';
10
- import { WsProvider, ApiPromise, Keyring } from '@polkadot/api';
10
+ import { WsProvider, ApiPromise, HttpProvider, Keyring } from '@polkadot/api';
11
11
  import { Struct, Vector, u8, Bytes, Enum, Tuple, _void, u64, u32, Option, bool, u128 } from 'scale-ts';
12
12
  import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a, blake2AsU8a } from '@polkadot/util-crypto';
13
13
  import { hexToU8a, u8aToHex, u8aConcat, stringToU8a, isHex as isHex$1, u8aToString } from '@polkadot/util';
@@ -2688,13 +2688,26 @@ var chainConfigs = {
2688
2688
  tokenDecimals: {
2689
2689
  USDC: 6,
2690
2690
  USDT: 6,
2691
- cNGN: 6
2691
+ cNGN: 6,
2692
+ ZARP: 18,
2693
+ EURC: 6,
2694
+ XSGD: 6,
2695
+ TRYB: 6,
2696
+ USDR: 6
2692
2697
  },
2693
2698
  tokenStorageSlots: {
2694
2699
  USDT: { balanceSlot: 2, allowanceSlot: 5 },
2695
2700
  USDC: { balanceSlot: 9, allowanceSlot: 10 },
2696
2701
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2697
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2702
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2703
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 },
2704
+ // custom upgradeable layout
2705
+ ZARP: { balanceSlot: 51, allowanceSlot: 52 },
2706
+ EURC: { balanceSlot: 9, allowanceSlot: 10 },
2707
+ // Circle FiatToken layout
2708
+ XSGD: { balanceSlot: 7, allowanceSlot: 8 },
2709
+ TRYB: { balanceSlot: 9, allowanceSlot: 10 },
2710
+ USDR: { balanceSlot: 51, allowanceSlot: 52 }
2698
2711
  },
2699
2712
  addresses: {
2700
2713
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -2743,18 +2756,25 @@ var chainConfigs = {
2743
2756
  DAI: "0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3",
2744
2757
  USDC: "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d",
2745
2758
  USDT: "0x55d398326f99059ff775485246999027b3197955",
2746
- EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209"
2759
+ EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209",
2760
+ cNGN: "0xa8AEA66B361a8d53e8865c62D142167Af28Af058"
2747
2761
  },
2748
2762
  tokenDecimals: {
2749
2763
  USDC: 18,
2750
2764
  USDT: 18,
2765
+ // 6, not 18 — cNGN keeps the same decimals it has on every other chain, unlike the
2766
+ // Binance-pegged stables above. Every phantom standard_amount and pool rate divides
2767
+ // by this, so the divergence from its neighbours here is load-bearing, not a typo.
2768
+ cNGN: 6,
2751
2769
  EXT: 18
2752
2770
  },
2753
2771
  tokenStorageSlots: {
2754
2772
  USDT: { balanceSlot: 1, allowanceSlot: 2 },
2755
2773
  USDC: { balanceSlot: 1, allowanceSlot: 2 },
2756
2774
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2757
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2775
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2776
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 }
2777
+ // custom upgradeable layout, as on Base
2758
2778
  },
2759
2779
  addresses: {
2760
2780
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -2874,13 +2894,22 @@ var chainConfigs = {
2874
2894
  USDC: 6,
2875
2895
  USDT: 6,
2876
2896
  cNGN: 6,
2877
- EXT: 18
2897
+ EXT: 18,
2898
+ ZARP: 18,
2899
+ EURC: 6,
2900
+ USDR: 6
2878
2901
  },
2879
2902
  tokenStorageSlots: {
2880
2903
  USDT: { balanceSlot: 0, allowanceSlot: 1 },
2881
2904
  USDC: { balanceSlot: 9, allowanceSlot: 10 },
2882
2905
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2883
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2906
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2907
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 },
2908
+ // custom upgradeable layout
2909
+ ZARP: { balanceSlot: 51, allowanceSlot: 52 },
2910
+ EURC: { balanceSlot: 9, allowanceSlot: 10 },
2911
+ // Circle FiatToken layout
2912
+ USDR: { balanceSlot: 51, allowanceSlot: 52 }
2884
2913
  },
2885
2914
  addresses: {
2886
2915
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -2941,13 +2970,21 @@ var chainConfigs = {
2941
2970
  USDC: 6,
2942
2971
  USDT: 6,
2943
2972
  EXT: 18,
2944
- cNGN: 6
2973
+ cNGN: 6,
2974
+ ZARP: 18,
2975
+ XSGD: 6,
2976
+ USDR: 6
2945
2977
  },
2946
2978
  tokenStorageSlots: {
2947
2979
  USDT: { balanceSlot: 0, allowanceSlot: 1 },
2948
2980
  USDC: { balanceSlot: 9, allowanceSlot: 10 },
2949
2981
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2950
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2982
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2983
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 },
2984
+ // custom upgradeable layout
2985
+ ZARP: { balanceSlot: 51, allowanceSlot: 52 },
2986
+ XSGD: { balanceSlot: 7, allowanceSlot: 8 },
2987
+ USDR: { balanceSlot: 51, allowanceSlot: 52 }
2951
2988
  },
2952
2989
  addresses: {
2953
2990
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -3248,8 +3285,9 @@ var chainConfigs = {
3248
3285
  assets: {
3249
3286
  WETH: "0x0000000000000000000000000000000000000000",
3250
3287
  DAI: "0x0000000000000000000000000000000000000000",
3288
+ // Asset Hub assets at their asset-id precompile addresses: 0x539 = 1337, 0x7c0 = 1984.
3251
3289
  USDC: "0x0000053900000000000000000000000001200000",
3252
- USDT: "0x0000000000000000000000000000000000000000"
3290
+ USDT: "0x000007c000000000000000000000000001200000"
3253
3291
  },
3254
3292
  tokenDecimals: {
3255
3293
  USDC: 6,
@@ -7768,6 +7806,27 @@ function encodeISMPMessage(message) {
7768
7806
  }
7769
7807
  var OFFCHAIN_BID_PREFIX = new TextEncoder().encode("intents::bid::");
7770
7808
  var OFFCHAIN_PHANTOM_PREFIX = new TextEncoder().encode("intents::phantom::order::");
7809
+ var HYPERBRIDGE_TYPES_BUNDLE = {
7810
+ spec: {
7811
+ nexus: { hasher: keccakAsU8a },
7812
+ gargantua: { hasher: keccakAsU8a }
7813
+ }
7814
+ };
7815
+ var BASE_TIP = 1000000000n;
7816
+ var HTTP_CONNECT_TIMEOUT_MS = 2e4;
7817
+ var PHANTOM_POLL_INTERVAL_MS = 15e3;
7818
+ var GARGANTUA_PHANTOM_POLL_INTERVAL_MS = 6e3;
7819
+ function rejectAfter(ms, message) {
7820
+ return new Promise((_resolve, reject) => {
7821
+ const timer = setTimeout(() => reject(new Error(message)), ms);
7822
+ timer.unref?.();
7823
+ });
7824
+ }
7825
+ function deriveHttpUrl(wsUrl) {
7826
+ if (wsUrl.startsWith("wss://")) return `https://${wsUrl.slice("wss://".length)}`;
7827
+ if (wsUrl.startsWith("ws://")) return `http://${wsUrl.slice("ws://".length)}`;
7828
+ throw new Error(`Cannot derive an HTTP endpoint from a non-websocket url: ${wsUrl}`);
7829
+ }
7771
7830
  var BidCodec = Struct({ filler: Bytes(32), user_op: Vector(u8) });
7772
7831
  var PackedUserOperationCodec = Struct({
7773
7832
  sender: Bytes(20),
@@ -7828,6 +7887,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7828
7887
  ownsConnection;
7829
7888
  /** Cached result of whether the node exposes intents_* RPC methods */
7830
7889
  hasIntentsRpc = null;
7890
+ /** The HTTP-backed api, connected on first use. Cleared after a failed attempt so it retries. */
7891
+ httpApi = null;
7831
7892
  // Serialises every extrinsic submission on this instance's substrate account. All submit/retract
7832
7893
  // methods funnel through signAndSendExtrinsic, each using the API's auto-nonce; fired in parallel
7833
7894
  // (bids for orders on different chains, or several phantom orders in one interval) they would grab
@@ -7844,12 +7905,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7844
7905
  static async connect(wsUrl, substratePrivateKey) {
7845
7906
  const api = await ApiPromise.create({
7846
7907
  provider: new WsProvider(wsUrl),
7847
- typesBundle: {
7848
- spec: {
7849
- nexus: { hasher: keccakAsU8a },
7850
- gargantua: { hasher: keccakAsU8a }
7851
- }
7852
- }
7908
+ typesBundle: HYPERBRIDGE_TYPES_BUNDLE
7853
7909
  });
7854
7910
  return new _IntentsCoprocessor(api, substratePrivateKey, true);
7855
7911
  }
@@ -7875,15 +7931,85 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7875
7931
  static fromApi(api, substratePrivateKey) {
7876
7932
  return new _IntentsCoprocessor(api, substratePrivateKey, false);
7877
7933
  }
7934
+ /**
7935
+ * The API every RPC query runs on: HTTP, connected to the same node as the websocket. Exposed so
7936
+ * callers query through this connection rather than opening one of their own.
7937
+ *
7938
+ * The split is by what each transport is for. Queries are one-shot request/response, which HTTP
7939
+ * serves without holding any state that can silently rot between calls. The websocket earns its
7940
+ * keep only where subscriptions do — watching a submitted extrinsic to inclusion.
7941
+ */
7942
+ async queryApi() {
7943
+ return await this.http();
7944
+ }
7945
+ /**
7946
+ * The websocket API, exposed so callers share this one connection instead of opening a second
7947
+ * socket to the same node. Only needed for subscriptions; use {@link queryApi} to read.
7948
+ */
7949
+ get apiConnection() {
7950
+ return this.api;
7951
+ }
7878
7952
  /**
7879
7953
  * Disconnects the underlying API connection if this instance owns it.
7880
- * Only disconnects if created via `connect()`, not when using shared connections.
7954
+ * Only disconnects the websocket if created via `connect()`, not when using shared connections.
7955
+ * The HTTP api is always created here, so it is always ours to close.
7881
7956
  */
7882
7957
  async disconnect() {
7958
+ const http4 = this.httpApi;
7959
+ this.httpApi = null;
7960
+ if (http4) {
7961
+ await http4.then((api) => api.disconnect()).catch(() => {
7962
+ });
7963
+ }
7883
7964
  if (this.ownsConnection) {
7884
7965
  await this.api.disconnect();
7885
7966
  }
7886
7967
  }
7968
+ /**
7969
+ * The HTTP api for this node, connected on first use. Every coprocessor has one — the endpoint
7970
+ * is derived from the websocket's own endpoint, so there is nothing to configure and nothing to
7971
+ * be absent.
7972
+ *
7973
+ * The connection attempt is bounded on both sides. `isReadyOrError` rejects on a failed
7974
+ * handshake, where plain `isReady` would simply never resolve, and the timeout covers an
7975
+ * endpoint that accepts the request and then goes quiet. An unbounded wait here would hang the
7976
+ * poll tick awaiting it, which is precisely the silent stall that polling exists to avoid. A
7977
+ * failed attempt is not cached, so the next call tries again.
7978
+ */
7979
+ async http() {
7980
+ if (!this.httpApi) {
7981
+ const httpUrl = deriveHttpUrl(this.wsEndpoint());
7982
+ const api = new ApiPromise({
7983
+ provider: new HttpProvider(httpUrl),
7984
+ typesBundle: HYPERBRIDGE_TYPES_BUNDLE,
7985
+ // A second connection to the node the ws api already reported on; its init warnings
7986
+ // would just be duplicates.
7987
+ noInitWarn: true
7988
+ });
7989
+ this.httpApi = Promise.race([
7990
+ api.isReadyOrError,
7991
+ rejectAfter(HTTP_CONNECT_TIMEOUT_MS, `HTTP RPC ${httpUrl} did not become ready`)
7992
+ ]).catch(async (err) => {
7993
+ await api.disconnect().catch(() => {
7994
+ });
7995
+ this.httpApi = null;
7996
+ throw new Error(`HTTP RPC ${httpUrl} is unavailable: ${err instanceof Error ? err.message : err}`);
7997
+ });
7998
+ }
7999
+ return await this.httpApi;
8000
+ }
8001
+ /**
8002
+ * The endpoint the websocket provider is connected to. Read from the provider rather than
8003
+ * remembered from a constructor argument, so it is the one endpoint in use no matter which
8004
+ * factory built this instance.
8005
+ */
8006
+ wsEndpoint() {
8007
+ const endpoint = this.api._rpcCore?.provider?.endpoint;
8008
+ if (!endpoint) {
8009
+ throw new Error("Cannot determine the Hyperbridge websocket endpoint to derive an HTTP endpoint from");
8010
+ }
8011
+ return endpoint;
8012
+ }
7887
8013
  /**
7888
8014
  * Creates a Substrate keypair from the configured private key.
7889
8015
  * Supports hex seed (with or without 0x), mnemonic phrases, and URI derivation paths (//Alice).
@@ -7906,26 +8032,67 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7906
8032
  /**
7907
8033
  * Signs and sends an extrinsic. Submissions are serialised through {@link submissionQueue} so
7908
8034
  * concurrent calls never collide on the substrate account nonce — each extrinsic reaches a block
7909
- * before the next is signed.
8035
+ * (or is confirmed still pooled and returned as `pending`) before the next is signed; auto-nonce
8036
+ * via `system.accountNextIndex` counts pooled extrinsics, so a pending one is never re-used.
8037
+ *
8038
+ * The extrinsic is built rather than passed in because the api it is built on decides where it
8039
+ * is signed and sent: a websocket that is down when the queue reaches this submission diverts it
8040
+ * to {@link sendViaHttp}, which needs the call bound to the HTTP api instead.
7910
8041
  */
7911
- async signAndSendExtrinsic(extrinsic, maxRetries = 3, timeoutMs = 3e4) {
7912
- const result = await this.submissionQueue.add(() => this.sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs));
8042
+ async signAndSendExtrinsic(build, maxRetries = 3, timeoutMs = 3e4) {
8043
+ const result = await this.submissionQueue.add(async () => {
8044
+ if (!this.api.isConnected) {
8045
+ try {
8046
+ return await this.sendViaHttp(await this.http(), build);
8047
+ } catch (err) {
8048
+ return { success: false, error: err instanceof Error ? err.message : String(err) };
8049
+ }
8050
+ }
8051
+ return await this.sendExtrinsicWithRetries(build(this.api), maxRetries, timeoutMs);
8052
+ });
7913
8053
  return result ?? { success: false, error: "Submission queue returned no result" };
7914
8054
  }
8055
+ /**
8056
+ * Last-resort submission for when the websocket is down at signing time. A bid is only worth
8057
+ * anything inside its window, so waiting for a reconnect usually means not bidding at all.
8058
+ *
8059
+ * HTTP has no subscriptions, so this is `author_submitExtrinsic`: the node accepts the extrinsic
8060
+ * into its pool and returns its hash, and nothing further is observable from here. That is
8061
+ * exactly the `pending` contract — in flight, outcome unknown, do not re-sign — so the result
8062
+ * says so rather than claiming a success it cannot see.
8063
+ *
8064
+ * Only reached when the socket was already down before signing. A submission that got as far as
8065
+ * the pool over the websocket is never retried here: that is the duplicate-nonce race the
8066
+ * `pending` result exists to prevent.
8067
+ */
8068
+ async sendViaHttp(api, build) {
8069
+ try {
8070
+ const hash = await build(api).signAndSend(this.getKeyPair(), { tip: BASE_TIP });
8071
+ return { success: false, pending: true, extrinsicHash: hash.toHex() };
8072
+ } catch (err) {
8073
+ return this.classifySubmissionError(err instanceof Error ? err : new Error(String(err)));
8074
+ }
8075
+ }
7915
8076
  /**
7916
8077
  * Signs and sends an extrinsic, handling status updates and errors.
7917
8078
  * Implements retry logic with progressive tip increases for stuck transactions.
8079
+ *
8080
+ * A retry only happens when the previous attempt verifiably went nowhere. Once an attempt's
8081
+ * extrinsic is known to be pooled (`pending`), re-signing the same call would race our own
8082
+ * submission: the copy either bounces off the pool (1014, same nonce below the replacement
8083
+ * priority bump) or — if the original lands first, freeing the nonce — executes as a duplicate
8084
+ * and fails on-chain (e.g. `BidNotFound` for a retraction). Neither can succeed, so the pending
8085
+ * result is returned for the caller to confirm later.
7918
8086
  */
7919
8087
  async sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs) {
7920
8088
  const keyPair = this.getKeyPair();
7921
- const baseTip = 1000000000n;
7922
8089
  let attempt = 0;
7923
8090
  while (attempt < maxRetries) {
7924
- const currentTip = baseTip * BigInt(2 ** attempt);
8091
+ const currentTip = BASE_TIP * BigInt(2 ** attempt);
7925
8092
  attempt++;
7926
8093
  try {
7927
8094
  const result = await this.sendWithTimeout(extrinsic, keyPair, currentTip, timeoutMs);
7928
- if (result.success || result.error?.includes("Dispatch error")) {
8095
+ if (result.success || result.pending || result.error?.includes("Dispatch error")) {
7929
8096
  return result;
7930
8097
  }
7931
8098
  } catch (err) {
@@ -7941,12 +8108,30 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7941
8108
  };
7942
8109
  }
7943
8110
  /**
7944
- * Sends an extrinsic with a timeout
8111
+ * Classifies a submission rejection. Codes 1013 ("already imported") and 1014 ("priority is
8112
+ * too low") both mean a copy of this account+nonce is already in the pool — almost always our
8113
+ * own earlier attempt whose watch handle didn't confirm cleanly. That extrinsic is in flight;
8114
+ * resubmitting can only bounce again or land a duplicate, so these are surfaced as `pending`
8115
+ * rather than failure.
8116
+ */
8117
+ classifySubmissionError(err) {
8118
+ const code = err.code;
8119
+ const inFlight = code === 1013 || code === 1014 || /already imported|already in the pool|priority is too low/i.test(err.message);
8120
+ return { success: false, pending: inFlight || void 0, error: err.message };
8121
+ }
8122
+ /**
8123
+ * Sends an extrinsic with a timeout.
8124
+ *
8125
+ * A timeout is only a failure when the extrinsic never made it into the transaction pool.
8126
+ * Once a pool-entry status (Future/Ready/Broadcast/Retracted) has been seen, the extrinsic is
8127
+ * in flight and may well execute after the watch is abandoned — the result is then `pending`,
8128
+ * telling the caller to confirm the outcome later instead of re-signing the same call.
7945
8129
  */
7946
8130
  async sendWithTimeout(extrinsic, keyPair, tip, timeoutMs) {
7947
8131
  return new Promise((resolve) => {
7948
8132
  let resolved = false;
7949
8133
  let unsubscribe = null;
8134
+ let enteredPool = false;
7950
8135
  const timeoutId = setTimeout(() => {
7951
8136
  if (!resolved) {
7952
8137
  resolved = true;
@@ -7955,25 +8140,23 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7955
8140
  }
7956
8141
  resolve({
7957
8142
  success: false,
7958
- error: `Transaction timed out after ${timeoutMs}ms`
8143
+ pending: enteredPool || void 0,
8144
+ extrinsicHash: enteredPool ? extrinsic.hash.toHex() : void 0,
8145
+ error: `Transaction timed out after ${timeoutMs}ms${enteredPool ? " while in the transaction pool" : ""}`
7959
8146
  });
7960
8147
  }
7961
8148
  }, timeoutMs);
7962
8149
  extrinsic.signAndSend(keyPair, { tip }, (result) => {
7963
8150
  if (resolved) return;
8151
+ if (result.status.isFuture || result.status.isReady || result.status.isBroadcast || result.status.isRetracted) {
8152
+ enteredPool = true;
8153
+ }
7964
8154
  if (result.dispatchError && (result.status.isInBlock || result.status.isFinalized)) {
7965
8155
  resolved = true;
7966
8156
  clearTimeout(timeoutId);
7967
- let errorMsg;
7968
- if (result.dispatchError.isModule) {
7969
- const decoded = this.api.registry.findMetaError(result.dispatchError.asModule);
7970
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
7971
- } else {
7972
- errorMsg = `Dispatch error: ${result.dispatchError.toString()}`;
7973
- }
7974
8157
  resolve({
7975
8158
  success: false,
7976
- error: errorMsg
8159
+ error: `Dispatch error: ${this.describeDispatchError(result.dispatchError)}`
7977
8160
  });
7978
8161
  } else if (result.status.isDropped || result.status.isInvalid || result.status.isUsurped || result.status.isFinalityTimeout) {
7979
8162
  resolved = true;
@@ -7991,21 +8174,19 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7991
8174
  if (interrupted) {
7992
8175
  const [indexCodec, dispatchError] = interrupted.event.data;
7993
8176
  if (Number(indexCodec.toString()) === 0) {
7994
- let errorMsg;
7995
- if (dispatchError?.isModule) {
7996
- const decoded = this.api.registry.findMetaError(dispatchError.asModule);
7997
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
7998
- } else {
7999
- errorMsg = `Dispatch error: batch interrupted (${dispatchError?.toString()})`;
8000
- }
8001
- resolve({ success: false, error: errorMsg });
8177
+ resolve({
8178
+ success: false,
8179
+ error: `Dispatch error: ${this.describeDispatchError(dispatchError)}`
8180
+ });
8002
8181
  return;
8003
8182
  }
8004
8183
  }
8005
8184
  resolve({
8006
8185
  success: true,
8007
8186
  blockHash: (result.status.isInBlock ? result.status.asInBlock : result.status.asFinalized).toHex(),
8008
- extrinsicHash: extrinsic.hash.toHex()
8187
+ extrinsicHash: extrinsic.hash.toHex(),
8188
+ // Carried so a batch caller can attribute each item's outcome.
8189
+ events: result.events
8009
8190
  });
8010
8191
  }
8011
8192
  }).then((unsub) => {
@@ -8018,7 +8199,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8018
8199
  if (!resolved) {
8019
8200
  resolved = true;
8020
8201
  clearTimeout(timeoutId);
8021
- resolve({ success: false, error: err.message });
8202
+ resolve(this.classifySubmissionError(err));
8022
8203
  }
8023
8204
  });
8024
8205
  });
@@ -8032,8 +8213,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8032
8213
  */
8033
8214
  async submitBid(commitment, userOp) {
8034
8215
  try {
8035
- const extrinsic = this.api.tx.intentsCoprocessor.placeBid(commitment, userOp);
8036
- return await this.signAndSendExtrinsic(extrinsic);
8216
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.placeBid(commitment, userOp));
8037
8217
  } catch (error) {
8038
8218
  return {
8039
8219
  success: false,
@@ -8051,8 +8231,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8051
8231
  */
8052
8232
  async retractBid(commitment) {
8053
8233
  try {
8054
- const extrinsic = this.api.tx.intentsCoprocessor.retractBid(commitment);
8055
- return await this.signAndSendExtrinsic(extrinsic);
8234
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.retractBid(commitment));
8056
8235
  } catch (error) {
8057
8236
  return {
8058
8237
  success: false,
@@ -8082,11 +8261,12 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8082
8261
  */
8083
8262
  async submitBidWithRetraction(retractCommitment, bidCommitment, userOp) {
8084
8263
  try {
8085
- const batch = this.api.tx.utility.batch([
8086
- this.api.tx.intentsCoprocessor.placeBid(bidCommitment, userOp),
8087
- this.api.tx.intentsCoprocessor.retractBid(retractCommitment)
8088
- ]);
8089
- return await this.signAndSendExtrinsic(batch);
8264
+ return await this.signAndSendExtrinsic(
8265
+ (api) => api.tx.utility.batch([
8266
+ api.tx.intentsCoprocessor.placeBid(bidCommitment, userOp),
8267
+ api.tx.intentsCoprocessor.retractBid(retractCommitment)
8268
+ ])
8269
+ );
8090
8270
  } catch (error) {
8091
8271
  return {
8092
8272
  success: false,
@@ -8094,6 +8274,98 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8094
8274
  };
8095
8275
  }
8096
8276
  }
8277
+ /**
8278
+ * Places every phantom bid of one interval in a single extrinsic, retracting each chain's
8279
+ * previous bid alongside it.
8280
+ *
8281
+ * The pallet registers one phantom order per configured chain in the same block, so this is the
8282
+ * whole interval's set. Submitting them one at a time costs a block per chain: submissions are
8283
+ * serialised on the account nonce and each waits for inclusion, so the last chain's bid is many
8284
+ * blocks behind the first, against a bid window measured in tens of blocks. Batched, every bid
8285
+ * lands in the same block.
8286
+ *
8287
+ * Uses `utility.force_batch`, not `utility.batch`. `batch` stops at the first failing call, so
8288
+ * one rejected bid — a closed window, a duplicate, an insufficient deposit — would silently
8289
+ * drop every bid after it. `force_batch` runs them all and reports each outcome. It needs no
8290
+ * special origin: any signed account may call it, exactly like `batch`.
8291
+ *
8292
+ * @param bids - The bids to place; an empty list is a no-op
8293
+ * @returns Per-bid outcomes, in the order given
8294
+ */
8295
+ async submitPhantomBids(bids) {
8296
+ if (bids.length === 0) return { bids: [] };
8297
+ const placeIndexByBid = [];
8298
+ let callCount = 0;
8299
+ for (const bid of bids) {
8300
+ placeIndexByBid.push(callCount);
8301
+ callCount += bid.retractCommitment ? 2 : 1;
8302
+ }
8303
+ const outcome = await this.signAndSendExtrinsic(
8304
+ (api) => api.tx.utility.forceBatch(
8305
+ bids.flatMap((bid) => {
8306
+ const calls = [api.tx.intentsCoprocessor.placeBid(bid.commitment, bid.userOp)];
8307
+ if (bid.retractCommitment) {
8308
+ calls.push(api.tx.intentsCoprocessor.retractBid(bid.retractCommitment));
8309
+ }
8310
+ return calls;
8311
+ })
8312
+ )
8313
+ );
8314
+ if (!outcome.success) {
8315
+ return {
8316
+ bids: bids.map((bid) => ({ commitment: bid.commitment, success: false, error: outcome.error })),
8317
+ pending: outcome.pending,
8318
+ extrinsicHash: outcome.extrinsicHash,
8319
+ error: outcome.error
8320
+ };
8321
+ }
8322
+ const items = this.readForceBatchItems(outcome.events ?? [], callCount);
8323
+ return {
8324
+ bids: bids.map((bid, index) => {
8325
+ const error = items.errors[placeIndexByBid[index]];
8326
+ return { commitment: bid.commitment, success: !error, error };
8327
+ }),
8328
+ blockHash: outcome.blockHash,
8329
+ extrinsicHash: outcome.extrinsicHash,
8330
+ error: items.error
8331
+ };
8332
+ }
8333
+ /**
8334
+ * Reads one outcome per call out of a force_batch's events.
8335
+ *
8336
+ * `ItemFailed` carries no index — pallet-utility emits exactly one `ItemCompleted` or
8337
+ * `ItemFailed` per call, in call order, so the k-th item event belongs to call k.
8338
+ *
8339
+ * A count that does not match the calls submitted means the events are not the ones assumed
8340
+ * here, and every attribution after the discrepancy would be off by one. The bids are then
8341
+ * reported as placed: a bid wrongly recorded as landed is retracted next interval and the
8342
+ * retraction harmlessly fails with `BidNotFound`, whereas one wrongly recorded as failed is
8343
+ * never retracted at all and leaves its deposit reserved.
8344
+ */
8345
+ readForceBatchItems(events, callCount) {
8346
+ const errors = [];
8347
+ for (const { event } of events) {
8348
+ if (event.section !== "utility") continue;
8349
+ if (event.method === "ItemCompleted") errors.push(void 0);
8350
+ else if (event.method === "ItemFailed") errors.push(this.describeDispatchError(event.data[0]));
8351
+ }
8352
+ if (errors.length !== callCount) {
8353
+ return {
8354
+ errors: new Array(callCount).fill(void 0),
8355
+ error: `force_batch reported ${errors.length} item events for ${callCount} calls; outcomes not attributed`
8356
+ };
8357
+ }
8358
+ return { errors };
8359
+ }
8360
+ /** Renders a DispatchError as `pallet::Error`, falling back to its raw form. */
8361
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8362
+ describeDispatchError(dispatchError) {
8363
+ if (dispatchError?.isModule) {
8364
+ const decoded = this.api.registry.findMetaError(dispatchError.asModule);
8365
+ return `${decoded.section}::${decoded.name}`;
8366
+ }
8367
+ return dispatchError?.toString() ?? "unknown dispatch error";
8368
+ }
8097
8369
  /**
8098
8370
  * Fetches all bid storage entries for a given order commitment.
8099
8371
  * Returns the on-chain data only (filler addresses and deposits).
@@ -8102,7 +8374,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8102
8374
  * @returns Array of BidStorageEntry objects
8103
8375
  */
8104
8376
  async getBidStorageEntries(commitment) {
8105
- const entries = await this.api.query.intentsCoprocessor.bids.entries(commitment);
8377
+ const api = await this.http();
8378
+ const entries = await api.query.intentsCoprocessor.bids.entries(commitment);
8106
8379
  return entries.map(([storageKey, depositValue]) => ({
8107
8380
  commitment,
8108
8381
  filler: storageKey.args[1].toString(),
@@ -8132,9 +8405,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8132
8405
  * Single round-trip but does not include deposit amounts.
8133
8406
  */
8134
8407
  async getBidsViaRpc(commitment) {
8135
- const result = await this.api._rpcCore.provider.send("intents_getBidsForOrder", [
8136
- commitment
8137
- ]);
8408
+ const api = await this.http();
8409
+ const result = await api._rpcCore.provider.send("intents_getBidsForOrder", [commitment]);
8138
8410
  return result.map((entry) => {
8139
8411
  const userOp = decodeUserOpScale(entry.user_op);
8140
8412
  const filler = new Keyring({ type: "sr25519" }).encodeAddress(hexToU8a(entry.filler));
@@ -8146,7 +8418,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8146
8418
  * Slower but works on all nodes and includes deposit amounts.
8147
8419
  */
8148
8420
  async getBidsViaStorage(commitment) {
8149
- const entries = await this.api.query.intentsCoprocessor.bids.entries(commitment);
8421
+ const api = await this.http();
8422
+ const entries = await api.query.intentsCoprocessor.bids.entries(commitment);
8150
8423
  if (entries.length === 0) return [];
8151
8424
  const bidPromises = entries.map(async ([storageKey, depositValue]) => {
8152
8425
  try {
@@ -8154,7 +8427,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8154
8427
  const deposit = BigInt(depositValue.toString());
8155
8428
  const offchainKey = this.buildOffchainBidKey(commitment, filler);
8156
8429
  const offchainKeyHex = u8aToHex(offchainKey);
8157
- const offchainResult = await this.api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8430
+ const offchainResult = await api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8158
8431
  if (!offchainResult || offchainResult.isNone) return null;
8159
8432
  const bidData = offchainResult.unwrap().toHex();
8160
8433
  const decoded = this.decodeBid(bidData);
@@ -8188,13 +8461,12 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8188
8461
  */
8189
8462
  async fetchPhantomOrder(commitment) {
8190
8463
  const key = u8aConcat(OFFCHAIN_PHANTOM_PREFIX, hexToU8a(commitment));
8191
- const result = await this.api.rpc.offchain.localStorageGet("PERSISTENT", u8aToHex(key));
8464
+ const api = await this.http();
8465
+ const result = await api.rpc.offchain.localStorageGet("PERSISTENT", u8aToHex(key));
8192
8466
  if (!result || result.isNone) return null;
8193
8467
  const rawHex = result.unwrap().toHex();
8194
8468
  if (rawHex === "0x" || rawHex === "0x00") return null;
8195
- const placeOrderAbi = IntentGatewayV2_default.ABI.find(
8196
- (item) => item.type === "function" && item.name === "placeOrder"
8197
- );
8469
+ const placeOrderAbi = IntentGatewayV2_default.ABI.find((item) => item.type === "function" && item.name === "placeOrder");
8198
8470
  const orderType = placeOrderAbi?.inputs?.[0];
8199
8471
  if (!orderType) return null;
8200
8472
  const [decoded] = decodeAbiParameters([orderType], rawHex);
@@ -8234,8 +8506,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8234
8506
  * Reads the PhantomOrderRegistered events emitted in a single block.
8235
8507
  */
8236
8508
  async getPhantomOrdersInBlock(blockNumber) {
8237
- const blockHash = await this.api.rpc.chain.getBlockHash(blockNumber);
8238
- const apiAt = await this.api.at(blockHash);
8509
+ const api = await this.http();
8510
+ const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
8511
+ const apiAt = await api.at(blockHash);
8239
8512
  const records = await apiAt.query.system.events();
8240
8513
  const orders = [];
8241
8514
  for (const { event } of records) {
@@ -8256,7 +8529,13 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8256
8529
  return orders;
8257
8530
  }
8258
8531
  /**
8259
- * Polls for newly registered phantom orders, invoking the callback once per order.
8532
+ * Polls for newly registered phantom orders, invoking the callback once per block that carries
8533
+ * any, with all of that block's orders.
8534
+ *
8535
+ * Per block rather than per order because that is how the pallet writes them: one order per
8536
+ * configured chain, all registered in the same `on_initialize`. Delivering them together lets a
8537
+ * caller bid on the whole interval in one extrinsic (see {@link submitPhantomBids}) instead of
8538
+ * one per chain.
8260
8539
  *
8261
8540
  * Each tick reads the current head and scans every block between the last one processed and that
8262
8541
  * head, so the block cursor — not the connection — determines what has been seen. This replaced a
@@ -8269,10 +8548,16 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8269
8548
  * cannot drop them, because the cursor only advances past a block whose events were actually
8270
8549
  * read. Recovery replays the backlog.
8271
8550
  *
8551
+ * Every read here goes over HTTP, never the websocket. Polling is a sequence of independent
8552
+ * one-shot requests with no state to lose between them, which is exactly what a stateless
8553
+ * transport does well: a request either answers or fails loudly on this tick, instead of a
8554
+ * socket that looks alive while delivering nothing. It also means a websocket outage does not
8555
+ * pause phantom bidding at all — the two transports fail independently.
8556
+ *
8272
8557
  * Returns a function that stops polling.
8273
8558
  */
8274
8559
  pollPhantomOrders(callback, options = {}) {
8275
- const { intervalMs = 6e3, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8560
+ const { intervalMs, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8276
8561
  let cursor = null;
8277
8562
  let inFlight = false;
8278
8563
  let stopped = false;
@@ -8280,7 +8565,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8280
8565
  if (inFlight || stopped) return;
8281
8566
  inFlight = true;
8282
8567
  try {
8283
- const head = (await this.api.rpc.chain.getHeader()).number.toNumber();
8568
+ const head = (await (await this.http()).rpc.chain.getHeader()).number.toNumber();
8284
8569
  if (cursor === null) {
8285
8570
  cursor = Math.max(head - 1 - lookbackBlocks, -1);
8286
8571
  }
@@ -8289,7 +8574,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8289
8574
  for (let blockNumber = cursor + 1; blockNumber <= to; blockNumber++) {
8290
8575
  if (stopped) return;
8291
8576
  const orders = await this.getPhantomOrdersInBlock(blockNumber);
8292
- for (const order of orders) callback(order);
8577
+ if (orders.length > 0) callback(orders);
8293
8578
  cursor = blockNumber;
8294
8579
  }
8295
8580
  } catch (err) {
@@ -8299,12 +8584,31 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8299
8584
  }
8300
8585
  };
8301
8586
  void tick();
8302
- const timer = setInterval(() => void tick(), intervalMs);
8587
+ let timer = null;
8588
+ const startTimer = (ms) => {
8589
+ if (stopped) return;
8590
+ timer = setInterval(() => void tick(), ms);
8591
+ };
8592
+ if (intervalMs !== void 0) startTimer(intervalMs);
8593
+ else void this.phantomPollIntervalMs().then(startTimer);
8303
8594
  return () => {
8304
8595
  stopped = true;
8305
- clearInterval(timer);
8596
+ if (timer) clearInterval(timer);
8306
8597
  };
8307
8598
  }
8599
+ /**
8600
+ * The poll cadence for the runtime this instance is connected to: Gargantua polls every block,
8601
+ * everything else every 15s. Falls back to the slower cadence if the runtime cannot be read,
8602
+ * since an unreachable node is the poll's problem to report, not the cadence lookup's.
8603
+ */
8604
+ async phantomPollIntervalMs() {
8605
+ try {
8606
+ const specName = (await this.http()).runtimeVersion.specName.toString();
8607
+ return specName === "gargantua" ? GARGANTUA_PHANTOM_POLL_INTERVAL_MS : PHANTOM_POLL_INTERVAL_MS;
8608
+ } catch {
8609
+ return PHANTOM_POLL_INTERVAL_MS;
8610
+ }
8611
+ }
8308
8612
  };
8309
8613
  var TronChain = class _TronChain {
8310
8614
  constructor(params, evm) {
@@ -15106,6 +15410,12 @@ var CryptoUtils = class _CryptoUtils {
15106
15410
  * signing infrastructure (hardware wallets, MPC/TEE policy engines) instead
15107
15411
  * of an opaque 32-byte digest.
15108
15412
  *
15413
+ * The payload must be a standard self-describing `eth_signTypedData_v4`
15414
+ * payload — `EIP712Domain` listed in `types`, `chainId` as a JSON number —
15415
+ * because some signing backends (e.g. MPC Vault) hash it server-side from
15416
+ * the JSON rather than locally via viem. viem ignores both details when
15417
+ * hashing, so the digest is unchanged for local signers.
15418
+ *
15109
15419
  * @param userOp - The packed UserOperation to sign (signature field ignored).
15110
15420
  * @param entryPoint - Address of the EntryPoint v0.8 contract.
15111
15421
  * @param chainId - Chain ID of the network on which the operation will execute.
@@ -15116,10 +15426,22 @@ var CryptoUtils = class _CryptoUtils {
15116
15426
  domain: {
15117
15427
  name: "ERC4337",
15118
15428
  version: "1",
15119
- chainId,
15429
+ // Runtime number so JSON.stringify emits a canonical v4 numeric chainId for
15430
+ // server-side hashers; viem's uint256 type mapping wants bigint but its
15431
+ // runtime accepts numbers, hence the cast.
15432
+ chainId: Number(chainId),
15120
15433
  verifyingContract: entryPoint
15121
15434
  },
15435
+ // `as const`: viem derives the domain's TYPE from `types.EIP712Domain`, so the
15436
+ // entries must stay string literals — widened `string` fields make viem's
15437
+ // typed-data generics reject the payload at every call site.
15122
15438
  types: {
15439
+ EIP712Domain: [
15440
+ { name: "name", type: "string" },
15441
+ { name: "version", type: "string" },
15442
+ { name: "chainId", type: "uint256" },
15443
+ { name: "verifyingContract", type: "address" }
15444
+ ],
15123
15445
  PackedUserOperation: [
15124
15446
  { name: "sender", type: "address" },
15125
15447
  { name: "nonce", type: "uint256" },
@@ -16983,14 +17305,14 @@ var BidManager = class {
16983
17305
  }
16984
17306
  /**
16985
17307
  * Autopilot bid selection: sorts the given bids by output value, simulates
16986
- * each in order until one passes, then executes that bid. For consumers that
16987
- * do not need custom selection logic.
17308
+ * each in order and attempts execution. Any bid that fails simulation or
17309
+ * execution is skipped once so the next ranked bid can be attempted in the
17310
+ * same round. For consumers that do not need custom selection logic.
16988
17311
  *
16989
17312
  * @param order - The placed order to fill.
16990
17313
  * @param bids - Candidate bids (from {@link buildBids}).
16991
17314
  * @returns A {@link SelectBidResult} for the executed bid.
16992
- * @throws If no valid bids exist, all simulations fail, or the bundler rejects
16993
- * the UserOperation.
17315
+ * @throws If no valid bids exist or every bid fails simulation/execution.
16994
17316
  */
16995
17317
  async selectAndExecuteBest(order, bids) {
16996
17318
  const commitment = order.id;
@@ -17007,22 +17329,34 @@ var BidManager = class {
17007
17329
  throw new Error("No valid bids found");
17008
17330
  }
17009
17331
  console.log(`[BidManager] Simulating ${sortedBids.length} sorted bid(s) to find a valid one`);
17332
+ let simulationFailures = 0;
17333
+ let executionFailures = 0;
17010
17334
  for (let idx = 0; idx < sortedBids.length; idx++) {
17011
17335
  const bid = sortedBids[idx];
17012
17336
  console.log(`[BidManager] Simulating bid ${idx + 1}/${sortedBids.length} from solver=${bid.solverAddress}`);
17013
17337
  try {
17014
17338
  await bid.simulate();
17015
17339
  } catch (err) {
17340
+ simulationFailures += 1;
17016
17341
  console.warn(
17017
17342
  `[BidManager] Bid ${idx + 1} from solver=${bid.solverAddress}: simulation FAILED: ${err instanceof Error ? err.message : String(err)}`
17018
17343
  );
17019
17344
  continue;
17020
17345
  }
17021
17346
  console.log(`[BidManager] Bid ${idx + 1} from solver=${bid.solverAddress}: simulation PASSED`);
17022
- return bid.execute();
17347
+ try {
17348
+ return await bid.execute();
17349
+ } catch (err) {
17350
+ executionFailures += 1;
17351
+ console.warn(
17352
+ `[BidManager] Bid ${idx + 1} from solver=${bid.solverAddress}: execution FAILED: ${err instanceof Error ? err.message : String(err)}; trying next bid`
17353
+ );
17354
+ }
17023
17355
  }
17024
- console.error(`[BidManager] All ${sortedBids.length} bid(s) failed simulation for commitment=${commitment}`);
17025
- throw new Error("No bids passed simulation");
17356
+ console.error(
17357
+ `[BidManager] No executable bids for commitment=${commitment}: ${simulationFailures} simulation failure(s), ${executionFailures} execution failure(s)`
17358
+ );
17359
+ throw new Error("No bids passed simulation and execution");
17026
17360
  }
17027
17361
  /**
17028
17362
  * Sorts a list of bids for the given order by output value.
@@ -17362,6 +17696,10 @@ var BidManager = class {
17362
17696
  }
17363
17697
  };
17364
17698
  var RELAYER_MESSAGE_GAS = 1000000n;
17699
+ var NO_BUNDLER_FILL_GAS_BASE = 700000n;
17700
+ var NO_BUNDLER_FILL_GAS_PER_OUTPUT = 150000n;
17701
+ var NO_BUNDLER_PAYMASTER_VERIFICATION_GAS = 250000n;
17702
+ var NO_BUNDLER_PAYMASTER_POST_OP_GAS = 100000n;
17365
17703
  var GasEstimator = class {
17366
17704
  /**
17367
17705
  * @param ctx - Shared IntentsV2 context providing the source and destination
@@ -17395,8 +17733,10 @@ var GasEstimator = class {
17395
17733
  * headroom. If the bundler is Pimlico, gas prices are refined with
17396
17734
  * `pimlico_getUserOperationGasPrice`.
17397
17735
  *
17398
- * **Fallback path (no bundler):** calls `estimateContractGas` directly on
17399
- * `fillOrder` with state overrides.
17736
+ * **Fallback path (no bundler):** uses a fixed budget
17737
+ * ({@link NO_BUNDLER_FILL_GAS_BASE} plus {@link NO_BUNDLER_FILL_GAS_PER_OUTPUT}
17738
+ * per output leg) — public RPCs don't reliably support estimation with
17739
+ * state overrides.
17400
17740
  *
17401
17741
  * @param params - Parameters including the order to estimate and optional
17402
17742
  * percentage bumps for `maxPriorityFeePerGas` and `maxFeePerGas`.
@@ -17431,14 +17771,14 @@ var GasEstimator = class {
17431
17771
  }
17432
17772
  const isSameChain = souceStateMachineId === destStateMachineId;
17433
17773
  const [stateOverridesResult, crossChainFees] = await Promise.all([
17434
- this.buildStateOverride({
17774
+ this.ctx.bundlerUrl ? this.buildStateOverride({
17435
17775
  accountAddress: solverAccountAddress,
17436
17776
  chain: destStateMachineId,
17437
17777
  outputAssets: assetsForOverrides,
17438
17778
  spenderAddress: intentGatewayV2Address,
17439
17779
  intentGatewayV2Address,
17440
17780
  entryPointAddress
17441
- }),
17781
+ }) : Promise.resolve({ viem: [], bundler: {} }),
17442
17782
  isSameChain ? Promise.resolve({ postRequestFee: 0n, relayerFeeInSourceFeeToken: 0n }) : this.estimateCrossChainFees(
17443
17783
  sourceFeeToken,
17444
17784
  destFeeToken,
@@ -17446,7 +17786,7 @@ var GasEstimator = class {
17446
17786
  orderFeeGasPriceBumpPercent
17447
17787
  )
17448
17788
  ]);
17449
- const { viem: stateOverrides, bundler: bundlerStateOverrides } = stateOverridesResult;
17789
+ const { bundler: bundlerStateOverrides } = stateOverridesResult;
17450
17790
  const fillOptions = {
17451
17791
  relayerFee: crossChainFees.postRequestFee,
17452
17792
  // Always dispatch with the fee token (see the method docs).
@@ -17587,20 +17927,9 @@ var GasEstimator = class {
17587
17927
  console.warn("Bundler gas estimation failed, using fallback values:", e);
17588
17928
  }
17589
17929
  } else {
17590
- try {
17591
- const estimatedGas = await this.ctx.dest.client.estimateContractGas({
17592
- abi: ABI3,
17593
- address: intentGatewayV2Address,
17594
- functionName: "fillOrder",
17595
- args: [transformOrderForContract(order), fillOptions],
17596
- account: solverAccountAddress,
17597
- value: totalNativeValue,
17598
- stateOverride: stateOverrides
17599
- });
17600
- callGasLimit = estimatedGas * 105n / 100n;
17601
- } catch (e) {
17602
- console.warn("fillOrder gas estimation failed, using fallback:", e);
17603
- }
17930
+ callGasLimit = NO_BUNDLER_FILL_GAS_BASE + NO_BUNDLER_FILL_GAS_PER_OUTPUT * BigInt(order.output.assets.length);
17931
+ paymasterVerificationGasLimit = NO_BUNDLER_PAYMASTER_VERIFICATION_GAS;
17932
+ paymasterPostOpGasLimit = NO_BUNDLER_PAYMASTER_POST_OP_GAS;
17604
17933
  }
17605
17934
  const totalGas = callGasLimit + verificationGasLimit + preVerificationGas + paymasterVerificationGasLimit + paymasterPostOpGasLimit;
17606
17935
  const rawTotalGasCostWei = totalGas * maxFeePerGas;
@@ -19130,14 +19459,34 @@ var IntentGateway = class _IntentGateway {
19130
19459
  }
19131
19460
  }
19132
19461
  };
19462
+
19463
+ // src/protocols/intents/phantom-aggregation.ts
19133
19464
  var FILL_ORDER_ABI = IntentGatewayV2_default.ABI;
19134
- var DECLARATION_VERSION = 1;
19135
- var MAX_DECLARED_CHAINS = 255;
19136
- function encodeAcceptedSourceChains(chains2) {
19137
- if (chains2.length > MAX_DECLARED_CHAINS) {
19138
- throw new Error(`Cannot declare more than ${MAX_DECLARED_CHAINS} source chains`);
19465
+ var DECLARATION_V1 = 1;
19466
+ var DECLARATION_V2 = 2;
19467
+ var MAX_DECLARED_ENTRIES = 255;
19468
+ var MAX_TOKEN_ID_BYTES = 32;
19469
+ function tokenIdToBytes(tokenId) {
19470
+ if (tokenId < 0n) throw new Error(`Uniswap V4 tokenId cannot be negative: ${tokenId}`);
19471
+ const bytes = [];
19472
+ let rest = tokenId;
19473
+ while (rest > 0n) {
19474
+ bytes.unshift(Number(rest & 0xffn));
19475
+ rest >>= 8n;
19476
+ }
19477
+ return bytes.length > 0 ? bytes : [0];
19478
+ }
19479
+ function encodePhantomBidDeclaration(declaration) {
19480
+ const chains2 = declaration.acceptedSourceChains ?? [];
19481
+ const positions = declaration.uniswapV4Positions ?? [];
19482
+ if (chains2.length > MAX_DECLARED_ENTRIES) {
19483
+ throw new Error(`Cannot declare more than ${MAX_DECLARED_ENTRIES} source chains`);
19139
19484
  }
19140
- const bytes = [DECLARATION_VERSION, chains2.length];
19485
+ if (positions.length > MAX_DECLARED_ENTRIES) {
19486
+ throw new Error(`Cannot declare more than ${MAX_DECLARED_ENTRIES} Uniswap V4 positions`);
19487
+ }
19488
+ const version = positions.length > 0 ? DECLARATION_V2 : DECLARATION_V1;
19489
+ const bytes = [version, chains2.length];
19141
19490
  for (const chain of chains2) {
19142
19491
  const encoded = stringToU8a(chain);
19143
19492
  if (encoded.length === 0 || encoded.length > 255) {
@@ -19145,25 +19494,59 @@ function encodeAcceptedSourceChains(chains2) {
19145
19494
  }
19146
19495
  bytes.push(encoded.length, ...encoded);
19147
19496
  }
19497
+ if (version === DECLARATION_V2) {
19498
+ bytes.push(positions.length);
19499
+ for (const tokenId of positions) {
19500
+ const encoded = tokenIdToBytes(tokenId);
19501
+ if (encoded.length > MAX_TOKEN_ID_BYTES) {
19502
+ throw new Error(`Uniswap V4 tokenId exceeds uint256: ${tokenId}`);
19503
+ }
19504
+ bytes.push(encoded.length, ...encoded);
19505
+ }
19506
+ }
19148
19507
  return u8aToHex(new Uint8Array(bytes));
19149
19508
  }
19150
- function decodeAcceptedSourceChains(paymasterAndData) {
19151
- if (!paymasterAndData || !isHex$1(paymasterAndData)) return null;
19509
+ function decodePhantomBidDeclaration(paymasterAndData) {
19510
+ const absent = { acceptedSources: null, uniswapV4Positions: [] };
19511
+ if (!paymasterAndData || !isHex$1(paymasterAndData)) return absent;
19152
19512
  const bytes = hexToU8a(paymasterAndData);
19153
- if (bytes.length < 2 || bytes[0] !== DECLARATION_VERSION) return null;
19154
- const count = bytes[1];
19513
+ if (bytes.length < 2) return absent;
19514
+ const version = bytes[0];
19515
+ if (version !== DECLARATION_V1 && version !== DECLARATION_V2) return absent;
19155
19516
  const chains2 = [];
19156
19517
  let offset = 2;
19157
- for (let entry = 0; entry < count; entry++) {
19158
- if (offset >= bytes.length) return null;
19518
+ for (let entry = 0; entry < bytes[1]; entry++) {
19519
+ if (offset >= bytes.length) return absent;
19159
19520
  const length = bytes[offset];
19160
19521
  offset += 1;
19161
- if (length === 0 || offset + length > bytes.length) return null;
19522
+ if (length === 0 || offset + length > bytes.length) return absent;
19162
19523
  chains2.push(u8aToString(bytes.subarray(offset, offset + length)));
19163
19524
  offset += length;
19164
19525
  }
19165
- if (offset !== bytes.length) return null;
19166
- return chains2;
19526
+ const positions = [];
19527
+ if (version === DECLARATION_V2) {
19528
+ if (offset >= bytes.length) return absent;
19529
+ const count = bytes[offset];
19530
+ offset += 1;
19531
+ for (let entry = 0; entry < count; entry++) {
19532
+ if (offset >= bytes.length) return absent;
19533
+ const length = bytes[offset];
19534
+ offset += 1;
19535
+ if (length === 0 || length > MAX_TOKEN_ID_BYTES || offset + length > bytes.length) return absent;
19536
+ let tokenId = 0n;
19537
+ for (const byte of bytes.subarray(offset, offset + length)) tokenId = tokenId << 8n | BigInt(byte);
19538
+ positions.push(tokenId);
19539
+ offset += length;
19540
+ }
19541
+ }
19542
+ if (offset !== bytes.length) return absent;
19543
+ return { acceptedSources: chains2, uniswapV4Positions: positions };
19544
+ }
19545
+ function encodeAcceptedSourceChains(chains2) {
19546
+ return encodePhantomBidDeclaration({ acceptedSourceChains: chains2 });
19547
+ }
19548
+ function decodeAcceptedSourceChains(paymasterAndData) {
19549
+ return decodePhantomBidDeclaration(paymasterAndData).acceptedSources;
19167
19550
  }
19168
19551
  FILL_ORDER_ABI.find(
19169
19552
  (item) => item?.type === "function" && item?.name === "fillOrder"
@@ -23638,6 +24021,6 @@ async function teleportDot(param_) {
23638
24021
  return stream;
23639
24022
  }
23640
24023
 
23641
- export { ADDRESS_ZERO2 as ADDRESS_ZERO, BundlerMethod, ChainConfigService, Chains, CryptoUtils, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, ERC20Method, ERC7821_BATCH_MODE, EvmChain, ABI as EvmHostABI, EvmLanguage, HyperClientStatus, HyperFungibleToken, HyperFungibleTokenABI, IntentGateway, ABI3 as IntentGatewayABI, IntentOrderStatus, IntentsCoprocessor, InvalidPhantomSnapshotError, IsmpClient, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, PhantomSnapshotUnavailableError, PharosChain, PolkadotHubChain, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SubstrateChain, Swap, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, TokenGateway, TronChain, USE_ETHERSCAN_CHAINS, UnsupportedIntentQuotePairError, UnsupportedIntentQuoteStrategyError, WrappedHyperFungibleTokenABI, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeAcceptedSourceChains, decodeERC7821ExecuteBatch, decodeUserOpScale, encodeAcceptedSourceChains, encodeERC7821ExecuteBatch, encodeISMPMessage, encodeStateMachineId, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getContractCallInputs, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, normalizeAddressForEvmBytes32, normalizeAddressForStateMachine, normalizeEvmAddress, normalizeEvmChainId, normalizeStateMachineId, orderCommitment, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, polkadotHubMainnet, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, quoteUniswap, requestCommitmentKey, responseCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
24024
+ export { ADDRESS_ZERO2 as ADDRESS_ZERO, BundlerMethod, ChainConfigService, Chains, CryptoUtils, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, ERC20Method, ERC7821_BATCH_MODE, EvmChain, ABI as EvmHostABI, EvmLanguage, HyperClientStatus, HyperFungibleToken, HyperFungibleTokenABI, IntentGateway, ABI3 as IntentGatewayABI, IntentOrderStatus, IntentsCoprocessor, InvalidPhantomSnapshotError, IsmpClient, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, PhantomSnapshotUnavailableError, PharosChain, PolkadotHubChain, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SubstrateChain, Swap, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, TokenGateway, TronChain, USE_ETHERSCAN_CHAINS, UnsupportedIntentQuotePairError, UnsupportedIntentQuoteStrategyError, WrappedHyperFungibleTokenABI, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeAcceptedSourceChains, decodeERC7821ExecuteBatch, decodePhantomBidDeclaration, decodeUserOpScale, deriveHttpUrl, encodeAcceptedSourceChains, encodeERC7821ExecuteBatch, encodeISMPMessage, encodePhantomBidDeclaration, encodeStateMachineId, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getContractCallInputs, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, normalizeAddressForEvmBytes32, normalizeAddressForStateMachine, normalizeEvmAddress, normalizeEvmChainId, normalizeStateMachineId, orderCommitment, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, polkadotHubMainnet, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, quoteUniswap, requestCommitmentKey, responseCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
23642
24025
  //# sourceMappingURL=index.js.map
23643
24026
  //# sourceMappingURL=index.js.map