@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.
@@ -4,7 +4,7 @@ import { baseSepolia, optimismSepolia, arbitrumSepolia, soneium, gnosis, optimis
4
4
  import { TronWeb } from 'tronweb';
5
5
  import { flatten, zip, capitalize, maxBy, isNil } from 'lodash-es';
6
6
  import { match } from 'ts-pattern';
7
- import { WsProvider, ApiPromise, Keyring } from '@polkadot/api';
7
+ import { WsProvider, ApiPromise, HttpProvider, Keyring } from '@polkadot/api';
8
8
  import { Struct, Vector, u8, Bytes, Enum, Tuple, _void, u64, u32, Option, bool, u128 } from 'scale-ts';
9
9
  import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a, blake2AsU8a } from '@polkadot/util-crypto';
10
10
  import { hexToU8a, u8aToHex, u8aConcat, stringToU8a, isHex as isHex$1, u8aToString } from '@polkadot/util';
@@ -2738,13 +2738,26 @@ var chainConfigs = {
2738
2738
  tokenDecimals: {
2739
2739
  USDC: 6,
2740
2740
  USDT: 6,
2741
- cNGN: 6
2741
+ cNGN: 6,
2742
+ ZARP: 18,
2743
+ EURC: 6,
2744
+ XSGD: 6,
2745
+ TRYB: 6,
2746
+ USDR: 6
2742
2747
  },
2743
2748
  tokenStorageSlots: {
2744
2749
  USDT: { balanceSlot: 2, allowanceSlot: 5 },
2745
2750
  USDC: { balanceSlot: 9, allowanceSlot: 10 },
2746
2751
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2747
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2752
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2753
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 },
2754
+ // custom upgradeable layout
2755
+ ZARP: { balanceSlot: 51, allowanceSlot: 52 },
2756
+ EURC: { balanceSlot: 9, allowanceSlot: 10 },
2757
+ // Circle FiatToken layout
2758
+ XSGD: { balanceSlot: 7, allowanceSlot: 8 },
2759
+ TRYB: { balanceSlot: 9, allowanceSlot: 10 },
2760
+ USDR: { balanceSlot: 51, allowanceSlot: 52 }
2748
2761
  },
2749
2762
  addresses: {
2750
2763
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -2793,18 +2806,25 @@ var chainConfigs = {
2793
2806
  DAI: "0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3",
2794
2807
  USDC: "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d",
2795
2808
  USDT: "0x55d398326f99059ff775485246999027b3197955",
2796
- EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209"
2809
+ EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209",
2810
+ cNGN: "0xa8AEA66B361a8d53e8865c62D142167Af28Af058"
2797
2811
  },
2798
2812
  tokenDecimals: {
2799
2813
  USDC: 18,
2800
2814
  USDT: 18,
2815
+ // 6, not 18 — cNGN keeps the same decimals it has on every other chain, unlike the
2816
+ // Binance-pegged stables above. Every phantom standard_amount and pool rate divides
2817
+ // by this, so the divergence from its neighbours here is load-bearing, not a typo.
2818
+ cNGN: 6,
2801
2819
  EXT: 18
2802
2820
  },
2803
2821
  tokenStorageSlots: {
2804
2822
  USDT: { balanceSlot: 1, allowanceSlot: 2 },
2805
2823
  USDC: { balanceSlot: 1, allowanceSlot: 2 },
2806
2824
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2807
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2825
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2826
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 }
2827
+ // custom upgradeable layout, as on Base
2808
2828
  },
2809
2829
  addresses: {
2810
2830
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -2924,13 +2944,22 @@ var chainConfigs = {
2924
2944
  USDC: 6,
2925
2945
  USDT: 6,
2926
2946
  cNGN: 6,
2927
- EXT: 18
2947
+ EXT: 18,
2948
+ ZARP: 18,
2949
+ EURC: 6,
2950
+ USDR: 6
2928
2951
  },
2929
2952
  tokenStorageSlots: {
2930
2953
  USDT: { balanceSlot: 0, allowanceSlot: 1 },
2931
2954
  USDC: { balanceSlot: 9, allowanceSlot: 10 },
2932
2955
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2933
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2956
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2957
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 },
2958
+ // custom upgradeable layout
2959
+ ZARP: { balanceSlot: 51, allowanceSlot: 52 },
2960
+ EURC: { balanceSlot: 9, allowanceSlot: 10 },
2961
+ // Circle FiatToken layout
2962
+ USDR: { balanceSlot: 51, allowanceSlot: 52 }
2934
2963
  },
2935
2964
  addresses: {
2936
2965
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -2991,13 +3020,21 @@ var chainConfigs = {
2991
3020
  USDC: 6,
2992
3021
  USDT: 6,
2993
3022
  EXT: 18,
2994
- cNGN: 6
3023
+ cNGN: 6,
3024
+ ZARP: 18,
3025
+ XSGD: 6,
3026
+ USDR: 6
2995
3027
  },
2996
3028
  tokenStorageSlots: {
2997
3029
  USDT: { balanceSlot: 0, allowanceSlot: 1 },
2998
3030
  USDC: { balanceSlot: 9, allowanceSlot: 10 },
2999
3031
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
3000
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
3032
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
3033
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 },
3034
+ // custom upgradeable layout
3035
+ ZARP: { balanceSlot: 51, allowanceSlot: 52 },
3036
+ XSGD: { balanceSlot: 7, allowanceSlot: 8 },
3037
+ USDR: { balanceSlot: 51, allowanceSlot: 52 }
3001
3038
  },
