@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.
@@ -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';
@@ -2806,18 +2806,25 @@ var chainConfigs = {
2806
2806
  DAI: "0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3",
2807
2807
  USDC: "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d",
2808
2808
  USDT: "0x55d398326f99059ff775485246999027b3197955",
2809
- EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209"
2809
+ EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209",
2810
+ cNGN: "0xa8AEA66B361a8d53e8865c62D142167Af28Af058"
2810
2811
  },
2811
2812
  tokenDecimals: {
2812
2813
  USDC: 18,
2813
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,
2814
2819
  EXT: 18
2815
2820
  },
2816
2821
  tokenStorageSlots: {
2817
2822
  USDT: { balanceSlot: 1, allowanceSlot: 2 },
2818
2823
  USDC: { balanceSlot: 1, allowanceSlot: 2 },
2819
2824
  WETH: { balanceSlot: 3, allowanceSlot: 4 },
2820
- DAI: { balanceSlot: 0, allowanceSlot: 0 }
2825
+ DAI: { balanceSlot: 0, allowanceSlot: 0 },
2826
+ cNGN: { balanceSlot: 201, allowanceSlot: 202 }
2827
+ // custom upgradeable layout, as on Base
2821
2828
  },
2822
2829
  addresses: {
2823
2830
  IntentGateway: "0xAe041F7B0CB581876832830baeB6a2Aa2a3C9716",
@@ -7849,6 +7856,27 @@ function encodeISMPMessage(message) {
7849
7856
  }
7850
7857
  var OFFCHAIN_BID_PREFIX = new TextEncoder().encode("intents::bid::");
7851
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
+ }
7852
7880
  var BidCodec = Struct({ filler: Bytes(32), user_op: Vector(u8) });
7853
7881
  var PackedUserOperationCodec = Struct({
7854
7882
  sender: Bytes(20),
@@ -7909,6 +7937,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7909
7937
  ownsConnection;
7910
7938
  /** Cached result of whether the node exposes intents_* RPC methods */
7911
7939
  hasIntentsRpc = null;
7940
+ /** The HTTP-backed api, connected on first use. Cleared after a failed attempt so it retries. */
7941
+ httpApi = null;
7912
7942
  // Serialises every extrinsic submission on this instance's substrate account. All submit/retract
7913
7943
  // methods funnel through signAndSendExtrinsic, each using the API's auto-nonce; fired in parallel
7914
7944
  // (bids for orders on different chains, or several phantom orders in one interval) they would grab
@@ -7925,12 +7955,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7925
7955
  static async connect(wsUrl, substratePrivateKey) {
7926
7956
  const api = await ApiPromise.create({
7927
7957
  provider: new WsProvider(wsUrl),
7928
- typesBundle: {
7929
- spec: {
7930
- nexus: { hasher: keccakAsU8a },
7931
- gargantua: { hasher: keccakAsU8a }
7932
- }
7933
- }
7958
+ typesBundle: HYPERBRIDGE_TYPES_BUNDLE
7934
7959
  });
7935
7960
  return new _IntentsCoprocessor(api, substratePrivateKey, true);
7936
7961
  }
@@ -7956,15 +7981,85 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7956
7981
  static fromApi(api, substratePrivateKey) {
7957
7982
  return new _IntentsCoprocessor(api, substratePrivateKey, false);
7958
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
+ }
7959
8002
  /**
7960
8003
  * Disconnects the underlying API connection if this instance owns it.
7961
- * 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.
7962
8006
  */
7963
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
+ }
7964
8014
  if (this.ownsConnection) {
7965
8015
  await this.api.disconnect();
7966
8016
  }
7967
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
+ }
7968
8063
  /**
7969
8064
  * Creates a Substrate keypair from the configured private key.
7970
8065
  * Supports hex seed (with or without 0x), mnemonic phrases, and URI derivation paths (//Alice).
@@ -7989,13 +8084,45 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
7989
8084
  * concurrent calls never collide on the substrate account nonce — each extrinsic reaches a block
7990
8085
  * (or is confirmed still pooled and returned as `pending`) before the next is signed; auto-nonce
7991
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.
7992
8091
  */
7993
- async signAndSendExtrinsic(extrinsic, maxRetries = 3, timeoutMs = 3e4) {
7994
- const result = await this.submissionQueue.add(
7995
- () => this.sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs)
7996
- );
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
+ });
7997
8103
  return result ?? { success: false, error: "Submission queue returned no result" };
7998
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
+ }
7999
8126
  /**
8000
8127
  * Signs and sends an extrinsic, handling status updates and errors.
8001
8128
  * Implements retry logic with progressive tip increases for stuck transactions.
@@ -8009,10 +8136,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8009
8136
  */
