@bananapus/nana-sdk-core 2.21.0 → 2.23.0

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.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RelayrPaymentRetryError = exports.RelayrDestinationRevertedError = exports.RelayrPaymentRevertedError = exports.RelayrProofError = exports.FORWARD_REQUEST_TYPES = exports.TRUSTED_FORWARDER_ABI = exports.RELAYR_FORWARDER_DEADLINE_SECONDS = exports.RELAYR_PAYMENT_GAS = exports.RELAYR_NATIVE_TOKEN = exports.RELAYR_PAYMENT_CODE_HASH = exports.RELAYR_PAYMENT_SELECTOR = exports.RELAYR_PAYMENT_ADDRESS = exports.RELAYR_API = void 0;
3
+ exports.MAX_RELAYR_SENT_PAYMENTS = exports.RelayrPaymentRetryError = exports.RelayrDestinationRevertedError = exports.RelayrPaymentRevertedError = exports.RelayrProofError = exports.RELAYR_UUID_RE = exports.FORWARD_REQUEST_TYPES = exports.TRUSTED_FORWARDER_ABI = exports.RELAYR_FORWARDER_DEADLINE_SECONDS = exports.RELAYR_PAYMENT_GAS = exports.RELAYR_NATIVE_TOKEN = exports.RELAYR_PAYMENT_CODE_HASH = exports.RELAYR_PAYMENT_SELECTOR = exports.RELAYR_PAYMENT_ADDRESS = exports.RELAYR_API = void 0;
4
4
  exports.relayrSupportsChain = relayrSupportsChain;
5
5
  exports.relayrSupportsChains = relayrSupportsChains;
6
6
  exports.relayrPaymentChains = relayrPaymentChains;
@@ -23,9 +23,27 @@ exports.requireRelayrPaymentRetry = requireRelayrPaymentRetry;
23
23
  exports.requireRelayrBundleUnpaid = requireRelayrBundleUnpaid;
24
24
  exports.verifyRelayrDestination = verifyRelayrDestination;
25
25
  exports.verifyRelayrDestinations = verifyRelayrDestinations;
26
+ exports.atCanonicalFinalizedBlock = atCanonicalFinalizedBlock;
27
+ exports.relayrSignedRequests = relayrSignedRequests;
28
+ exports.relayrRequestStates = relayrRequestStates;
29
+ exports.relayrRequestsVerdict = relayrRequestsVerdict;
30
+ exports.relayrRequestsDead = relayrRequestsDead;
31
+ exports.relayrDeadlinePassed = relayrDeadlinePassed;
32
+ exports.isRelayrDiscardReason = isRelayrDiscardReason;
33
+ exports.relayrSessionOutcome = relayrSessionOutcome;
34
+ exports.sentRelayrPayment = sentRelayrPayment;
35
+ exports.relayrSentPaymentsSnapshot = relayrSentPaymentsSnapshot;
36
+ exports.relayrRetryOption = relayrRetryOption;
37
+ exports.relayrPaymentAttemptOutcome = relayrPaymentAttemptOutcome;
38
+ exports.requireRelayrRetry = requireRelayrRetry;
39
+ exports.proveSavedRelayrPayment = proveSavedRelayrPayment;
40
+ exports.relayrPaidQuoteOpen = relayrPaidQuoteOpen;
41
+ exports.relayrQuotedOptions = relayrQuotedOptions;
42
+ exports.revertedRelayrQuote = revertedRelayrQuote;
26
43
  const viem_1 = require("viem");
27
44
  const juicebox_js_1 = require("../generated/juicebox.js");
28
45
  const untrusted_js_1 = require("../untrusted.js");
46
+ const contractWrite_js_1 = require("./contractWrite.js");
29
47
  const simulation_js_1 = require("./simulation.js");
30
48
  // Relayr runs a bundle of transactions on several chains for one prepaid
31
49
  // native payment on one of them. Everything its API returns is untrusted:
@@ -84,7 +102,8 @@ const TESTNETS = [11155111, 11155420, 84532, 421614];
84
102
  const PAYMENT_CODE_MAX_BYTES = 2_048;
85
103
  const BUNDLE_READ_TIMEOUT_MS = 15_000;
86
104
  const HTTP_DETAIL_CHARACTERS = 240;
87
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
105
+ /** A Relayr bundle or transaction ID, in lower case. */
106
+ exports.RELAYR_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
88
107
  // RFC 3339 with an explicit offset. A time without one is read in the
89
108
  // machine's timezone, which would make the same quote pass or fail by place.
90
109
  const DEADLINE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/iu;
@@ -94,6 +113,7 @@ const NO_PROOF = "This saved Relayr bundle lacks exact destination proof. Keep i
94
113
  const NOT_IDENTIFIED = "Relayr has not identified every exact destination transaction. Keep checking the original bundle; do not pay again.";