3002
3039
  addresses: {
3003
3040
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -3298,8 +3335,9 @@ var chainConfigs = {
3298
3335
  assets: {
3299
3336
  WETH: "0x0000000000000000000000000000000000000000",
3300
3337
  DAI: "0x0000000000000000000000000000000000000000",
3338
+ // Asset Hub assets at their asset-id precompile addresses: 0x539 = 1337, 0x7c0 = 1984.
3301
3339
  USDC: "0x0000053900000000000000000000000001200000",
3302
- USDT: "0x0000000000000000000000000000000000000000"
3340
+ USDT: "0x000007c000000000000000000000000001200000"
3303
3341
  },
3304
3342
  tokenDecimals: {
3305
3343
  USDC: 6,
@@ -7818,6 +7856,27 @@ function encodeISMPMessage(message) {
7818
7856
  }
7819
7857
  var OFFCHAIN_BID_PREFIX = new TextEncoder().encode("intents::bid::");
7820
7858
  var OFFCHAIN_PHANTOM_PREFIX = new TextEncoder().encode("intents::phantom::order::");
7859
+ var HYPERBRIDGE_TYPES_BUNDLE = {
7860
+ spec: {
7861
+ nexus: { hasher: keccakAsU8a },
7862
+ gargantua: { hasher: keccakAsU8a }
7863
+ }
7864
+ };
7865
+ var BASE_TIP = 1000000000n;
7866
+ var HTTP_CONNECT_TIMEOUT_MS = 2e4;
7867
+ var PHANTOM_POLL_INTERVAL_MS = 15e3;
7868
+ var GARGANTUA_PHANTOM_POLL_INTERVAL_MS = 6e3;
7869
+ function rejectAfter(ms, message) {
7870
+ return new Promise((_resolve, reject) => {
7871
+ const timer = setTimeout(() => reject(new Error(message)), ms);
7872
+ timer.unref?.();
7873
+ });
7874
+ }
7875
+ function deriveHttpUrl(wsUrl) {
7876
+ if (wsUrl.startsWith("wss://")) return `https://${wsUrl.slice("wss://".length)}`;
7877
+ if (wsUrl.startsWith("ws://")) return `http://${wsUrl.slice("ws://".length)}`;
7878
+ throw new Error(`Cannot derive an HTTP endpoint from a non-websocket url: ${wsUrl}`);
7879
+ }
7821
7880
  var BidCodec = Struct({ filler: Bytes(32), user_op: Vector(u8) });
7822
7881
  var PackedUserOperationCodec = Struct({
7823
7882
  sender: Bytes(20),
@@ -7878,6 +7937,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7878
7937
  ownsConnection;
7879
7938
  /** Cached result of whether the node exposes intents_* RPC methods */
7880
7939
  hasIntentsRpc = null;
7940
+ /** The HTTP-backed api, connected on first use. Cleared after a failed attempt so it retries. */
7941
+ httpApi = null;
7881
7942
  // Serialises every extrinsic submission on this instance's substrate account. All submit/retract
7882
7943
  // methods funnel through signAndSendExtrinsic, each using the API's auto-nonce; fired in parallel
7883
7944
  // (bids for orders on different chains, or several phantom orders in one interval) they would grab
@@ -7894,12 +7955,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7894
7955
  static async connect(wsUrl, substratePrivateKey) {
7895
7956
  const api = await ApiPromise.create({
7896
7957
  provider: new WsProvider(wsUrl),
7897
- typesBundle: {
7898
- spec: {
7899
- nexus: { hasher: keccakAsU8a },
7900
- gargantua: { hasher: keccakAsU8a }
7901
- }
7902
- }
7958
+ typesBundle: HYPERBRIDGE_TYPES_BUNDLE
7903
7959
  });
7904
7960
  return new _IntentsCoprocessor(api, substratePrivateKey, true);
7905
7961
  }
@@ -7925,15 +7981,85 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7925
7981
  static fromApi(api, substratePrivateKey) {
7926
7982
  return new _IntentsCoprocessor(api, substratePrivateKey, false);
7927
7983
  }
7984
+ /**
7985
+ * The API every RPC query runs on: HTTP, connected to the same node as the websocket. Exposed so
7986
+ * callers query through this connection rather than opening one of their own.
7987
+ *
7988
+ * The split is by what each transport is for. Queries are one-shot request/response, which HTTP
7989
+ * serves without holding any state that can silently rot between calls. The websocket earns its
7990
+ * keep only where subscriptions do — watching a submitted extrinsic to inclusion.
7991
+ */
7992
+ async queryApi() {
7993
+ return await this.http();
7994
+ }
7995
+ /**
7996
+ * The websocket API, exposed so callers share this one connection instead of opening a second
7997
+ * socket to the same node. Only needed for subscriptions; use {@link queryApi} to read.
7998
+ */
7999
+ get apiConnection() {
8000
+ return this.api;
8001
+ }
7928
8002
  /**
7929
8003
  * Disconnects the underlying API connection if this instance owns it.
7930
- * Only disconnects if created via `connect()`, not when using shared connections.
8004
+ * Only disconnects the websocket if created via `connect()`, not when using shared connections.
8005
+ * The HTTP api is always created here, so it is always ours to close.
7931
8006
  */
7932
8007
  async disconnect() {
8008
+ const http4 = this.httpApi;
8009
+ this.httpApi = null;
8010
+ if (http4) {
8011
+ await http4.then((api) => api.disconnect()).catch(() => {
8012
+ });
8013
+ }
7933
8014
  if (this.ownsConnection) {
7934
8015
  await this.api.disconnect();
7935
8016
  }
7936
8017
  }
8018
+ /**
8019
+ * The HTTP api for this node, connected on first use. Every coprocessor has one — the endpoint
8020
+ * is derived from the websocket's own endpoint, so there is nothing to configure and nothing to
8021
+ * be absent.
8022
+ *
8023
+ * The connection attempt is bounded on both sides. `isReadyOrError` rejects on a failed
8024
+ * handshake, where plain `isReady` would simply never resolve, and the timeout covers an
8025
+ * endpoint that accepts the request and then goes quiet. An unbounded wait here would hang the
8026
+ * poll tick awaiting it, which is precisely the silent stall that polling exists to avoid. A
8027
+ * failed attempt is not cached, so the next call tries again.
8028
+ */
8029
+ async http() {
8030
+ if (!this.httpApi) {
8031
+ const httpUrl = deriveHttpUrl(this.wsEndpoint());
8032
+ const api = new ApiPromise({
8033
+ provider: new HttpProvider(httpUrl),
8034
+ typesBundle: HYPERBRIDGE_TYPES_BUNDLE,
8035
+ // A second connection to the node the ws api already reported on; its init warnings
8036
+ // would just be duplicates.
8037
+ noInitWarn: true
8038
+ });
8039
+ this.httpApi = Promise.race([
8040
+ api.isReadyOrError,
8041
+ rejectAfter(HTTP_CONNECT_TIMEOUT_MS, `HTTP RPC ${httpUrl} did not become ready`)
8042
+ ]).catch(async (err) => {
8043
+ await api.disconnect().catch(() => {
8044
+ });
8045
+ this.httpApi = null;
8046
+ throw new Error(`HTTP RPC ${httpUrl} is unavailable: ${err instanceof Error ? err.message : err}`);
8047
+ });
8048
+ }
8049
+ return await this.httpApi;
8050
+ }
8051
+ /**
8052
+ * The endpoint the websocket provider is connected to. Read from the provider rather than
8053
+ * remembered from a constructor argument, so it is the one endpoint in use no matter which
8054
+ * factory built this instance.
8055
+ */
8056
+ wsEndpoint() {
8057
+ const endpoint = this.api._rpcCore?.provider?.endpoint;
8058
+ if (!endpoint) {
8059
+ throw new Error("Cannot determine the Hyperbridge websocket endpoint to derive an HTTP endpoint from");
8060
+ }
8061
+ return endpoint;
8062
+ }
7937
8063
  /**
7938
8064
  * Creates a Substrate keypair from the configured private key.
7939
8065
  * Supports hex seed (with or without 0x), mnemonic phrases, and URI derivation paths (//Alice).
@@ -7956,26 +8082,67 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7956
8082
  /**
7957
8083
  * Signs and sends an extrinsic. Submissions are serialised through {@link submissionQueue} so
7958
8084
  * concurrent calls never collide on the substrate account nonce — each extrinsic reaches a block
7959
- * before the next is signed.
8085
+ * (or is confirmed still pooled and returned as `pending`) before the next is signed; auto-nonce
8086
+ * via `system.accountNextIndex` counts pooled extrinsics, so a pending one is never re-used.
8087
+ *
8088
+ * The extrinsic is built rather than passed in because the api it is built on decides where it
8089
+ * is signed and sent: a websocket that is down when the queue reaches this submission diverts it
8090
+ * to {@link sendViaHttp}, which needs the call bound to the HTTP api instead.
7960
8091
  */
7961
- async signAndSendExtrinsic(extrinsic, maxRetries = 3, timeoutMs = 3e4) {
7962
- const result = await this.submissionQueue.add(() => this.sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs));
8092
+ async signAndSendExtrinsic(build, maxRetries = 3, timeoutMs = 3e4) {
8093
+ const result = await this.submissionQueue.add(async () => {
8094
+ if (!this.api.isConnected) {
8095
+ try {
8096
+ return await this.sendViaHttp(await this.http(), build);
8097
+ } catch (err) {
8098
+ return { success: false, error: err instanceof Error ? err.message : String(err) };
8099
+ }
8100
+ }
8101
+ return await this.sendExtrinsicWithRetries(build(this.api), maxRetries, timeoutMs);
8102
+ });
7963
8103
  return result ?? { success: false, error: "Submission queue returned no result" };
7964
8104
  }
8105
+ /**
8106
+ * Last-resort submission for when the websocket is down at signing time. A bid is only worth
8107
+ * anything inside its window, so waiting for a reconnect usually means not bidding at all.
8108
+ *
8109
+ * HTTP has no subscriptions, so this is `author_submitExtrinsic`: the node accepts the extrinsic
8110
+ * into its pool and returns its hash, and nothing further is observable from here. That is
8111
+ * exactly the `pending` contract — in flight, outcome unknown, do not re-sign — so the result
8112
+ * says so rather than claiming a success it cannot see.
8113
+ *
8114
+ * Only reached when the socket was already down before signing. A submission that got as far as
8115
+ * the pool over the websocket is never retried here: that is the duplicate-nonce race the
8116
+ * `pending` result exists to prevent.
8117
+ */
8118
+ async sendViaHttp(api, build) {
8119
+ try {
8120
+ const hash = await build(api).signAndSend(this.getKeyPair(), { tip: BASE_TIP });
8121
+ return { success: false, pending: true, extrinsicHash: hash.toHex() };
8122
+ } catch (err) {
8123
+ return this.classifySubmissionError(err instanceof Error ? err : new Error(String(err)));
8124
+ }
8125
+ }
7965
8126
  /**
7966
8127
  * Signs and sends an extrinsic, handling status updates and errors.
7967
8128
  * Implements retry logic with progressive tip increases for stuck transactions.
8129
+ *
8130
+ * A retry only happens when the previous attempt verifiably went nowhere. Once an attempt's
8131
+ * extrinsic is known to be pooled (`pending`), re-signing the same call would race our own
8132
+ * submission: the copy either bounces off the pool (1014, same nonce below the replacement
8133
+ * priority bump) or — if the original lands first, freeing the nonce — executes as a duplicate
8134
+ * and fails on-chain (e.g. `BidNotFound` for a retraction). Neither can succeed, so the pending
8135
+ * result is returned for the caller to confirm later.
7968
8136
  */
7969
8137
  async sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs) {
7970
8138
  const keyPair = this.getKeyPair();
7971
- const baseTip = 1000000000n;
7972
8139
  let attempt = 0;
7973
8140
  while (attempt < maxRetries) {
7974
- const currentTip = baseTip * BigInt(2 ** attempt);
8141
+ const currentTip = BASE_TIP * BigInt(2 ** attempt);
7975
8142
  attempt++;
7976
8143
  try {
7977
8144
  const result = await this.sendWithTimeout(extrinsic, keyPair, currentTip, timeoutMs);
7978
- if (result.success || result.error?.includes("Dispatch error")) {
8145
+ if (result.success || result.pending || result.error?.includes("Dispatch error")) {
7979
8146
  return result;
7980
8147
  }
7981
8148
  } catch (err) {
@@ -7991,12 +8158,30 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7991
8158
  };
7992
8159
  }
7993
8160
  /**
7994
- * Sends an extrinsic with a timeout
8161
+ * Classifies a submission rejection. Codes 1013 ("already imported") and 1014 ("priority is
8162
+ * too low") both mean a copy of this account+nonce is already in the pool — almost always our
8163
+ * own earlier attempt whose watch handle didn't confirm cleanly. That extrinsic is in flight;
8164
+ * resubmitting can only bounce again or land a duplicate, so these are surfaced as `pending`
8165
+ * rather than failure.
8166
+ */
8167
+ classifySubmissionError(err) {
8168
+ const code = err.code;
8169
+ const inFlight = code === 1013 || code === 1014 || /already imported|already in the pool|priority is too low/i.test(err.message);
8170
+ return { success: false, pending: inFlight || void 0, error: err.message };
8171
+ }
8172
+ /**
8173
+ * Sends an extrinsic with a timeout.
8174
+ *
8175
+ * A timeout is only a failure when the extrinsic never made it into the transaction pool.
8176
+ * Once a pool-entry status (Future/Ready/Broadcast/Retracted) has been seen, the extrinsic is
8177
+ * in flight and may well execute after the watch is abandoned — the result is then `pending`,
8178
+ * telling the caller to confirm the outcome later instead of re-signing the same call.
7995
8179
  */
7996
8180
  async sendWithTimeout(extrinsic, keyPair, tip, timeoutMs) {
7997
8181
  return new Promise((resolve) => {
7998
8182
  let resolved = false;
7999
8183
  let unsubscribe = null;
8184
+ let enteredPool = false;
8000
8185
  const timeoutId = setTimeout(() => {
8001
8186
  if (!resolved) {
8002
8187
  resolved = true;
@@ -8005,25 +8190,23 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8005
8190
  }
8006
8191
  resolve({
8007
8192
  success: false,
8008
- error: `Transaction timed out after ${timeoutMs}ms`
8193
+ pending: enteredPool || void 0,
8194
+ extrinsicHash: enteredPool ? extrinsic.hash.toHex() : void 0,
8195
+ error: `Transaction timed out after ${timeoutMs}ms${enteredPool ? " while in the transaction pool" : ""}`
8009
8196
  });
8010
8197
  }
8011
8198
  }, timeoutMs);
8012
8199
  extrinsic.signAndSend(keyPair, { tip }, (result) => {
8013
8200
  if (resolved) return;
8201
+ if (result.status.isFuture || result.status.isReady || result.status.isBroadcast || result.status.isRetracted) {
8202
+ enteredPool = true;
8203
+ }
8014
8204
  if (result.dispatchError && (result.status.isInBlock || result.status.isFinalized)) {
8015
8205
  resolved = true;
8016
8206
  clearTimeout(timeoutId);
8017
- let errorMsg;
8018
- if (result.dispatchError.isModule) {
8019
- const decoded = this.api.registry.findMetaError(result.dispatchError.asModule);
8020
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
8021
- } else {
8022
- errorMsg = `Dispatch error: ${result.dispatchError.toString()}`;
8023
- }
8024
8207
  resolve({
8025
8208
  success: false,
8026
- error: errorMsg
8209
+ error: `Dispatch error: ${this.describeDispatchError(result.dispatchError)}`
8027
8210
  });
8028
8211
  } else if (result.status.isDropped || result.status.isInvalid || result.status.isUsurped || result.status.isFinalityTimeout) {
8029
8212
  resolved = true;
@@ -8041,21 +8224,19 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8041
8224
  if (interrupted) {
8042
8225
  const [indexCodec, dispatchError] = interrupted.event.data;
8043
8226
  if (Number(indexCodec.toString()) === 0) {
8044
- let errorMsg;
8045
- if (dispatchError?.isModule) {
8046
- const decoded = this.api.registry.findMetaError(dispatchError.asModule);
8047
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
8048
- } else {
8049
- errorMsg = `Dispatch error: batch interrupted (${dispatchError?.toString()})`;
8050
- }
8051
- resolve({ success: false, error: errorMsg });
8227
+ resolve({
8228
+ success: false,
8229
+ error: `Dispatch error: ${this.describeDispatchError(dispatchError)}`
8230
+ });
8052
8231
  return;
8053
8232
  }
8054
8233
  }
8055
8234
  resolve({
8056
8235
  success: true,
8057
8236
  blockHash: (result.status.isInBlock ? result.status.asInBlock : result.status.asFinalized).toHex(),
8058
- extrinsicHash: extrinsic.hash.toHex()
8237
+ extrinsicHash: extrinsic.hash.toHex(),
8238
+ // Carried so a batch caller can attribute each item's outcome.
8239
+ events: result.events
8059
8240
  });
8060
8241
  }
8061
8242
  }).then((unsub) => {
@@ -8068,7 +8249,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8068
8249
  if (!resolved) {
8069
8250
  resolved = true;
8070
8251
  clearTimeout(timeoutId);
8071
- resolve({ success: false, error: err.message });
8252
+ resolve(this.classifySubmissionError(err));
8072
8253
  }
8073
8254
  });
8074
8255
  });
@@ -8082,8 +8263,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8082
8263
  */
8083
8264
  async submitBid(commitment, userOp) {
8084
8265
  try {
8085
- const extrinsic = this.api.tx.intentsCoprocessor.placeBid(commitment, userOp);
8086
- return await this.signAndSendExtrinsic(extrinsic);
8266
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.placeBid(commitment, userOp));
8087
8267
  } catch (error) {
8088
8268
  return {
8089
8269
  success: false,
@@ -8101,8 +8281,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8101
8281
  */
8102
8282
  async retractBid(commitment) {
8103
8283
  try {
8104
- const extrinsic = this.api.tx.intentsCoprocessor.retractBid(commitment);
8105
- return await this.signAndSendExtrinsic(extrinsic);
8284
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.retractBid(commitment));
8106
8285
  } catch (error) {
8107
8286
  return {
8108
8287
  success: false,
@@ -8132,11 +8311,12 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8132
8311
  */
8133
8312
  async submitBidWithRetraction(retractCommitment, bidCommitment, userOp) {
8134
8313
  try {
8135
- const batch = this.api.tx.utility.batch([
8136
- this.api.tx.intentsCoprocessor.placeBid(bidCommitment, userOp),
8137
- this.api.tx.intentsCoprocessor.retractBid(retractCommitment)
8138
- ]);
8139
- return await this.signAndSendExtrinsic(batch);
8314
+ return await this.signAndSendExtrinsic(
8315
+ (api) => api.tx.utility.batch([
8316
+ api.tx.intentsCoprocessor.placeBid(bidCommitment, userOp),
8317
+ api.tx.intentsCoprocessor.retractBid(retractCommitment)
8318
+ ])
8319
+ );
8140
8320
  } catch (error) {
8141
8321
  return {
8142
8322
  success: false,
@@ -8144,6 +8324,98 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8144
8324
  };
8145
8325
  }
8146
8326
  }
8327
+ /**
8328
+ * Places every phantom bid of one interval in a single extrinsic, retracting each chain's
8329
+ * previous bid alongside it.
8330
+ *
8331
+ * The pallet registers one phantom order per configured chain in the same block, so this is the
8332
+ * whole interval's set. Submitting them one at a time costs a block per chain: submissions are
8333
+ * serialised on the account nonce and each waits for inclusion, so the last chain's bid is many
8334
+ * blocks behind the first, against a bid window measured in tens of blocks. Batched, every bid
8335
+ * lands in the same block.
8336
+ *
8337
+ * Uses `utility.force_batch`, not `utility.batch`. `batch` stops at the first failing call, so
8338
+ * one rejected bid — a closed window, a duplicate, an insufficient deposit — would silently
8339
+ * drop every bid after it. `force_batch` runs them all and reports each outcome. It needs no
8340
+ * special origin: any signed account may call it, exactly like `batch`.
8341
+ *
8342
+ * @param bids - The bids to place; an empty list is a no-op
8343
+ * @returns Per-bid outcomes, in the order given
8344
+ */
8345
+ async submitPhantomBids(bids) {
8346
+ if (bids.length === 0) return { bids: [] };
8347
+ const placeIndexByBid = [];
8348
+ let callCount = 0;
8349
+ for (const bid of bids) {
8350
+ placeIndexByBid.push(callCount);
8351
+ callCount += bid.retractCommitment ? 2 : 1;
8352
+ }
8353
+ const outcome = await this.signAndSendExtrinsic(
8354
+ (api) => api.tx.utility.forceBatch(
8355
+ bids.flatMap((bid) => {
8356
+ const calls = [api.tx.intentsCoprocessor.placeBid(bid.commitment, bid.userOp)];
8357
+ if (bid.retractCommitment) {
8358
+ calls.push(api.tx.intentsCoprocessor.retractBid(bid.retractCommitment));
8359
+ }
8360
+ return calls;
8361
+ })
8362
+ )
8363
+ );
8364
+ if (!outcome.success) {
8365
+ return {
8366
+ bids: bids.map((bid) => ({ commitment: bid.commitment, success: false, error: outcome.error })),
8367
+ pending: outcome.pending,
8368
+ extrinsicHash: outcome.extrinsicHash,
8369
+ error: outcome.error
8370
+ };
8371
+ }
8372
+ const items = this.readForceBatchItems(outcome.events ?? [], callCount);
8373
+ return {
8374
+ bids: bids.map((bid, index) => {
8375
+ const error = items.errors[placeIndexByBid[index]];
8376
+ return { commitment: bid.commitment, success: !error, error };
8377
+ }),
8378
+ blockHash: outcome.blockHash,
8379
+ extrinsicHash: outcome.extrinsicHash,
8380
+ error: items.error
8381
+ };
8382
+ }
8383
+ /**
8384
+ * Reads one outcome per call out of a force_batch's events.
8385
+ *
8386
+ * `ItemFailed` carries no index — pallet-utility emits exactly one `ItemCompleted` or
8387
+ * `ItemFailed` per call, in call order, so the k-th item event belongs to call k.
8388
+ *
8389
+ * A count that does not match the calls submitted means the events are not the ones assumed
8390
+ * here, and every attribution after the discrepancy would be off by one. The bids are then
8391
+ * reported as placed: a bid wrongly recorded as landed is retracted next interval and the
8392
+ * retraction harmlessly fails with `BidNotFound`, whereas one wrongly recorded as failed is
8393
+ * never retracted at all and leaves its deposit reserved.
8394
+ */
8395
+ readForceBatchItems(events, callCount) {
8396
+ const errors = [];
8397
+ for (const { event } of events) {
8398
+ if (event.section !== "utility") continue;
8399
+ if (event.method === "ItemCompleted") errors.push(void 0);
8400
+ else if (event.method === "ItemFailed") errors.push(this.describeDispatchError(event.data[0]));
8401
+ }
8402
+ if (errors.length !== callCount) {
8403
+ return {
8404
+ errors: new Array(callCount).fill(void 0),
8405
+ error: `force_batch reported ${errors.length} item events for ${callCount} calls; outcomes not attributed`
8406
+ };
8407
+ }
8408
+ return { errors };
8409
+ }
8410
+ /** Renders a DispatchError as `pallet::Error`, falling back to its raw form. */
8411
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8412
+ describeDispatchError(dispatchError) {
8413
+ if (dispatchError?.isModule) {
8414
+ const decoded = this.api.registry.findMetaError(dispatchError.asModule);
8415
+ return `${decoded.section}::${decoded.name}`;
8416
+ }
8417
+ return dispatchError?.toString() ?? "unknown dispatch error";
8418
+ }
8147
8419
  /**
8148
8420
  * Fetches all bid storage entries for a given order commitment.
8149
8421
  * Returns the on-chain data only (filler addresses and deposits).
@@ -8152,7 +8424,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8152
8424
  * @returns Array of BidStorageEntry objects
8153
8425
  */
8154
8426
  async getBidStorageEntries(commitment) {
8155
- const entries = await this.api.query.intentsCoprocessor.bids.entries(commitment);
8427
+ const api = await this.http();
8428
+ const entries = await api.query.intentsCoprocessor.bids.entries(commitment);
8156
8429
  return entries.map(([storageKey, depositValue]) => ({
8157
8430
  commitment,
8158
8431
  filler: storageKey.args[1].toString(),
@@ -8182,9 +8455,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8182
8455
  * Single round-trip but does not include deposit amounts.
8183
8456
  */
8184
8457
  async getBidsViaRpc(commitment) {
8185
- const result = await this.api._rpcCore.provider.send("intents_getBidsForOrder", [
8186
- commitment
8187
- ]);
8458
+ const api = await this.http();
8459
+ const result = await api._rpcCore.provider.send("intents_getBidsForOrder", [commitment]);
8188
8460
  return result.map((entry) => {
8189
8461
  const userOp = decodeUserOpScale(entry.user_op);
8190
8462
  const filler = new Keyring({ type: "sr25519" }).encodeAddress(hexToU8a(entry.filler));
@@ -8196,7 +8468,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8196
8468
  * Slower but works on all nodes and includes deposit amounts.
8197
8469
  */
8198
8470
  async getBidsViaStorage(commitment) {
8199
- const entries = await this.api.query.intentsCoprocessor.bids.entries(commitment);
8471
+ const api = await this.http();
8472
+ const entries = await api.query.intentsCoprocessor.bids.entries(commitment);
8200
8473
  if (entries.length === 0) return [];
8201
8474
  const bidPromises = entries.map(async ([storageKey, depositValue]) => {
8202
8475
  try {
@@ -8204,7 +8477,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8204
8477
  const deposit = BigInt(depositValue.toString());
8205
8478
  const offchainKey = this.buildOffchainBidKey(commitment, filler);
8206
8479
  const offchainKeyHex = u8aToHex(offchainKey);
8207
- const offchainResult = await this.api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8480
+ const offchainResult = await api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8208
8481
  if (!offchainResult || offchainResult.isNone) return null;
8209
8482
  const bidData = offchainResult.unwrap().toHex();
8210
8483
  const decoded = this.decodeBid(bidData);
@@ -8238,13 +8511,12 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8238
8511
  */
8239
8512
  async fetchPhantomOrder(commitment) {
8240
8513
  const key = u8aConcat(OFFCHAIN_PHANTOM_PREFIX, hexToU8a(commitment));
8241
- const result = await this.api.rpc.offchain.localStorageGet("PERSISTENT", u8aToHex(key));
8514
+ const api = await this.http();
8515
+ const result = await api.rpc.offchain.localStorageGet("PERSISTENT", u8aToHex(key));
8242
8516
  if (!result || result.isNone) return null;
8243
8517
  const rawHex = result.unwrap().toHex();
8244
8518
  if (rawHex === "0x" || rawHex === "0x00") return null;
8245
- const placeOrderAbi = IntentGatewayV2_default.ABI.find(
8246
- (item) => item.type === "function" && item.name === "placeOrder"
8247
- );
8519
+ const placeOrderAbi = IntentGatewayV2_default.ABI.find((item) => item.type === "function" && item.name === "placeOrder");
8248
8520
  const orderType = placeOrderAbi?.inputs?.[0];
8249
8521
  if (!orderType) return null;
8250
8522
  const [decoded] = decodeAbiParameters([orderType], rawHex);
@@ -8284,8 +8556,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8284
8556
  * Reads the PhantomOrderRegistered events emitted in a single block.
8285
8557
  */
8286
8558
  async getPhantomOrdersInBlock(blockNumber) {
8287
- const blockHash = await this.api.rpc.chain.getBlockHash(blockNumber);
8288
- const apiAt = await this.api.at(blockHash);
8559
+ const api = await this.http();
8560
+ const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
8561
+ const apiAt = await api.at(blockHash);
8289
8562
  const records = await apiAt.query.system.events();
8290
8563
  const orders = [];
8291
8564
  for (const { event } of records) {
@@ -8306,7 +8579,13 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8306
8579
  return orders;
8307
8580
  }
8308
8581
  /**
8309
- * Polls for newly registered phantom orders, invoking the callback once per order.
8582
+ * Polls for newly registered phantom orders, invoking the callback once per block that carries
8583
+ * any, with all of that block's orders.
8584
+ *
8585
+ * Per block rather than per order because that is how the pallet writes them: one order per
8586
+ * configured chain, all registered in the same `on_initialize`. Delivering them together lets a
8587
+ * caller bid on the whole interval in one extrinsic (see {@link submitPhantomBids}) instead of
8588
+ * one per chain.
8310
8589
  *
8311
8590
  * Each tick reads the current head and scans every block between the last one processed and that
8312
8591
  * head, so the block cursor — not the connection — determines what has been seen. This replaced a
@@ -8319,10 +8598,16 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8319
8598
  * cannot drop them, because the cursor only advances past a block whose events were actually
8320
8599
  * read. Recovery replays the backlog.
8321
8600
  *
8601
+ * Every read here goes over HTTP, never the websocket. Polling is a sequence of independent
8602
+ * one-shot requests with no state to lose between them, which is exactly what a stateless
8603
+ * transport does well: a request either answers or fails loudly on this tick, instead of a
8604
+ * socket that looks alive while delivering nothing. It also means a websocket outage does not
8605
+ * pause phantom bidding at all — the two transports fail independently.
8606
+ *
8322
8607
  * Returns a function that stops polling.
8323
8608
  */
8324
8609
  pollPhantomOrders(callback, options = {}) {
8325
- const { intervalMs = 6e3, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8610
+ const { intervalMs, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8326
8611
  let cursor = null;
8327
8612
  let inFlight = false;
8328
8613
  let stopped = false;
@@ -8330,7 +8615,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8330
8615
  if (inFlight || stopped) return;
8331
8616
  inFlight = true;
8332
8617
  try {
8333
- const head = (await this.api.rpc.chain.getHeader()).number.toNumber();
8618
+ const head = (await (await this.http()).rpc.chain.getHeader()).number.toNumber();
8334
8619
  if (cursor === null) {
8335
8620
  cursor = Math.max(head - 1 - lookbackBlocks, -1);
8336
8621
  }
@@ -8339,7 +8624,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8339
8624
  for (let blockNumber = cursor + 1; blockNumber <= to; blockNumber++) {
8340
8625
  if (stopped) return;
8341
8626
  const orders = await this.getPhantomOrdersInBlock(blockNumber);
8342
- for (const order of orders) callback(order);
8627
+ if (orders.length > 0) callback(orders);
8343
8628
  cursor = blockNumber;
8344
8629
  }
8345
8630
  } catch (err) {
@@ -8349,12 +8634,31 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8349
8634
  }
8350
8635
  };
8351
8636
  void tick();
8352
- const timer = setInterval(() => void tick(), intervalMs);
8637
+ let timer = null;
8638
+ const startTimer = (ms) => {
8639
+ if (stopped) return;
8640
+ timer = setInterval(() => void tick(), ms);
8641
+ };
8642
+ if (intervalMs !== void 0) startTimer(intervalMs);
8643
+ else void this.phantomPollIntervalMs().then(startTimer);
8353
8644
  return () => {
8354
8645
  stopped = true;
8355
- clearInterval(timer);
8646
+ if (timer) clearInterval(timer);
8356
8647
  };
8357
8648
  }
8649
+ /**
8650
+ * The poll cadence for the runtime this instance is connected to: Gargantua polls every block,
8651
+ * everything else every 15s. Falls back to the slower cadence if the runtime cannot be read,
8652
+ * since an unreachable node is the poll's problem to report, not the cadence lookup's.
8653
+ */
8654
+ async phantomPollIntervalMs() {
8655
+ try {
8656
+ const specName = (await this.http()).runtimeVersion.specName.toString();
8657
+ return specName === "gargantua" ? GARGANTUA_PHANTOM_POLL_INTERVAL_MS : PHANTOM_POLL_INTERVAL_MS;
8658
+ } catch {
8659
+ return PHANTOM_POLL_INTERVAL_MS;
8660
+ }
8661
+ }
8358
8662
  };
8359
8663
  var TronChain = class _TronChain {
8360
8664
  constructor(params, evm) {
@@ -15166,6 +15470,12 @@ var CryptoUtils = class _CryptoUtils {
15166
15470
  * signing infrastructure (hardware wallets, MPC/TEE policy engines) instead
15167
15471
  * of an opaque 32-byte digest.
15168
15472
  *
15473
+ * The payload must be a standard self-describing `eth_signTypedData_v4`
15474
+ * payload — `EIP712Domain` listed in `types`, `chainId` as a JSON number —
15475
+ * because some signing backends (e.g. MPC Vault) hash it server-side from
15476
+ * the JSON rather than locally via viem. viem ignores both details when
15477
+ * hashing, so the digest is unchanged for local signers.
15478
+ *
15169
15479
  * @param userOp - The packed UserOperation to sign (signature field ignored).
15170
15480
  * @param entryPoint - Address of the EntryPoint v0.8 contract.
15171
15481
  * @param chainId - Chain ID of the network on which the operation will execute.
@@ -15176,10 +15486,22 @@ var CryptoUtils = class _CryptoUtils {
15176
15486
  domain: {
15177
15487
  name: "ERC4337",
15178
15488
  version: "1",
15179
- chainId,
15489
+ // Runtime number so JSON.stringify emits a canonical v4 numeric chainId for
15490
+ // server-side hashers; viem's uint256 type mapping wants bigint but its
15491
+ // runtime accepts numbers, hence the cast.
15492
+ chainId: Number(chainId),
15180
15493
  verifyingContract: entryPoint
15181
15494
  },
15495
+ // `as const`: viem derives the domain's TYPE from `types.EIP712Domain`, so the
15496
+ // entries must stay string literals — widened `string` fields make viem's
15497
+ // typed-data generics reject the payload at every call site.
15182
15498
  types: {
15499
+ EIP712Domain: [
15500
+ { name: "name", type: "string" },
15501
+ { name: "version", type: "string" },
15502
+ { name: "chainId", type: "uint256" },
15503
+ { name: "verifyingContract", type: "address" }
15504
+ ],
15183
15505
  PackedUserOperation: [
15184
15506
  { name: "sender", type: "address" },
15185
15507
  { name: "nonce", type: "uint256" },
@@ -17043,14 +17365,14 @@ var BidManager = class {
17043
17365
  }
17044
17366
  /**
17045
17367
  * Autopilot bid selection: sorts the given bids by output value, simulates
17046
- * each in order until one passes, then executes that bid. For consumers that
17047
- * do not need custom selection logic.
17368
+ * each in order and attempts execution. Any bid that fails simulation or
17369
+ * execution is skipped once so the next ranked bid can be attempted in the
17370
+ * same round. For consumers that do not need custom selection logic.
17048
17371
  *
17049
17372
  * @param order - The placed order to fill.
17050
17373
  * @param bids - Candidate bids (from {@link buildBids}).
17051
17374
  * @returns A {@link SelectBidResult} for the executed bid.
17052
- * @throws If no valid bids exist, all simulations fail, or the bundler rejects
17053
- * the UserOperation.
17375
+ * @throws If no valid bids exist or every bid fails simulation/execution.
17054
17376
  */
17055
17377
  async selectAndExecuteBest(order, bids) {
17056
17378
  const commitment = order.id;
@@ -17067,22 +17389,34 @@ var BidManager = class {
17067
17389
  throw new Error("No valid bids found");
17068
17390
  }
17069
17391
  console.log(`[BidManager] Simulating ${sortedBids.length} sorted bid(s) to find a valid one`);
17392
+ let simulationFailures = 0;
17393
+ let executionFailures = 0;
17070
17394
  for (let idx = 0; idx < sortedBids.length; idx++) {
17071
17395
  const bid = sortedBids[idx];
17072
17396
  console.log(`[BidManager] Simulating bid ${idx + 1}/${sortedBids.length} from solver=${bid.solverAddress}`);
17073
17397
  try {
17074
17398
  await bid.simulate();
17075
17399
  } catch (err) {
17400
+ simulationFailures += 1;
17076
17401
  console.warn(
17077
17402
  `[BidManager] Bid ${idx + 1} from solver=${bid.solverAddress}: simulation FAILED: ${err instanceof Error ? err.message : String(err)}`
17078
17403
  );
17079
17404
  continue;
17080
17405
  }
17081
17406
  console.log(`[BidManager] Bid ${idx + 1} from solver=${bid.solverAddress}: simulation PASSED`);
17082
- return bid.execute();
17407
+ try {
17408
+ return await bid.execute();
17409
+ } catch (err) {
17410
+ executionFailures += 1;
17411
+ console.warn(
17412
+ `[BidManager] Bid ${idx + 1} from solver=${bid.solverAddress}: execution FAILED: ${err instanceof Error ? err.message : String(err)}; trying next bid`
17413
+ );
17414
+ }
17083
17415
  }
17084
- console.error(`[BidManager] All ${sortedBids.length} bid(s) failed simulation for commitment=${commitment}`);
17085
- throw new Error("No bids passed simulation");
17416
+ console.error(
17417
+ `[BidManager] No executable bids for commitment=${commitment}: ${simulationFailures} simulation failure(s), ${executionFailures} execution failure(s)`
17418
+ );
17419
+ throw new Error("No bids passed simulation and execution");
17086
17420
  }
17087
17421
  /**
17088
17422
  * Sorts a list of bids for the given order by output value.
@@ -17422,6 +17756,10 @@ var BidManager = class {
17422
17756
  }
17423
17757
  };
17424
17758
  var RELAYER_MESSAGE_GAS = 1000000n;
17759
+ var NO_BUNDLER_FILL_GAS_BASE = 700000n;
17760
+ var NO_BUNDLER_FILL_GAS_PER_OUTPUT = 150000n;
17761
+ var NO_BUNDLER_PAYMASTER_VERIFICATION_GAS = 250000n;
17762
+ var NO_BUNDLER_PAYMASTER_POST_OP_GAS = 100000n;
17425
17763
  var GasEstimator = class {
17426
17764
  /**
17427
17765
  * @param ctx - Shared IntentsV2 context providing the source and destination
@@ -17455,8 +17793,10 @@ var GasEstimator = class {
17455
17793
  * headroom. If the bundler is Pimlico, gas prices are refined with
17456
17794
  * `pimlico_getUserOperationGasPrice`.
17457
17795
  *
17458
- * **Fallback path (no bundler):** calls `estimateContractGas` directly on
17459
- * `fillOrder` with state overrides.
17796
+ * **Fallback path (no bundler):** uses a fixed budget
17797
+ * ({@link NO_BUNDLER_FILL_GAS_BASE} plus {@link NO_BUNDLER_FILL_GAS_PER_OUTPUT}
17798
+ * per output leg) — public RPCs don't reliably support estimation with
17799
+ * state overrides.
17460
17800
  *
17461
17801
  * @param params - Parameters including the order to estimate and optional
17462
17802
  * percentage bumps for `maxPriorityFeePerGas` and `maxFeePerGas`.
@@ -17491,14 +17831,14 @@ var GasEstimator = class {
17491
17831
  }
17492
17832
  const isSameChain = souceStateMachineId === destStateMachineId;
17493
17833
  const [stateOverridesResult, crossChainFees] = await Promise.all([
17494
- this.buildStateOverride({
17834
+ this.ctx.bundlerUrl ? this.buildStateOverride({
17495
17835
  accountAddress: solverAccountAddress,
17496
17836
  chain: destStateMachineId,
17497
17837
  outputAssets: assetsForOverrides,
17498
17838
  spenderAddress: intentGatewayV2Address,
17499
17839
  intentGatewayV2Address,
17500
17840
  entryPointAddress
17501
- }),
17841
+ }) : Promise.resolve({ viem: [], bundler: {} }),
17502
17842
  isSameChain ? Promise.resolve({ postRequestFee: 0n, relayerFeeInSourceFeeToken: 0n }) : this.estimateCrossChainFees(
17503
17843
  sourceFeeToken,
17504
17844
  destFeeToken,
@@ -17506,7 +17846,7 @@ var GasEstimator = class {
17506
17846
  orderFeeGasPriceBumpPercent
17507
17847
  )
17508
17848
  ]);
17509
- const { viem: stateOverrides, bundler: bundlerStateOverrides } = stateOverridesResult;
17849
+ const { bundler: bundlerStateOverrides } = stateOverridesResult;
17510
17850
  const fillOptions = {
17511
17851
  relayerFee: crossChainFees.postRequestFee,
17512
17852
  // Always dispatch with the fee token (see the method docs).
@@ -17647,20 +17987,9 @@ var GasEstimator = class {
17647
17987
  console.warn("Bundler gas estimation failed, using fallback values:", e);
17648
17988
  }
17649
17989
  } else {
17650
- try {
17651
- const estimatedGas = await this.ctx.dest.client.estimateContractGas({
17652
- abi: ABI3,
17653
- address: intentGatewayV2Address,
17654
- functionName: "fillOrder",
17655
- args: [transformOrderForContract(order), fillOptions],
17656
- account: solverAccountAddress,
17657
- value: totalNativeValue,
17658
- stateOverride: stateOverrides
17659
- });
17660
- callGasLimit = estimatedGas * 105n / 100n;
17661
- } catch (e) {
17662
- console.warn("fillOrder gas estimation failed, using fallback:", e);
17663
- }
17990
+ callGasLimit = NO_BUNDLER_FILL_GAS_BASE + NO_BUNDLER_FILL_GAS_PER_OUTPUT * BigInt(order.output.assets.length);
17991
+ paymasterVerificationGasLimit = NO_BUNDLER_PAYMASTER_VERIFICATION_GAS;
17992
+ paymasterPostOpGasLimit = NO_BUNDLER_PAYMASTER_POST_OP_GAS;
17664
17993
  }
17665
17994
  const totalGas = callGasLimit + verificationGasLimit + preVerificationGas + paymasterVerificationGasLimit + paymasterPostOpGasLimit;
17666
17995
  const rawTotalGasCostWei = totalGas * maxFeePerGas;
@@ -19190,14 +19519,34 @@ var IntentGateway = class _IntentGateway {
19190
19519
  }
19191
19520
  }
19192
19521
  };
19522
+
19523
+ // src/protocols/intents/phantom-aggregation.ts
19193
19524
  var FILL_ORDER_ABI = IntentGatewayV2_default.ABI;
19194
- var DECLARATION_VERSION = 1;
19195
- var MAX_DECLARED_CHAINS = 255;
19196
- function encodeAcceptedSourceChains(chains2) {
19197
- if (chains2.length > MAX_DECLARED_CHAINS) {
19198
- throw new Error(`Cannot declare more than ${MAX_DECLARED_CHAINS} source chains`);
19525
+ var DECLARATION_V1 = 1;
19526
+ var DECLARATION_V2 = 2;
19527
+ var MAX_DECLARED_ENTRIES = 255;
19528
+ var MAX_TOKEN_ID_BYTES = 32;
19529
+ function tokenIdToBytes(tokenId) {
19530
+ if (tokenId < 0n) throw new Error(`Uniswap V4 tokenId cannot be negative: ${tokenId}`);
19531
+ const bytes = [];
19532
+ let rest = tokenId;
19533
+ while (rest > 0n) {
19534
+ bytes.unshift(Number(rest & 0xffn));
19535
+ rest >>= 8n;
19536
+ }
19537
+ return bytes.length > 0 ? bytes : [0];
19538
+ }
19539
+ function encodePhantomBidDeclaration(declaration) {
19540
+ const chains2 = declaration.acceptedSourceChains ?? [];
19541
+ const positions = declaration.uniswapV4Positions ?? [];
19542
+ if (chains2.length > MAX_DECLARED_ENTRIES) {
19543
+ throw new Error(`Cannot declare more than ${MAX_DECLARED_ENTRIES} source chains`);
19199
19544
  }
19200
- const bytes = [DECLARATION_VERSION, chains2.length];
19545
+ if (positions.length > MAX_DECLARED_ENTRIES) {
19546
+ throw new Error(`Cannot declare more than ${MAX_DECLARED_ENTRIES} Uniswap V4 positions`);
19547
+ }
19548
+ const version = positions.length > 0 ? DECLARATION_V2 : DECLARATION_V1;
19549
+ const bytes = [version, chains2.length];
19201
19550
  for (const chain of chains2) {
19202
19551
  const encoded = stringToU8a(chain);
19203
19552
  if (encoded.length === 0 || encoded.length > 255) {
@@ -19205,25 +19554,59 @@ function encodeAcceptedSourceChains(chains2) {
19205
19554
  }
19206
19555
  bytes.push(encoded.length, ...encoded);
19207
19556
  }
19557
+ if (version === DECLARATION_V2) {
19558
+ bytes.push(positions.length);
19559
+ for (const tokenId of positions) {
19560
+ const encoded = tokenIdToBytes(tokenId);
19561
+ if (encoded.length > MAX_TOKEN_ID_BYTES) {
19562
+ throw new Error(`Uniswap V4 tokenId exceeds uint256: ${tokenId}`);
19563
+ }
19564
+ bytes.push(encoded.length, ...encoded);
19565
+ }
19566
+ }
19208
19567
  return u8aToHex(new Uint8Array(bytes));
19209
19568
  }
19210
- function decodeAcceptedSourceChains(paymasterAndData) {
19211
- if (!paymasterAndData || !isHex$1(paymasterAndData)) return null;
19569
+ function decodePhantomBidDeclaration(paymasterAndData) {
19570
+ const absent = { acceptedSources: null, uniswapV4Positions: [] };
19571
+ if (!paymasterAndData || !isHex$1(paymasterAndData)) return absent;
19212
19572
  const bytes = hexToU8a(paymasterAndData);
19213
- if (bytes.length < 2 || bytes[0] !== DECLARATION_VERSION) return null;
19214
- const count = bytes[1];
19573
+ if (bytes.length < 2) return absent;
19574
+ const version = bytes[0];
19575
+ if (version !== DECLARATION_V1 && version !== DECLARATION_V2) return absent;
19215
19576
  const chains2 = [];
19216
19577
  let offset = 2;
19217
- for (let entry = 0; entry < count; entry++) {
19218
- if (offset >= bytes.length) return null;
19578
+ for (let entry = 0; entry < bytes[1]; entry++) {
19579
+ if (offset >= bytes.length) return absent;
19219
19580
  const length = bytes[offset];
19220
19581
  offset += 1;
19221
- if (length === 0 || offset + length > bytes.length) return null;
19582
+ if (length === 0 || offset + length > bytes.length) return absent;
19222
19583
  chains2.push(u8aToString(bytes.subarray(offset, offset + length)));
19223
19584
  offset += length;
19224
19585
  }
19225
- if (offset !== bytes.length) return null;
19226
- return chains2;
19586
+ const positions = [];
19587
+ if (version === DECLARATION_V2) {
19588
+ if (offset >= bytes.length) return absent;
19589
+ const count = bytes[offset];
19590
+ offset += 1;
19591
+ for (let entry = 0; entry < count; entry++) {
19592
+ if (offset >= bytes.length) return absent;
19593
+ const length = bytes[offset];
19594
+ offset += 1;
19595
+ if (length === 0 || length > MAX_TOKEN_ID_BYTES || offset + length > bytes.length) return absent;
19596
+ let tokenId = 0n;
19597
+ for (const byte of bytes.subarray(offset, offset + length)) tokenId = tokenId << 8n | BigInt(byte);
19598
+ positions.push(tokenId);
19599
+ offset += length;
19600
+ }
19601
+ }
19602
+ if (offset !== bytes.length) return absent;
19603
+ return { acceptedSources: chains2, uniswapV4Positions: positions };
19604
+ }
19605
+ function encodeAcceptedSourceChains(chains2) {
19606
+ return encodePhantomBidDeclaration({ acceptedSourceChains: chains2 });
19607
+ }
19608
+ function decodeAcceptedSourceChains(paymasterAndData) {
19609
+ return decodePhantomBidDeclaration(paymasterAndData).acceptedSources;
19227
19610
  }
19228
19611
  FILL_ORDER_ABI.find(
19229
19612
  (item) => item?.type === "function" && item?.name === "fillOrder"
@@ -23698,6 +24081,6 @@ async function teleportDot(param_) {
23698
24081
  return stream;
23699
24082
  }
23700
24083
 
23701
- 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 };
24084
+ 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 };
23702
24085
  //# sourceMappingURL=index.js.map
23703
24086
  //# sourceMappingURL=index.js.map