8010
8137
  async sendExtrinsicWithRetries(extrinsic, maxRetries, timeoutMs) {
8011
8138
  const keyPair = this.getKeyPair();
8012
- const baseTip = 1000000000n;
8013
8139
  let attempt = 0;
8014
8140
  while (attempt < maxRetries) {
8015
- const currentTip = baseTip * BigInt(2 ** attempt);
8141
+ const currentTip = BASE_TIP * BigInt(2 ** attempt);
8016
8142
  attempt++;
8017
8143
  try {
8018
8144
  const result = await this.sendWithTimeout(extrinsic, keyPair, currentTip, timeoutMs);
@@ -8078,16 +8204,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8078
8204
  if (result.dispatchError && (result.status.isInBlock || result.status.isFinalized)) {
8079
8205
  resolved = true;
8080
8206
  clearTimeout(timeoutId);
8081
- let errorMsg;
8082
- if (result.dispatchError.isModule) {
8083
- const decoded = this.api.registry.findMetaError(result.dispatchError.asModule);
8084
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
8085
- } else {
8086
- errorMsg = `Dispatch error: ${result.dispatchError.toString()}`;
8087
- }
8088
8207
  resolve({
8089
8208
  success: false,
8090
- error: errorMsg
8209
+ error: `Dispatch error: ${this.describeDispatchError(result.dispatchError)}`
8091
8210
  });
8092
8211
  } else if (result.status.isDropped || result.status.isInvalid || result.status.isUsurped || result.status.isFinalityTimeout) {
8093
8212
  resolved = true;
@@ -8105,21 +8224,19 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8105
8224
  if (interrupted) {
8106
8225
  const [indexCodec, dispatchError] = interrupted.event.data;
8107
8226
  if (Number(indexCodec.toString()) === 0) {
8108
- let errorMsg;
8109
- if (dispatchError?.isModule) {
8110
- const decoded = this.api.registry.findMetaError(dispatchError.asModule);
8111
- errorMsg = `Dispatch error: ${decoded.section}::${decoded.name}`;
8112
- } else {
8113
- errorMsg = `Dispatch error: batch interrupted (${dispatchError?.toString()})`;
8114
- }
8115
- resolve({ success: false, error: errorMsg });
8227
+ resolve({
8228
+ success: false,
8229
+ error: `Dispatch error: ${this.describeDispatchError(dispatchError)}`
8230
+ });
8116
8231
  return;
8117
8232
  }
8118
8233
  }
8119
8234
  resolve({
8120
8235
  success: true,
8121
8236
  blockHash: (result.status.isInBlock ? result.status.asInBlock : result.status.asFinalized).toHex(),
8122
- 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
8123
8240
  });
8124
8241
  }
8125
8242
  }).then((unsub) => {
@@ -8146,8 +8263,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8146
8263
  */
8147
8264
  async submitBid(commitment, userOp) {
8148
8265
  try {
8149
- const extrinsic = this.api.tx.intentsCoprocessor.placeBid(commitment, userOp);
8150
- return await this.signAndSendExtrinsic(extrinsic);
8266
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.placeBid(commitment, userOp));
8151
8267
  } catch (error) {
8152
8268
  return {
8153
8269
  success: false,
@@ -8165,8 +8281,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8165
8281
  */
8166
8282
  async retractBid(commitment) {
8167
8283
  try {
8168
- const extrinsic = this.api.tx.intentsCoprocessor.retractBid(commitment);
8169
- return await this.signAndSendExtrinsic(extrinsic);
8284
+ return await this.signAndSendExtrinsic((api) => api.tx.intentsCoprocessor.retractBid(commitment));
8170
8285
  } catch (error) {
8171
8286
  return {
8172
8287
  success: false,
@@ -8196,11 +8311,12 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8196
8311
  */
8197
8312
  async submitBidWithRetraction(retractCommitment, bidCommitment, userOp) {
8198
8313
  try {
8199
- const batch = this.api.tx.utility.batch([
8200
- this.api.tx.intentsCoprocessor.placeBid(bidCommitment, userOp),
8201
- this.api.tx.intentsCoprocessor.retractBid(retractCommitment)
8202
- ]);
8203
- 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
+ );
8204
8320
  } catch (error) {
8205
8321
  return {
8206
8322
  success: false,
@@ -8208,6 +8324,98 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8208
8324
  };
8209
8325
  }
8210
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
+ }
8211
8419
  /**
8212
8420
  * Fetches all bid storage entries for a given order commitment.
8213
8421
  * Returns the on-chain data only (filler addresses and deposits).
@@ -8216,7 +8424,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8216
8424
  * @returns Array of BidStorageEntry objects
8217
8425
  */
8218
8426
  async getBidStorageEntries(commitment) {
8219
- 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);
8220
8429
  return entries.map(([storageKey, depositValue]) => ({
8221
8430
  commitment,
8222
8431
  filler: storageKey.args[1].toString(),
@@ -8246,9 +8455,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8246
8455
  * Single round-trip but does not include deposit amounts.
8247
8456
  */
8248
8457
  async getBidsViaRpc(commitment) {
8249
- const result = await this.api._rpcCore.provider.send("intents_getBidsForOrder", [
8250
- commitment
8251
- ]);
8458
+ const api = await this.http();
8459
+ const result = await api._rpcCore.provider.send("intents_getBidsForOrder", [commitment]);
8252
8460
  return result.map((entry) => {
8253
8461
  const userOp = decodeUserOpScale(entry.user_op);
8254
8462
  const filler = new Keyring({ type: "sr25519" }).encodeAddress(hexToU8a(entry.filler));
@@ -8260,7 +8468,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8260
8468
  * Slower but works on all nodes and includes deposit amounts.
8261
8469
  */
8262
8470
  async getBidsViaStorage(commitment) {
8263
- 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);
8264
8473
  if (entries.length === 0) return [];
8265
8474
  const bidPromises = entries.map(async ([storageKey, depositValue]) => {
8266
8475
  try {
@@ -8268,7 +8477,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8268
8477
  const deposit = BigInt(depositValue.toString());
8269
8478
  const offchainKey = this.buildOffchainBidKey(commitment, filler);
8270
8479
  const offchainKeyHex = u8aToHex(offchainKey);
8271
- const offchainResult = await this.api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8480
+ const offchainResult = await api.rpc.offchain.localStorageGet("PERSISTENT", offchainKeyHex);
8272
8481
  if (!offchainResult || offchainResult.isNone) return null;
8273
8482
  const bidData = offchainResult.unwrap().toHex();
8274
8483
  const decoded = this.decodeBid(bidData);
@@ -8302,7 +8511,8 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8302
8511
  */
8303
8512
  async fetchPhantomOrder(commitment) {
8304
8513
  const key = u8aConcat(OFFCHAIN_PHANTOM_PREFIX, hexToU8a(commitment));
8305
- 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));
8306
8516
  if (!result || result.isNone) return null;
8307
8517
  const rawHex = result.unwrap().toHex();
8308
8518
  if (rawHex === "0x" || rawHex === "0x00") return null;
@@ -8346,8 +8556,9 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8346
8556
  * Reads the PhantomOrderRegistered events emitted in a single block.
8347
8557
  */
8348
8558
  async getPhantomOrdersInBlock(blockNumber) {
8349
- const blockHash = await this.api.rpc.chain.getBlockHash(blockNumber);
8350
- 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);
8351
8562
  const records = await apiAt.query.system.events();
8352
8563
  const orders = [];
8353
8564
  for (const { event } of records) {
@@ -8368,7 +8579,13 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8368
8579
  return orders;
8369
8580
  }
8370
8581
  /**
8371
- * 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.
8372
8589
  *
8373
8590
  * Each tick reads the current head and scans every block between the last one processed and that
8374
8591
  * head, so the block cursor — not the connection — determines what has been seen. This replaced a
@@ -8381,10 +8598,16 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8381
8598
  * cannot drop them, because the cursor only advances past a block whose events were actually
8382
8599
  * read. Recovery replays the backlog.
8383
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
+ *
8384
8607
  * Returns a function that stops polling.
8385
8608
  */
8386
8609
  pollPhantomOrders(callback, options = {}) {
8387
- const { intervalMs = 6e3, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8610
+ const { intervalMs, maxBlocksPerPoll = 500, lookbackBlocks = 0, onError } = options;
8388
8611
  let cursor = null;
8389
8612
  let inFlight = false;
8390
8613
  let stopped = false;
@@ -8392,7 +8615,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8392
8615
  if (inFlight || stopped) return;
8393
8616
  inFlight = true;
8394
8617
  try {
8395
- const head = (await this.api.rpc.chain.getHeader()).number.toNumber();
8618
+ const head = (await (await this.http()).rpc.chain.getHeader()).number.toNumber();
8396
8619
  if (cursor === null) {
8397
8620
  cursor = Math.max(head - 1 - lookbackBlocks, -1);
8398
8621
  }
@@ -8401,7 +8624,7 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8401
8624
  for (let blockNumber = cursor + 1; blockNumber <= to; blockNumber++) {
8402
8625
  if (stopped) return;
8403
8626
  const orders = await this.getPhantomOrdersInBlock(blockNumber);
8404
- for (const order of orders) callback(order);
8627
+ if (orders.length > 0) callback(orders);
8405
8628
  cursor = blockNumber;
8406
8629
  }
8407
8630
  } catch (err) {
@@ -8411,12 +8634,31 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8411
8634
  }
8412
8635
  };
8413
8636
  void tick();
8414
- 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);
8415
8644
  return () => {
8416
8645
  stopped = true;
8417
- clearInterval(timer);
8646
+ if (timer) clearInterval(timer);
8418
8647
  };
8419
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
+ }
8420
8662
  };
8421
8663
  var TronChain = class _TronChain {
8422
8664
  constructor(params, evm) {
@@ -15228,6 +15470,12 @@ var CryptoUtils = class _CryptoUtils {
15228
15470
  * signing infrastructure (hardware wallets, MPC/TEE policy engines) instead
15229
15471
  * of an opaque 32-byte digest.
15230
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
+ *
15231
15479
  * @param userOp - The packed UserOperation to sign (signature field ignored).
15232
15480
  * @param entryPoint - Address of the EntryPoint v0.8 contract.
15233
15481
  * @param chainId - Chain ID of the network on which the operation will execute.
@@ -15238,10 +15486,22 @@ var CryptoUtils = class _CryptoUtils {
15238
15486
  domain: {
15239
15487
  name: "ERC4337",
15240
15488
  version: "1",
15241
- 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),
15242
15493
  verifyingContract: entryPoint
15243
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.
15244
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
+ ],
15245
15505
  PackedUserOperation: [
15246
15506
  { name: "sender", type: "address" },
15247
15507
  { name: "nonce", type: "uint256" },
@@ -19259,14 +19519,34 @@ var IntentGateway = class _IntentGateway {
19259
19519
  }
19260
19520
  }
19261
19521
  };
19522
+
19523
+ // src/protocols/intents/phantom-aggregation.ts
19262
19524
  var FILL_ORDER_ABI = IntentGatewayV2_default.ABI;
19263
- var DECLARATION_VERSION = 1;
19264
- var MAX_DECLARED_CHAINS = 255;
19265
- function encodeAcceptedSourceChains(chains2) {
19266
- if (chains2.length > MAX_DECLARED_CHAINS) {
19267
- 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`);
19544
+ }
19545
+ if (positions.length > MAX_DECLARED_ENTRIES) {
19546
+ throw new Error(`Cannot declare more than ${MAX_DECLARED_ENTRIES} Uniswap V4 positions`);
19268
19547
  }
19269
- const bytes = [DECLARATION_VERSION, chains2.length];
19548
+ const version = positions.length > 0 ? DECLARATION_V2 : DECLARATION_V1;
19549
+ const bytes = [version, chains2.length];
19270
19550
  for (const chain of chains2) {
19271
19551
  const encoded = stringToU8a(chain);
19272
19552
  if (encoded.length === 0 || encoded.length > 255) {
@@ -19274,25 +19554,59 @@ function encodeAcceptedSourceChains(chains2) {
19274
19554
  }
19275
19555
  bytes.push(encoded.length, ...encoded);
19276
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
+ }
19277
19567
  return u8aToHex(new Uint8Array(bytes));
19278
19568
  }
19279
- function decodeAcceptedSourceChains(paymasterAndData) {
19280
- 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;
19281
19572
  const bytes = hexToU8a(paymasterAndData);
19282
- if (bytes.length < 2 || bytes[0] !== DECLARATION_VERSION) return null;
19283
- 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;
19284
19576
  const chains2 = [];
19285
19577
  let offset = 2;
19286
- for (let entry = 0; entry < count; entry++) {
19287
- if (offset >= bytes.length) return null;
19578
+ for (let entry = 0; entry < bytes[1]; entry++) {
19579
+ if (offset >= bytes.length) return absent;
19288
19580
  const length = bytes[offset];
19289
19581
  offset += 1;
19290
- if (length === 0 || offset + length > bytes.length) return null;
19582
+ if (length === 0 || offset + length > bytes.length) return absent;
19291
19583
  chains2.push(u8aToString(bytes.subarray(offset, offset + length)));
19292
19584
  offset += length;
19293
19585
  }
19294
- if (offset !== bytes.length) return null;
19295
- 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;
19296
19610
  }
19297
19611
  FILL_ORDER_ABI.find(
19298
19612
  (item) => item?.type === "function" && item?.name === "fillOrder"
@@ -23767,6 +24081,6 @@ async function teleportDot(param_) {
23767
24081
  return stream;
23768
24082
  }
23769
24083
 
23770
- 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 };
23771
24085
  //# sourceMappingURL=index.js.map
23772
24086
  //# sourceMappingURL=index.js.map