95
114
  const EXPIRED = "This Relayr quote expired. Review the action again for a new quote.";
96
115
  const UNKNOWN_PAYMENT = "Relayr has not said whether this bundle is paid. Do not pay again yet; check it later.";
116
+ const UNNAMED = "Name every payment this session sent for the quote before paying it again.";
97
117
  const UNVERIFIABLE = "Only an authenticated Relayr payment with its transaction hash can be verified.";
98
118
  /**
99
119
  * The chain or Relayr contradicts the expected transaction: this evidence can
@@ -150,15 +170,19 @@ class RelayrPaymentRetryError extends Error {
150
170
  }
151
171
  }
152
172
  exports.RelayrPaymentRetryError = RelayrPaymentRetryError;
153
- /** `error` with `cause` set like a native error cause, but on ES2021 and never enumerable: an RPC error's URL can carry a key. */
154
- function withCause(error, cause) {
155
- Object.defineProperty(error, "cause", {
156
- value: cause,
173
+ /** `target` with `key` set to `value`, writable but never enumerable: an RPC error's URL can carry a key, and no JSON or log may show it. */
174
+ function withHidden(target, key, value) {
175
+ Object.defineProperty(target, key, {
176
+ value,
157
177
  writable: true,
158
178
  enumerable: false,
159
179
  configurable: true,
160
180
  });
161
- return error;
181
+ return target;
182
+ }
183
+ /** `error` with `cause` set like a native error cause, but on ES2021 and never enumerable: an RPC error's URL can carry a key. */
184
+ function withCause(error, cause) {
185
+ return withHidden(error, "cause", cause);
162
186
  }
163
187
  function errorWithCause(message, cause) {
164
188
  return withCause(new Error(message), cause);
@@ -184,7 +208,7 @@ function uuidOf(value) {
184
208
  if (typeof value !== "string")
185
209
  return null;
186
210
  const uuid = value.toLowerCase();
187
- return UUID.test(uuid) ? uuid : null;
211
+ return exports.RELAYR_UUID_RE.test(uuid) ? uuid : null;
188
212
  }
189
213
  function readEntry(entry) {
190
214
  if (!entry || typeof entry !== "object")
@@ -821,7 +845,7 @@ async function verifyRelayrPayment(client, { hash, from, payment, }) {
821
845
  */
822
846
  async function requireRelayrPaymentRetry(client, { hashes, from, payment, }, { fetch: fetchBundle = globalThis.fetch, nowSeconds = Date.now() / 1_000, } = {}) {
823
847
  if (!Array.isArray(hashes) || !hashes.length) {
824
- throw new RelayrPaymentRetryError("Name every payment this session sent for the quote before paying it again.", "invalid");
848
+ throw new RelayrPaymentRetryError(UNNAMED, "invalid");
825
849
  }
826
850
  const reviewed = verifiablePayment(hashes, from, payment);
827
851
  if (!reviewed)
@@ -863,6 +887,11 @@ async function requireRelayrBundleUnpaid(bundleUuid, { fetch: fetchBundle = glob
863
887
  }
864
888
  requireUnpaidBundle(await readBundle(fetchBundle, uuid, () => new RelayrPaymentRetryError(UNKNOWN_PAYMENT, "unknown")));
865
889
  }
890
+ /** Relayr has not run the call: `pending`, in any case, with no destination hash. */
891
+ function relayrRecordPending(record) {
892
+ return (relayrDestinationHash(record) === null &&
893
+ relayrStateIsPending(record?.status?.state));
894
+ }
866
895
  /** {@link requireRelayrBundleUnpaid}'s check of a bundle already read. */
867
896
  function requireUnpaidBundle({ payment_received, transactions, }) {
868
897
  if (payment_received === true) {
@@ -873,8 +902,7 @@ function requireUnpaidBundle({ payment_received, transactions, }) {
873
902
  !transactions.length) {
874
903
  throw new RelayrPaymentRetryError(UNKNOWN_PAYMENT, "unknown");
875
904
  }
876
- if (transactions.some((record) => relayrDestinationHash(record) !== null ||
877
- !relayrStateIsPending(record?.status?.state))) {
905
+ if (transactions.some((record) => !relayrRecordPending(record))) {
878
906
  throw new RelayrPaymentRetryError("Relayr reports a transaction of this bundle as running or run. Do not pay again.", "running");
879
907
  }
880
908
  }
@@ -988,4 +1016,575 @@ async function verifyRelayrDestinations(clientFor, { bindings, records, account,
988
1016
  }
989
1017
  return verified;
990
1018
  }
1019
+ /**
1020
+ * `read` at the chain's finalized block, with that block's timestamp, once
1021
+ * the block at its number still has the same hash after the read. Null while
1022
+ * any of it cannot be read: a node without the finalized tag, an RPC error, a
1023
+ * malformed block, or a block that is no longer canonical.
1024
+ */
1025
+ async function atCanonicalFinalizedBlock(client, read) {
1026
+ try {
1027
+ const { number, hash, timestamp } = await client.getBlock({
1028
+ blockTag: "finalized",
1029
+ });
1030
+ if (typeof number !== "bigint" ||
1031
+ !(0, untrusted_js_1.isBytes32)(hash) ||
1032
+ typeof timestamp !== "bigint") {
1033
+ return null;
1034
+ }
1035
+ const value = await read(number);
1036
+ const canonical = await client.getBlock({ blockNumber: number });
1037
+ return canonical.hash === hash ? { value, timestamp } : null;
1038
+ }
1039
+ catch {
1040
+ return null;
1041
+ }
1042
+ }
1043
+ /** `clientFor(chainId)`, or none when it has none or throws. */
1044
+ function clientOn(clientFor, chainId) {
1045
+ try {
1046
+ return clientFor(chainId);
1047
+ }
1048
+ catch {
1049
+ return undefined;
1050
+ }
1051
+ }
1052
+ /**
1053
+ * The nonce the canonical forwarder on `chainId` expects next from `signer`
1054
+ * at the chain's finalized block, still canonical, with that block's
1055
+ * timestamp. Null while that cannot be read.
1056
+ */
1057
+ async function finalizedForwarderNonce(clientFor, chainId, signer) {
1058
+ const forwarder = forwarderOn(chainId);
1059
+ const reader = forwarder && isAddressLike(signer)
1060
+ ? clientOn(clientFor, chainId)
1061
+ : undefined;
1062
+ if (!forwarder || !reader)
1063
+ return null;
1064
+ const finalized = await atCanonicalFinalizedBlock(reader, (blockNumber) => reader.readContract({
1065
+ address: forwarder,
1066
+ abi: juicebox_js_1.erc2771ForwarderAbi,
1067
+ functionName: "nonces",
1068
+ args: [signer],
1069
+ blockNumber,
1070
+ }));
1071
+ const nonce = finalized && (0, untrusted_js_1.uint256)(finalized.value);
1072
+ return finalized && nonce !== null
1073
+ ? { nonce, timestamp: finalized.timestamp }
1074
+ : null;
1075
+ }
1076
+ /**
1077
+ * The requests a session published, each read from its entry (an `execute`
1078
+ * on its chain's canonical forwarder, as {@link relayrForwardRequest} reads
1079
+ * it), with the nonce it was signed with when `nonces` has one for every
1080
+ * entry. Null when there are none, or one is not such a request: requests
1081
+ * that can't be read can't be classified, so they never count as dead.
1082
+ */
1083
+ function relayrSignedRequests(entries, nonces) {
1084
+ const published = Array.isArray(entries) ? entries : [];
1085
+ const saved = Array.isArray(nonces) && nonces.length === published.length
1086
+ ? nonces
1087
+ : undefined;
1088
+ const requests = published.flatMap((entry, index) => {
1089
+ const request = relayrForwardRequest(entry);
1090
+ return request
1091
+ ? [
1092
+ {
1093
+ chainId: entry.chain,
1094
+ signer: request.from,
1095
+ deadline: request.deadline,
1096
+ ...(saved ? { nonce: saved[index] } : {}),
1097
+ },
1098
+ ]
1099
+ : [];
1100
+ });
1101
+ return published.length && requests.length === published.length
1102
+ ? requests
1103
+ : null;
1104
+ }
1105
+ /**
1106
+ * The one classification of signed forward requests (ruling R114): each at a
1107
+ * canonical finalized block on its chain, read once per chain and signer with
1108
+ * `clientFor(chainId)`. Never throws for a chain it cannot read: its requests
1109
+ * are live.
1110
+ */
1111
+ async function relayrRequestStates(clientFor, requests) {
1112
+ const finalized = new Map();
1113
+ return Promise.all(requests.map(async ({ chainId, signer, deadline, nonce, }) => {
1114
+ const key = `${chainId}:${String(signer).toLowerCase()}`;
1115
+ if (!finalized.has(key)) {
1116
+ finalized.set(key, finalizedForwarderNonce(clientFor, chainId, signer));
1117
+ }
1118
+ const block = await finalized.get(key);
1119
+ // A saved nonce that can't be read leaves the request unknown, and a
1120
+ // deadline that can't be read has not passed.
1121
+ const saved = nonce === undefined ? null : (0, untrusted_js_1.uint256)(nonce);
1122
+ const end = (0, untrusted_js_1.uint256)(deadline);
1123
+ if (block && (nonce === undefined || saved !== null)) {
1124
+ if (saved !== null && block.nonce > saved) {
1125
+ return { live: false, mayHaveRun: true, unused: false };
1126
+ }
1127
+ if (end !== null && end < block.timestamp) {
1128
+ return {
1129
+ live: false,
1130
+ mayHaveRun: saved === null,
1131
+ unused: block.nonce === saved,
1132
+ };
1133
+ }
1134
+ }
1135
+ return { live: true, deadline: Number(deadline) };
1136
+ }));
1137
+ }
1138
+ /**
1139
+ * What `states` allow together. No states are neither run nor unused, so a
1140
+ * session with none holds.
1141
+ */
1142
+ function relayrRequestsVerdict(states) {
1143
+ const deadlines = states.flatMap((state) => state.live ? [state.deadline] : []);
1144
+ const mayHaveRun = states.some((state) => !state.live && state.mayHaveRun);
1145
+ if (deadlines.length) {
1146
+ return { live: true, until: Math.max(...deadlines), mayHaveRun };
1147
+ }
1148
+ return {
1149
+ live: false,
1150
+ mayHaveRun,
1151
+ unused: states.length > 0 && states.every((state) => !state.live && state.unused),
1152
+ };
1153
+ }
1154
+ /**
1155
+ * Ruling R117: whether every request is dead at a canonical finalized block
1156
+ * on its chain, anything unknown counting as live. A saved session reserves
1157
+ * its signers' forwarder nonces on its chains exactly while one of its
1158
+ * requests is live, never by a device clock or a quote's expiry. Requests that
1159
+ * can't be classified (null) or none at all are never dead.
1160
+ */
1161
+ async function relayrRequestsDead(clientFor, requests) {
1162
+ return (Array.isArray(requests) &&
1163
+ requests.length > 0 &&
1164
+ !relayrRequestsVerdict(await relayrRequestStates(clientFor, requests)).live);
1165
+ }
1166
+ /**
1167
+ * Whether the chain's finalized block, still canonical, is past `deadline`
1168
+ * (seconds, as a safe integer, decimal or 0x-hex digits, or a bigint): its
1169
+ * timestamp is later. False while that is unknown, or the deadline can't be
1170
+ * read.
1171
+ */
1172
+ async function relayrDeadlinePassed(client, deadline) {
1173
+ const finalized = await atCanonicalFinalizedBlock(client, async () => undefined);
1174
+ const end = (0, untrusted_js_1.uint256)(deadline);
1175
+ return !!finalized && end !== null && finalized.timestamp > end;
1176
+ }
1177
+ /** Whether `value` is a {@link RelayrDiscardReason}, for a reason read back from storage. */
1178
+ function isRelayrDiscardReason(value) {
1179
+ return value === "ran" || value === "changed" || value === "expired";
1180
+ }
1181
+ /** The transport failures that mean a recheck could not reach the chain. */
1182
+ const UNREACHED = ["HttpRequestError", "TimeoutError", "WebSocketRequestError"];
1183
+ /**
1184
+ * Revert data: whole bytes of hex, at least a 4-byte selector, bare or in
1185
+ * Nethermind's "Reverted 0x…" form.
1186
+ */
1187
+ const REVERT_DATA = /^(?:Reverted )?0x(?:[0-9a-fA-F]{2}){4,}$/u;
1188
+ /**
1189
+ * Whether one error carries revert data, whatever its JSON-RPC code: in its
1190
+ * `data`, in a `data.data` a node nests there, or in the `raw` data of viem's
1191
+ * contract revert. Such an error is the chain answering.
1192
+ */
1193
+ function revertedWithData(link) {
1194
+ const { raw, data } = link;
1195
+ const nested = data !== null && typeof data === "object"
1196
+ ? data.data
1197
+ : undefined;
1198
+ return [raw, data, nested].some((value) => typeof value === "string" && REVERT_DATA.test(value));
1199
+ }
1200
+ /**
1201
+ * Ruling R118: the node could not answer the recheck, so it says nothing
1202
+ * about the project. Within the error's first eight links (its cause chain),
1203
+ * one is a transport failure (HTTP, timeout or WebSocket), a JSON-RPC failure
1204
+ * (viem's `RpcRequestError` or any `RpcError`, such as -32001, -32005 or
1205
+ * -32603), or a contract revert without revert data, as viem reads a bare
1206
+ * revert, transient or not; and no link carries revert data, which on any
1207
+ * code is the chain answering. An app's error that wraps such a failure as
1208
+ * its `cause` reads the same way.
1209
+ */
1210
+ function recheckUnreached(error) {
1211
+ const links = [];
1212
+ for (let link = error; links.length < 8 && link instanceof Error; link = link.cause) {
1213
+ links.push(link);
1214
+ }
1215
+ return (!links.some(revertedWithData) &&
1216
+ links.some((link) => UNREACHED.includes(link.name) ||
1217
+ link instanceof viem_1.RpcRequestError ||
1218
+ link instanceof viem_1.RpcError ||
1219
+ link instanceof viem_1.ContractFunctionRevertedError));
1220
+ }
1221
+ /**
1222
+ * What a session does next from its requests' `verdict` (see
1223
+ * {@link RelayrSessionOutcome}), which was classified before the action's own
1224
+ * recheck, since a request that ran would make the recheck refuse.
1225
+ *
1226
+ * `nonces` must be the saved nonces of exactly the requests that were
1227
+ * classified into `verdict`, in the same order: `refresh` and `re-sign` hand
1228
+ * them back to sign at, and nothing here can check them against the verdict.
1229
+ * Without them (omitted, empty or not a list), a session whose requests are
1230
+ * all dead and unused holds as `reorg-hold`, and is neither discarded nor
1231
+ * signed again.
1232
+ *
1233
+ * `recheck`, the action's proof that its calls still apply, resolves when
1234
+ * they do and throws when they don't; a value it resolves with is never read.
1235
+ * It runs only once every request is dead and unused. Without one, as in an
1236
+ * account view, such a session can be discarded as `expired`. A recheck that
1237
+ * fails because the node could not answer decides nothing. Known limit: a
1238
+ * reorg that drops an earlier forwarded transaction can leave a finalized
1239
+ * nonce below a saved one, and the session holds until the nonce catches up.
1240
+ */
1241
+ async function relayrSessionOutcome(verdict, { nonces, recheck, } = {}) {
1242
+ const saved = Array.isArray(nonces) && nonces.length ? [...nonces] : null;
1243
+ if (verdict.live) {
1244
+ return verdict.mayHaveRun
1245
+ ? { kind: "hold", until: verdict.until }
1246
+ : { kind: "refresh", until: verdict.until, nonces: saved };
1247
+ }
1248
+ if (verdict.mayHaveRun)
1249
+ return { kind: "discard", reason: "ran" };
1250
+ if (!verdict.unused || !saved)
1251
+ return { kind: "reorg-hold" };
1252
+ if (!recheck)
1253
+ return { kind: "discard", reason: "expired" };
1254
+ try {
1255
+ await recheck();
1256
+ }
1257
+ catch (error) {
1258
+ return recheckUnreached(error)
1259
+ ? withHidden({ kind: "unchecked" }, "error", error)
1260
+ : withHidden({ kind: "discard", reason: "changed" }, "error", error);
1261
+ }
1262
+ return { kind: "re-sign", nonces: saved };
1263
+ }
1264
+ /** The payment `details` describes, as a session records it once sent under `hash`. */
1265
+ function sentRelayrPayment(details, hash) {
1266
+ return {
1267
+ ...details,
1268
+ amount: details.amount.toString(),
1269
+ deadline: details.deadline.toString(),
1270
+ hash,
1271
+ };
1272
+ }
1273
+ /** The most payments one quote's journal keeps. No payment is sent beyond them. */
1274
+ exports.MAX_RELAYR_SENT_PAYMENTS = 16;
1275
+ /**
1276
+ * A saved sent payment, read strictly, or null. Its deadline must be the one
1277
+ * its calldata pays until, which the payment's proof binds onchain.
1278
+ */
1279
+ function relayrSentPaymentSnapshot(value) {
1280
+ if (!value || typeof value !== "object")
1281
+ return null;
1282
+ const { hash, chainId, target, calldata, amount, deadline, bundleUuid } = value;
1283
+ return (0, untrusted_js_1.isBytes32)(hash) &&
1284
+ typeof chainId === "number" &&
1285
+ relayrSupportsChain(chainId) &&
1286
+ isStrictAddress(target) &&
1287
+ typeof calldata === "string" &&
1288
+ /^0x[0-9a-f]{136}$/iu.test(calldata) &&
1289
+ typeof amount === "string" &&
1290
+ /^\d{1,78}$/u.test(amount) &&
1291
+ typeof deadline === "string" &&
1292
+ /^\d{1,13}$/u.test(deadline) &&
1293
+ typeof bundleUuid === "string" &&
1294
+ exports.RELAYR_UUID_RE.test(bundleUuid) &&
1295
+ BigInt(deadline) === calldataDeadline(calldata)
1296
+ ? {
1297
+ hash,
1298
+ chainId,
1299
+ target,
1300
+ calldata: calldata,
1301
+ amount,
1302
+ deadline,
1303
+ bundleUuid,
1304
+ }
1305
+ : null;
1306
+ }
1307
+ /**
1308
+ * A saved list of sent payments, read strictly: at most
1309
+ * {@link MAX_RELAYR_SENT_PAYMENTS}, each with only a payment's own fields.
1310
+ * Null when any of it is malformed.
1311
+ */
1312
+ function relayrSentPaymentsSnapshot(values) {
1313
+ if (!Array.isArray(values) || values.length > exports.MAX_RELAYR_SENT_PAYMENTS) {
1314
+ return null;
1315
+ }
1316
+ const payments = values.map(relayrSentPaymentSnapshot);
1317
+ return payments.every((payment) => payment !== null)
1318
+ ? payments
1319
+ : null;
1320
+ }
1321
+ /**
1322
+ * The saved option a quote paid before is paid again with: exactly the one
1323
+ * its latest payment used, on its chain with its calldata (in any case) and
1324
+ * amount. Throws when no option is that one, and when an option on that
1325
+ * chain with that calldata whose amount can't be read comes before it.
1326
+ */
1327
+ function relayrRetryOption(payments, options) {
1328
+ const latest = Array.isArray(payments)
1329
+ ? payments[payments.length - 1]
1330
+ : undefined;
1331
+ let option;
1332
+ if (latest && Array.isArray(options)) {
1333
+ for (const item of options) {
1334
+ if (item.chain !== latest.chainId ||
1335
+ typeof item.calldata !== "string" ||
1336
+ item.calldata.toLowerCase() !== latest.calldata.toLowerCase() ||
1337
+ typeof item.amount !== "string") {
1338
+ continue;
1339
+ }
1340
+ // An earlier twin whose amount can't be read ends the search, refused.
1341
+ const amount = (0, untrusted_js_1.uint256)(item.amount);
1342
+ if (amount === null)
1343
+ break;
1344
+ if (amount === (0, untrusted_js_1.uint256)(latest.amount)) {
1345
+ option = item;
1346
+ break;
1347
+ }
1348
+ }
1349
+ }
1350
+ if (!option) {
1351
+ throw new Error("This Relayr quote cannot be paid again from its saved record. Keep it pending; do not pay again.");
1352
+ }
1353
+ return option;
1354
+ }
1355
+ /**
1356
+ * Where a failed payment attempt leaves its quote: `reverted` when the
1357
+ * payment reverted onchain, or when the wallet declined to pay a quote paid
1358
+ * before, which stays on {@link requireRelayrPaymentRetry}'s rule; `unpaid`
1359
+ * when the wallet declined its first payment; null when nothing is known, and
1360
+ * the journal stays as it is. `sending` is whether the wallet held the
1361
+ * payment, and `paid` whether the quote was paid before.
1362
+ */
1363
+ function relayrPaymentAttemptOutcome(error, { sending, paid }) {
1364
+ if (error instanceof RelayrPaymentRevertedError)
1365
+ return "reverted";
1366
+ if (sending && (0, contractWrite_js_1.isDefiniteWalletRejection)(error)) {
1367
+ return paid ? "reverted" : "unpaid";
1368
+ }
1369
+ return null;
1370
+ }
1371
+ /**
1372
+ * Clear a quote paid before for one more payment, with
1373
+ * {@link requireRelayrPaymentRetry}'s rule for each option its payments used.
1374
+ * `payments` is every payment the session sent for the quote, as mined; those
1375
+ * of one option (its chain, its calldata in any case, and its amount) are
1376
+ * proven together on its chain, with `clientFor`. Before reading anything it
1377
+ * refuses, as `invalid`, an empty list and anything
1378
+ * {@link relayrSentPaymentsSnapshot} refuses, and a payment of another
1379
+ * bundle; a chain without a client is `unknown`. Never pay on an error.
1380
+ */
1381
+ async function requireRelayrRetry(clientFor, { payments, from, bundleUuid, }, options = {}) {
1382
+ if (!Array.isArray(payments) || !payments.length) {
1383
+ throw new RelayrPaymentRetryError(UNNAMED, "invalid");
1384
+ }
1385
+ const sent = relayrSentPaymentsSnapshot(payments);
1386
+ if (!sent)
1387
+ throw new RelayrPaymentRetryError(UNVERIFIABLE, "invalid");
1388
+ if (sent.some((payment) => payment.bundleUuid !== bundleUuid)) {
1389
+ throw new Error("A saved Relayr payment belongs to another bundle. Do not pay again; check the original bundle.");
1390
+ }
1391
+ const byPayment = new Map();
1392
+ for (const payment of sent) {
1393
+ const key = `${payment.chainId}:${payment.calldata.toLowerCase()}:${payment.amount}`;
1394
+ const group = byPayment.get(key) ?? { payment, hashes: [] };
1395
+ group.hashes.push(payment.hash);
1396
+ byPayment.set(key, group);
1397
+ }
1398
+ for (const { payment, hashes } of byPayment.values()) {
1399
+ const client = clientOn(clientFor, payment.chainId);
1400
+ if (!client) {
1401
+ throw new RelayrPaymentRetryError(`No RPC is available for chain ${payment.chainId}. Do not pay again yet; check it later.`, "unknown");
1402
+ }
1403
+ await requireRelayrPaymentRetry(client, { hashes, from, payment }, options);
1404
+ }
1405
+ }
1406
+ /**
1407
+ * Prove a saved session's latest payment when it resumes, on its chain with
1408
+ * `clientFor`. Resolves true once it succeeded onchain, and false while that
1409
+ * can't be proven: no payment, an `account` that is not an address, no client
1410
+ * for its chain, or a read that failed. A canonical revert runs `onReverted`
1411
+ * and is thrown, as is any other {@link RelayrProofError}; the quote then
1412
+ * waits on {@link requireRelayrPaymentRetry}'s rule.
1413
+ */
1414
+ async function proveSavedRelayrPayment(clientFor, payments, account, onReverted) {
1415
+ const latest = Array.isArray(payments)
1416
+ ? payments[payments.length - 1]
1417
+ : undefined;
1418
+ if (!latest || !isStrictAddress(account))
1419
+ return false;
1420
+ const client = clientOn(clientFor, latest.chainId);
1421
+ if (!client)
1422
+ return false;
1423
+ try {
1424
+ await verifyRelayrPayment(client, {
1425
+ hash: latest.hash,
1426
+ from: account,
1427
+ payment: latest,
1428
+ });
1429
+ return true;
1430
+ }
1431
+ catch (error) {
1432
+ if (error instanceof RelayrPaymentRevertedError)
1433
+ onReverted();
1434
+ if (error instanceof RelayrProofError)
1435
+ throw error;
1436
+ return false;
1437
+ }
1438
+ }
1439
+ /**
1440
+ * Whether the quote a session paid can still be paid at `nowMs` (the clock by
1441
+ * default): its latest payment's deadline is more than 15 seconds away, as
1442
+ * {@link quoteExpired} reads it and {@link requireRelayrPaymentRetry}
1443
+ * requires. A deadline or a time that can't be read is closed.
1444
+ */
1445
+ function relayrPaidQuoteOpen(payments, nowMs = Date.now()) {
1446
+ const latest = Array.isArray(payments)
1447
+ ? payments[payments.length - 1]
1448
+ : undefined;
1449
+ const deadline = latest ? (0, untrusted_js_1.uint256)(latest.deadline) : null;
1450
+ return (deadline !== null &&
1451
+ Number.isFinite(nowMs) &&
1452
+ !quoteExpired(deadline, nowMs / 1_000));
1453
+ }
1454
+ /**
1455
+ * Every option of a quote that {@link relayrPaymentDetails} accepts, expired
1456
+ * or not, several on one chain included, with its details: the options a
1457
+ * session keeps, and whose deadlines a release waits out. An option nothing
1458
+ * can authenticate is never paid from, so it is left out.
1459
+ */
1460
+ function relayrQuotedOptions(quote, destinationChainIds) {
1461
+ return (Array.isArray(quote.payment_info) ? quote.payment_info : []).flatMap((option) => {
1462
+ try {
1463
+ return [
1464
+ {
1465
+ option,
1466
+ details: relayrPaymentDetails(option, {
1467
+ bundleUuid: quote.bundle_uuid,
1468
+ destinationChainIds,
1469
+ nowSeconds: 0,
1470
+ }),
1471
+ },
1472
+ ];
1473
+ }
1474
+ catch {
1475
+ return [];
1476
+ }
1477
+ });
1478
+ }
1479
+ /** One uncached read of the bundle, or null when it can't be read, names another bundle or lists no calls. */
1480
+ async function relayrBundleIfNamed(bundleUuid, fetchBundle) {
1481
+ try {
1482
+ const { payment_received, transactions } = await readRelayrBundle(bundleUuid, { fetch: fetchBundle });
1483
+ return Array.isArray(transactions)
1484
+ ? { paymentReceived: payment_received, records: transactions }
1485
+ : null;
1486
+ }
1487
+ catch {
1488
+ return null;
1489
+ }
1490
+ }
1491
+ /**
1492
+ * Nothing can fund the quote any more: every payment it sent is proven
1493
+ * canonically reverted, and the deadline of each of those payments, and of
1494
+ * each option {@link relayrQuotedOptions} keeps, has passed at a canonical
1495
+ * finalized block on its chain. Anything unread is false.
1496
+ */
1497
+ async function relayrQuoteUnfundable(clientFor, { payments, options, bundleUuid, destinationChainIds, account, }) {
1498
+ if (!Array.isArray(payments) ||
1499
+ !payments.length ||
1500
+ !Array.isArray(options) ||
1501
+ !isStrictAddress(account)) {
1502
+ return false;
1503
+ }
1504
+ for (const payment of payments) {
1505
+ const client = clientOn(clientFor, payment.chainId);
1506
+ if (!client)
1507
+ return false;
1508
+ try {
1509
+ await verifyRelayrPayment(client, {
1510
+ hash: payment.hash,
1511
+ from: account,
1512
+ payment,
1513
+ });
1514
+ return false;
1515
+ }
1516
+ catch (error) {
1517
+ if (!(error instanceof RelayrPaymentRevertedError))
1518
+ return false;
1519
+ }
1520
+ // The proof read the calldata's deadline word; the saved one must be it.
1521
+ if ((0, untrusted_js_1.uint256)(payment.deadline) !== calldataDeadline(payment.calldata)) {
1522
+ return false;
1523
+ }
1524
+ }
1525
+ const deadlines = new Map(payments.map((payment) => [
1526
+ `${payment.chainId}:${payment.deadline}`,
1527
+ payment,
1528
+ ]));
1529
+ for (const { details } of relayrQuotedOptions({ bundle_uuid: bundleUuid, payment_info: [...options] }, destinationChainIds)) {
1530
+ deadlines.set(`${details.chainId}:${details.deadline}`, {
1531
+ chainId: details.chainId,
1532
+ deadline: details.deadline.toString(),
1533
+ });
1534
+ }
1535
+ for (const { chainId, deadline } of deadlines.values()) {
1536
+ const client = clientOn(clientFor, chainId);
1537
+ if (!client || !(await relayrDeadlinePassed(client, deadline))) {
1538
+ return false;
1539
+ }
1540
+ }
1541
+ return true;
1542
+ }
1543
+ /**
1544
+ * What a quote whose own payments reverted allows (ruling R104), from one
1545
+ * uncached read of its bundle (with `fetch`, the global one by default):
1546
+ *
1547
+ * - `funded` when Relayr reports a payment, or a call running or run: another
1548
+ * payment funded it, so its destinations are proven, never paid again;
1549
+ * - `payable` while the quote of its latest payment is open at `nowMs` (the
1550
+ * clock, read after the bundle, by default), for
1551
+ * {@link requireRelayrPaymentRetry}'s rule;
1552
+ * - `released` once nothing can fund it: every payment it sent is proven
1553
+ * canonically reverted on its chain (with `clientFor`), every deadline of
1554
+ * those payments and of the options {@link relayrQuotedOptions} keeps
1555
+ * passed at a canonical finalized block, and
1556
+ * {@link requireRelayrBundleUnpaid}, reading the bundle once more, finds it
1557
+ * unpaid with every call pending. Its action then quotes its calls again.
1558
+ *
1559
+ * Throws while an expired quote's release is unproven, and, unless the
1560
+ * bundle is funded, for a payment of another bundle or a time that can't be
1561
+ * read. Resolves with the records Relayr reported, or null when the bundle
1562
+ * could not be read.
1563
+ */
1564
+ async function revertedRelayrQuote(clientFor, quote, { fetch: fetchBundle = globalThis.fetch, nowMs, } = {}) {
1565
+ const bundle = await relayrBundleIfNamed(quote.bundleUuid, fetchBundle);
1566
+ const records = bundle?.records ?? null;
1567
+ if (bundle &&
1568
+ (bundle.paymentReceived === true ||
1569
+ bundle.records.some((record) => !relayrRecordPending(record)))) {
1570
+ return { state: "funded", records };
1571
+ }
1572
+ // The clock is read after the bundle, whose read can take a while.
1573
+ const now = nowMs ?? Date.now();
1574
+ const ownPayments = Array.isArray(quote.payments) &&
1575
+ quote.payments.every((payment) => payment?.bundleUuid === quote.bundleUuid);
1576
+ if (ownPayments && Number.isFinite(now)) {
1577
+ if (relayrPaidQuoteOpen(quote.payments, now)) {
1578
+ return { state: "payable", records };
1579
+ }
1580
+ if (bundle &&
1581
+ (await relayrQuoteUnfundable(clientFor, quote)) &&
1582
+ (await requireRelayrBundleUnpaid(quote.bundleUuid, {
1583
+ fetch: fetchBundle,
1584
+ }).then(() => true, () => false))) {
1585
+ return { state: "released", records };
1586
+ }
1587
+ }
1588
+ throw new Error("This Relayr quote expired after its payment reverted. A new quote needs its deadline final onchain and Relayr to report nothing ran; try again in a few minutes.");
1589
+ }
991
1590
  //# sourceMappingURL=relayr.js.map