@hyperbridge/sdk 2.8.2 → 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';
@@ -2756,18 +2756,25 @@ var chainConfigs = {
2756
2756
  DAI: "0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3",
2757
2757
  USDC: "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d",
2758
2758
  USDT: "0x55d398326f99059ff775485246999027b3197955",
2759
- EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209"
2759
+ EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209",
2760
+ cNGN: "0xa8AEA66B361a8d53e8865c62D142167Af28Af058"
2760
2761
  },
2761
2762
  tokenDecimals: {
2762
2763
  USDC: 18,
2763
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,
2764
2769
  EXT: 18
2765
2770
  },
2766
2771
  tokenStorageSlots: {
2767
2772
  USDT: { balanceSlot: 1, allowanceSlot: 2 },
2768
2773
  USDC: { balanceSlot: 1, allowanceSlot: 2 },
2769
2774
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2770
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2775
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2776
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 }
2777
+ // custom upgradeable layout, as on Base
2771
2778
  },
2772
2779
  addresses: {
2773
2780
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -7799,6 +7806,27 @@ function encodeISMPMessage(message) {
7799
7806
  }
7800
7807
  var OFFCHAIN_BID_PREFIX = new TextEncoder().encode("intents::bid::");
7801
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
+ }
7802
7830
  var BidCodec = Struct({ filler: Bytes(32), user_op: Vector(u8) });
7803
7831
  var PackedUserOperationCodec = Struct({
7804
7832
  sender: Bytes(20),
@@ -7859,6 +7887,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7859
7887
  ownsConnection;
7860
7888
  /** Cached result of whether the node exposes intents_* RPC methods */
7861
7889
  hasIntentsRpc = null;
7890
+ /** The HTTP-backed api, connected on first use. Cleared after a failed attempt so it retries. */
7891
+ httpApi = null;
7862
7892
  // Serialises every extrinsic submission on this instance's substrate account. All submit/retract
7863
7893
  // methods funnel through signAndSendExtrinsic, each using the API's auto-nonce; fired in parallel
7864
7894
  // (bids for orders on different chains, or several phantom orders in one interval) they would grab
@@ -7875,12 +7905,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7875
7905
  static async connect(wsUrl, substratePrivateKey) {
7876
7906
  const api = await ApiPromise.create({
7877
7907
  provider: new WsProvider(wsUrl),
7878
- typesBundle: {
7879
- spec: {
7880
- nexus: { hasher: keccakAsU8a },
7881
- gargantua: { hasher: keccakAsU8a }
7882
- }
7883
- }
7908
+ typesBundle: HYPERBRIDGE_TYPES_BUNDLE
7884
7909
  });
7885
7910
  return new _IntentsCoprocessor(api, substratePrivateKey, true);
7886
7911
  }
@@ -7906,15 +7931,85 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7906
7931
  static fromApi(api, substratePrivateKey) {
7907
7932
  return new _IntentsCoprocessor(api, substratePrivateKey, false);
7908
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
+ }
7909
7952
  /**
7910
7953
  * Disconnects the underlying API connection if this instance owns it.
7911
- * 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.
7912
7956
  */
7913
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
+ }
7914
7964
  if (this.ownsConnection) {
7915
7965
  await this.api.disconnect();
7916
7966
  }
7917
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
+ }
7918
8013
  /**
7919
8014
  * Creates a Substrate keypair from the configured private key.
7920
8015
  * Supports hex seed (with or without 0x), mnemonic phrases, and URI derivation paths (//Alice).
@@ -7939,13 +8034,45 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7939
8034
  * concurrent calls never collide on the substrate account nonce — each extrinsic reaches a block
7940
8035
  * (or is confirmed still pooled and returned as `pending`) before the next is signed; auto-nonce
7941
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.
7942
8041
  */
7943
- async signAndSendExtrinsic(extrinsic, maxRetries = 3, timeoutMs = 3e4) {
7944
- const result = await this.submissionQueue.add(
7945
- () => this.sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs)
7946
- );
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
+ });
7947
8053
  return result ?? { success: false, error: "Submission queue returned no result" };
7948
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
+ }
7949
8076
  /**
7950
8077
  * Signs and sends an extrinsic, handling status updates and errors.
7951
8078
  * Implements retry logic with progressive tip increases for stuck transactions.
@@ -7959,10 +8086,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7959
8086
  */
7960
8087
  async sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs) {
7961
8088
  const keyPair = this.getKeyPair();
7962
- const baseTip = 1000000000n;
7963
8089
  let attempt = 0;
7964
8090
  while (attempt < maxRetries) {
7965
- const currentTip = baseTip * BigInt(2 ** attempt);
8091
+ const currentTip = BASE_TIP * BigInt(2 ** attempt);
7966
8092
  attempt++;
7967
8093
  try {
7968
8094
  const result = await this.sendWithTimeout(extrinsic, keyPair, currentTip, timeoutMs);
@@ -8028,16 +8154,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8028
8154
  if (result.dispatchError && (result.status.isInBlock || result.status.isFinalized)) {
8029
8155
  resolved = true;
8030
8156
  clearTimeout(timeoutId);
8031
- let errorMsg;
8032
- if (result.dispatchError.isModule) {
8033
- const decoded = this.api.registry.findMetaError(result.dispatchError.asModule);
8034
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
8035
- } else {
8036
- errorMsg = `Dispatch error: ${result.dispatchError.toString()}`;
8037
- }
8038
8157
  resolve({
8039
8158
  success: false,
8040
- error: errorMsg
8159
+ error: `Dispatch error: ${this.describeDispatchError(result.dispatchError)}`
8041
8160
  });
8042
8161
  } else if (result.status.isDropped || result.status.isInvalid || result.status.isUsurped || result.status.isFinalityTimeout) {
8043
8162
  resolved = true;
@@ -8055,21 +8174,19 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8055
8174
  if (interrupted) {
8056
8175
  const [indexCodec, dispatchError] = interrupted.event.data;
8057
8176
  if (Number(indexCodec.toString()) === 0) {
8058
- let errorMsg;
8059
- if (dispatchError?.isModule) {
8060
- const decoded = this.api.registry.findMetaError(dispatchError.asModule);
8061
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
8062
- } else {
8063
- errorMsg = `Dispatch error: batch interrupted (${dispatchError?.toString()})`;
8064
- }
8065
- resolve({ success: false, error: errorMsg });
8177
+ resolve({
8178
+ success: false,
8179
+ error: `Dispatch error: ${this.describeDispatchError(dispatchError)}`
8180
+ });
8066
8181
  return;
8067
8182
  }
8068
8183
  }
8069
8184
  resolve({
8070
8185
  success: true,
8071
8186
  blockHash: (result.status.isInBlock ? result.status.asInBlock : result.status.asFinalized).toHex(),
8072
- 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
8073
8190
  });
8074
8191
  }
8075
8192
  }).then((unsub) => {
@@ -8096,8 +8213,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8096
8213
  */
8097
8214
  async submitBid(commitment, userOp) {
8098
8215
  try {
8099
- const extrinsic = this.api.tx.intentsCoprocessor.placeBid(commitment, userOp);
8100
- return await this.signAndSendExtrinsic(extrinsic);
8216
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.placeBid(commitment, userOp));
8101
8217
  } catch (error) {
8102
8218
  return {
8103
8219
  success: false,
@@ -8115,8 +8231,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8115
8231
  */
8116
8232
  async retractBid(commitment) {
8117
8233
  try {
8118
- const extrinsic = this.api.tx.intentsCoprocessor.retractBid(commitment);
8119
- return await this.signAndSendExtrinsic(extrinsic);
8234
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.retractBid(commitment));
8120
8235
  } catch (error) {
8121
8236
  return {
8122
8237
  success: false,
@@ -8146,11 +8261,12 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8146
8261
  */
8147
8262
  async submitBidWithRetraction(retractCommitment, bidCommitment, userOp) {
8148
8263
  try {
8149
- const batch = this.api.tx.utility.batch([
8150
- this.api.tx.intentsCoprocessor.placeBid(bidCommitment, userOp),
8151
- this.api.tx.intentsCoprocessor.retractBid(retractCommitment)
8152
- ]);
8153
- 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
+ );
8154
8270
  } catch (error) {
8155
8271
  return {
8156
8272
  success: false,
@@ -8158,6 +8274,98 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8158
8274
  };
8159
8275
  }
8160
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
+ }
8161
8369
  /**
8162
8370
  * Fetches all bid storage entries for a given order commitment.
8163
8371
  * Returns the on-chain data only (filler addresses and deposits).
@@ -8166,7 +8374,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8166
8374
  * @returns Array of BidStorageEntry objects
8167
8375
  */
8168
8376
  async getBidStorageEntries(commitment) {
8169
- 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);
8170
8379
  return entries.map(([storageKey, depositValue]) => ({
8171
8380
  commitment,
8172
8381
  filler: storageKey.args[1].toString(),
@@ -8196,9 +8405,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8196
8405
  * Single round-trip but does not include deposit amounts.
8197
8406
  */
8198
8407
  async getBidsViaRpc(commitment) {
8199
- const result = await this.api._rpcCore.provider.send("intents_getBidsForOrder", [
8200
- commitment
8201
- ]);
8408
+ const api = await this.http();
8409
+ const result = await api._rpcCore.provider.send("intents_getBidsForOrder", [commitment]);
8202
8410
  return result.map((entry) => {
8203
8411
  const userOp = decodeUserOpScale(entry.user_op);
8204
8412
  const filler = new Keyring({ type: "sr25519" }).encodeAddress(hexToU8a(entry.filler));
@@ -8210,7 +8418,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8210
8418
  * Slower but works on all nodes and includes deposit amounts.
8211
8419
  */
8212
8420
  async getBidsViaStorage(commitment) {
8213
- 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);
8214
8423
  if (entries.length === 0) return [];
8215
8424
  const bidPromises = entries.map(async ([storageKey, depositValue]) => {
8216
8425
  try {
@@ -8218,7 +8427,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8218
8427
  const deposit = BigInt(depositValue.toString());
8219
8428
  const offchainKey = this.buildOffchainBidKey(commitment, filler);
8220
8429
  const offchainKeyHex = u8aToHex(offchainKey);
8221
- const offchainResult = await this.api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8430
+ const offchainResult = await api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8222
8431
  if (!offchainResult || offchainResult.isNone) return null;
8223
8432
  const bidData = offchainResult.unwrap().toHex();
8224
8433
  const decoded = this.decodeBid(bidData);
@@ -8252,7 +8461,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8252
8461
  */
8253
8462
  async fetchPhantomOrder(commitment) {
8254
8463
  const key = u8aConcat(OFFCHAIN_PHANTOM_PREFIX, hexToU8a(commitment));
8255
- 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));
8256
8466
  if (!result || result.isNone) return null;
8257
8467
  const rawHex = result.unwrap().toHex();
8258
8468
  if (rawHex === "0x" || rawHex === "0x00") return null;
@@ -8296,8 +8506,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8296
8506
  * Reads the PhantomOrderRegistered events emitted in a single block.
8297
8507
  */
8298
8508
  async getPhantomOrdersInBlock(blockNumber) {
8299
- const blockHash = await this.api.rpc.chain.getBlockHash(blockNumber);
8300
- 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);
8301
8512
  const records = await apiAt.query.system.events();
8302
8513
  const orders = [];
8303
8514
  for (const { event } of records) {
@@ -8318,7 +8529,13 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8318
8529
  return orders;
8319
8530
  }
8320
8531
  /**
8321
- * 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.
8322
8539
  *
8323
8540
  * Each tick reads the current head and scans every block between the last one processed and that
8324
8541
  * head, so the block cursor — not the connection — determines what has been seen. This replaced a
@@ -8331,10 +8548,16 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8331
8548
  * cannot drop them, because the cursor only advances past a block whose events were actually
8332
8549
  * read. Recovery replays the backlog.
8333
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
+ *
8334
8557
  * Returns a function that stops polling.
8335
8558
  */
8336
8559
  pollPhantomOrders(callback, options = {}) {
8337
- const { intervalMs = 6e3, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8560
+ const { intervalMs, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8338
8561
  let cursor = null;
8339
8562
  let inFlight = false;
8340
8563
  let stopped = false;
@@ -8342,7 +8565,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8342
8565
  if (inFlight || stopped) return;
8343
8566
  inFlight = true;
8344
8567
  try {
8345
- const head = (await this.api.rpc.chain.getHeader()).number.toNumber();
8568
+ const head = (await (await this.http()).rpc.chain.getHeader()).number.toNumber();
8346
8569
  if (cursor === null) {
8347
8570
  cursor = Math.max(head - 1 - lookbackBlocks, -1);
8348
8571
  }
@@ -8351,7 +8574,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8351
8574
  for (let blockNumber = cursor + 1; blockNumber <= to; blockNumber++) {
8352
8575
  if (stopped) return;
8353
8576
  const orders = await this.getPhantomOrdersInBlock(blockNumber);
8354
- for (const order of orders) callback(order);
8577
+ if (orders.length > 0) callback(orders);
8355
8578
  cursor = blockNumber;
8356
8579
  }
8357
8580
  } catch (err) {
@@ -8361,12 +8584,31 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8361
8584
  }
8362
8585
  };
8363
8586
  void tick();
8364
- 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);
8365
8594
  return () => {
8366
8595
  stopped = true;
8367
- clearInterval(timer);
8596
+ if (timer) clearInterval(timer);
8368
8597
  };
8369
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
+ }
8370
8612
  };
8371
8613
  var TronChain = class _TronChain {
8372
8614
  constructor(params, evm) {
@@ -15168,6 +15410,12 @@ var CryptoUtils = class _CryptoUtils {
15168
15410
  * signing infrastructure (hardware wallets, MPC/TEE policy engines) instead
15169
15411
  * of an opaque 32-byte digest.
15170
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
+ *
15171
15419
  * @param userOp - The packed UserOperation to sign (signature field ignored).
15172
15420
  * @param entryPoint - Address of the EntryPoint v0.8 contract.
15173
15421
  * @param chainId - Chain ID of the network on which the operation will execute.
@@ -15178,10 +15426,22 @@ var CryptoUtils = class _CryptoUtils {
15178
15426
  domain: {
15179
15427
  name: "ERC4337",
15180
15428
  version: "1",
15181
- 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),
15182
15433
  verifyingContract: entryPoint
15183
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.
15184
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
+ ],
15185
15445
  PackedUserOperation: [
15186
15446
  { name: "sender", type: "address" },
15187
15447
  { name: "nonce", type: "uint256" },
@@ -19199,14 +19459,34 @@ var IntentGateway = class _IntentGateway {
19199
19459
  }
19200
19460
  }
19201
19461
  };
19462
+
19463
+ // src/protocols/intents/phantom-aggregation.ts
19202
19464
  var FILL_ORDER_ABI = IntentGatewayV2_default.ABI;
19203
- var DECLARATION_VERSION = 1;
19204
- var MAX_DECLARED_CHAINS = 255;
19205
- function encodeAcceptedSourceChains(chains2) {
19206
- if (chains2.length > MAX_DECLARED_CHAINS) {
19207
- 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`);
19484
+ }
19485
+ if (positions.length > MAX_DECLARED_ENTRIES) {
19486
+ throw new Error(`Cannot declare more than ${MAX_DECLARED_ENTRIES} Uniswap V4 positions`);
19208
19487
  }
19209
- const bytes = [DECLARATION_VERSION, chains2.length];
19488
+ const version = positions.length > 0 ? DECLARATION_V2 : DECLARATION_V1;
19489
+ const bytes = [version, chains2.length];
19210
19490
  for (const chain of chains2) {
19211
19491
  const encoded = stringToU8a(chain);
19212
19492
  if (encoded.length === 0 || encoded.length > 255) {
@@ -19214,25 +19494,59 @@ function encodeAcceptedSourceChains(chains2) {
19214
19494
  }
19215
19495
  bytes.push(encoded.length, ...encoded);
19216
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
+ }
19217
19507
  return u8aToHex(new Uint8Array(bytes));
19218
19508
  }
19219
- function decodeAcceptedSourceChains(paymasterAndData) {
19220
- 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;
19221
19512
  const bytes = hexToU8a(paymasterAndData);
19222
- if (bytes.length < 2 || bytes[0] !== DECLARATION_VERSION) return null;
19223
- 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;
19224
19516
  const chains2 = [];
19225
19517
  let offset = 2;
19226
- for (let entry = 0; entry < count; entry++) {
19227
- if (offset >= bytes.length) return null;
19518
+ for (let entry = 0; entry < bytes[1]; entry++) {
19519
+ if (offset >= bytes.length) return absent;
19228
19520
  const length = bytes[offset];
19229
19521
  offset += 1;
19230
- if (length === 0 || offset + length > bytes.length) return null;
19522
+ if (length === 0 || offset + length > bytes.length) return absent;
19231
19523
  chains2.push(u8aToString(bytes.subarray(offset, offset + length)));
19232
19524
  offset += length;
19233
19525
  }
19234
- if (offset !== bytes.length) return null;
19235
- 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;
19236
19550
  }
19237
19551
  FILL_ORDER_ABI.find(
19238
19552
  (item) => item?.type === "function" && item?.name === "fillOrder"
@@ -23707,6 +24021,6 @@ async function teleportDot(param_) {
23707
24021
  return stream;
23708
24022
  }
23709
24023
 
23710
- 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 };
23711
24025
  //# sourceMappingURL=index.js.map
23712
24026
  //# sourceMappingURL=index.js.map