@lifi/sdk-provider-sui 4.2.7 → 4.2.9

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +9 -0
  3. package/dist/esm/actions/getSuiBalance.d.ts.map +1 -1
  4. package/dist/esm/actions/getSuiBalance.js +5 -4
  5. package/dist/esm/actions/getSuiBalance.js.map +1 -1
  6. package/dist/esm/client/suiClient.d.ts +2 -1
  7. package/dist/esm/client/suiClient.d.ts.map +1 -1
  8. package/dist/esm/client/suiClient.js +14 -15
  9. package/dist/esm/client/suiClient.js.map +1 -1
  10. package/dist/esm/core/SuiStepExecutor.d.ts.map +1 -1
  11. package/dist/esm/core/SuiStepExecutor.js +2 -2
  12. package/dist/esm/core/SuiStepExecutor.js.map +1 -1
  13. package/dist/esm/core/constants.d.ts +7 -0
  14. package/dist/esm/core/constants.d.ts.map +1 -0
  15. package/dist/esm/core/constants.js +9 -0
  16. package/dist/esm/core/constants.js.map +1 -0
  17. package/dist/esm/core/tasks/SuiSignAndExecuteTask.d.ts.map +1 -1
  18. package/dist/esm/core/tasks/SuiSignAndExecuteTask.js +54 -7
  19. package/dist/esm/core/tasks/SuiSignAndExecuteTask.js.map +1 -1
  20. package/dist/esm/core/tasks/SuiWaitForTransactionTask.d.ts.map +1 -1
  21. package/dist/esm/core/tasks/SuiWaitForTransactionTask.js +110 -12
  22. package/dist/esm/core/tasks/SuiWaitForTransactionTask.js.map +1 -1
  23. package/dist/esm/core/tasks/helpers/callWithinDeadline.d.ts +19 -0
  24. package/dist/esm/core/tasks/helpers/callWithinDeadline.d.ts.map +1 -0
  25. package/dist/esm/core/tasks/helpers/callWithinDeadline.js +45 -0
  26. package/dist/esm/core/tasks/helpers/callWithinDeadline.js.map +1 -0
  27. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.d.ts +24 -0
  28. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.d.ts.map +1 -0
  29. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.js +141 -0
  30. package/dist/esm/core/tasks/helpers/isSuiTransactionDropped.js.map +1 -0
  31. package/dist/esm/errors/parseSuiErrors.js +5 -4
  32. package/dist/esm/errors/parseSuiErrors.js.map +1 -1
  33. package/dist/esm/utils/getSuiTxLink.d.ts +5 -0
  34. package/dist/esm/utils/getSuiTxLink.d.ts.map +1 -0
  35. package/dist/esm/utils/getSuiTxLink.js +6 -0
  36. package/dist/esm/utils/getSuiTxLink.js.map +1 -0
  37. package/dist/esm/utils/suiSignedTransaction.d.ts +39 -0
  38. package/dist/esm/utils/suiSignedTransaction.d.ts.map +1 -0
  39. package/dist/esm/utils/suiSignedTransaction.js +73 -0
  40. package/dist/esm/utils/suiSignedTransaction.js.map +1 -0
  41. package/dist/esm/version.d.ts +1 -1
  42. package/dist/esm/version.js +1 -1
  43. package/dist/esm/version.js.map +1 -1
  44. package/package.json +3 -3
  45. package/src/actions/getSuiBalance.ts +40 -24
  46. package/src/client/suiClient.ts +21 -18
  47. package/src/core/SuiStepExecutor.ts +9 -3
  48. package/src/core/constants.ts +21 -0
  49. package/src/core/tasks/SuiSignAndExecuteTask.ts +107 -8
  50. package/src/core/tasks/SuiWaitForTransactionTask.ts +249 -22
  51. package/src/core/tasks/helpers/callWithinDeadline.ts +48 -0
  52. package/src/core/tasks/helpers/isSuiTransactionDropped.ts +292 -0
  53. package/src/errors/parseSuiErrors.ts +19 -19
  54. package/src/utils/getSuiTxLink.ts +4 -0
  55. package/src/utils/suiSignedTransaction.ts +109 -0
  56. package/src/version.ts +1 -1
@@ -0,0 +1,45 @@
1
+ //#region src/core/tasks/helpers/callWithinDeadline.ts
2
+ /**
3
+ * Runs one call to one node with its own abort signal and a budget of
4
+ * `timeoutMs`. Past the budget it aborts the call and rejects with a
5
+ * `TimeoutError`, so a node that accepts the connection and never answers
6
+ * cannot hold the caller open. The race does not rely on the transport to
7
+ * honour the abort, and the `finally` clears the timer on every exit.
8
+ *
9
+ * A timeout says nothing about the transaction: it is never a "not found",
10
+ * so the outcome stays unknown.
11
+ *
12
+ * The gRPC `timeout` call option is not enough: the gRPC-web transport only
13
+ * sends it as the `grpc-timeout` header, which a node that never answers
14
+ * ignores. Not `AbortSignal.timeout`: a published SDK should not raise its
15
+ * runtime floor for it.
16
+ */
17
+ async function callWithinDeadline(call, timeoutMs) {
18
+ const controller = new AbortController();
19
+ let timer;
20
+ const deadline = new Promise((_resolve, reject) => {
21
+ timer = setTimeout(() => {
22
+ const error = createTimeoutError(timeoutMs);
23
+ controller.abort(error);
24
+ reject(error);
25
+ }, timeoutMs);
26
+ });
27
+ try {
28
+ return await Promise.race([new Promise((resolve) => resolve(call(controller.signal))), deadline]);
29
+ } finally {
30
+ clearTimeout(timer);
31
+ }
32
+ }
33
+ /**
34
+ * The name makes the gRPC transport report the abort as DEADLINE_EXCEEDED,
35
+ * as for any timeout.
36
+ */
37
+ function createTimeoutError(timeoutMs) {
38
+ const error = /* @__PURE__ */ new Error(`The Sui node did not answer within ${timeoutMs} ms.`);
39
+ error.name = "TimeoutError";
40
+ return error;
41
+ }
42
+ //#endregion
43
+ export { callWithinDeadline };
44
+
45
+ //# sourceMappingURL=callWithinDeadline.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callWithinDeadline.js","names":[],"sources":["../../../../../src/core/tasks/helpers/callWithinDeadline.ts"],"sourcesContent":["/**\n * Runs one call to one node with its own abort signal and a budget of\n * `timeoutMs`. Past the budget it aborts the call and rejects with a\n * `TimeoutError`, so a node that accepts the connection and never answers\n * cannot hold the caller open. The race does not rely on the transport to\n * honour the abort, and the `finally` clears the timer on every exit.\n *\n * A timeout says nothing about the transaction: it is never a \"not found\",\n * so the outcome stays unknown.\n *\n * The gRPC `timeout` call option is not enough: the gRPC-web transport only\n * sends it as the `grpc-timeout` header, which a node that never answers\n * ignores. Not `AbortSignal.timeout`: a published SDK should not raise its\n * runtime floor for it.\n */\nexport async function callWithinDeadline<T>(\n call: (signal: AbortSignal) => PromiseLike<T>,\n timeoutMs: number\n): Promise<T> {\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n const error = createTimeoutError(timeoutMs)\n controller.abort(error)\n reject(error)\n }, timeoutMs)\n })\n try {\n return await Promise.race([\n // A synchronous throw of `call` becomes a rejection too.\n new Promise<T>((resolve) => resolve(call(controller.signal))),\n deadline,\n ])\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * The name makes the gRPC transport report the abort as DEADLINE_EXCEEDED,\n * as for any timeout.\n */\nfunction createTimeoutError(timeoutMs: number): Error {\n const error = new Error(`The Sui node did not answer within ${timeoutMs} ms.`)\n error.name = 'TimeoutError'\n return error\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,eAAsB,mBACpB,MACA,WACY;CACZ,MAAM,aAAa,IAAI,gBAAgB;CACvC,IAAI;CACJ,MAAM,WAAW,IAAI,SAAgB,UAAU,WAAW;EACxD,QAAQ,iBAAiB;GACvB,MAAM,QAAQ,mBAAmB,SAAS;GAC1C,WAAW,MAAM,KAAK;GACtB,OAAO,KAAK;EACd,GAAG,SAAS;CACd,CAAC;CACD,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CAExB,IAAI,SAAY,YAAY,QAAQ,KAAK,WAAW,MAAM,CAAC,CAAC,GAC5D,QACF,CAAC;CACH,UAAU;EACR,aAAa,KAAK;CACpB;AACF;;;;;AAMA,SAAS,mBAAmB,WAA0B;CACpD,MAAM,wBAAQ,IAAI,MAAM,sCAAsC,UAAU,KAAK;CAC7E,MAAM,OAAO;CACb,OAAO;AACT"}
@@ -0,0 +1,24 @@
1
+ import { LiFiStepExtended, SDKClient } from "@lifi/sdk";
2
+ //#region src/core/tasks/helpers/isSuiTransactionDropped.d.ts
3
+ /**
4
+ * True only when the digest can no longer land and no source knows it (see
5
+ * the resume rules in `transactionState.ts`):
6
+ * (a) the resend age cap has passed, so the SDK never sends the bytes again.
7
+ * An unknown signing time never drops, and nor does one in the future:
8
+ * a refused resend does not mean that the cap passed;
9
+ * (b) a node answers "not found" for the digest in the same
10
+ * `BatchGetTransactions` response that finds one canary user transaction
11
+ * from before the earliest landing time and one from after the latest
12
+ * landing time + margin, and no node returns the digest. The canaries
13
+ * prove that this very response covers the whole landing window; a
14
+ * separate coverage request can reach another backend of a load-balanced
15
+ * RPC;
16
+ * (c) the LI.FI status API does not know the digest (veto only).
17
+ *
18
+ * Any lookup error leaves the outcome unknown and returns false. Each call
19
+ * to a node has `SUI_LOOKUP_TIMEOUT_MS` to answer; a node that does not
20
+ * counts as failed, so the next node is asked.
21
+ */
22
+ export declare function isSuiTransactionDropped(client: SDKClient, step: LiFiStepExtended, digest: string): Promise<boolean>;
23
+ //#endregion
24
+ //# sourceMappingURL=isSuiTransactionDropped.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isSuiTransactionDropped.d.ts","names":[],"sources":["../../../../../src/core/tasks/helpers/isSuiTransactionDropped.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgEsB,wBACpB,QAAQ,WACR,MAAM,kBACN,iBACC"}
@@ -0,0 +1,141 @@
1
+ import { callSuiWithRetry } from "../../../client/suiClient.js";
2
+ import { SUI_CANARY_TIP_OFFSET, SUI_HEAD_MARGIN_MS, SUI_LOOKUP_TIMEOUT_MS } from "../../constants.js";
3
+ import { callWithinDeadline } from "./callWithinDeadline.js";
4
+ import { CLOCK_SKEW_MARGIN_MS, MAX_RESEND_AGE_MS, isKnownToStatusApi } from "@lifi/sdk";
5
+ import { GrpcStatusCode, GrpcTypes } from "@mysten/sui/grpc";
6
+ //#region src/core/tasks/helpers/isSuiTransactionDropped.ts
7
+ const MAX_SKIPPED_CHECKPOINTS = 10;
8
+ const PROGRAMMABLE_TRANSACTION = GrpcTypes.TransactionKind_Kind.PROGRAMMABLE_TRANSACTION;
9
+ /**
10
+ * True only when the digest can no longer land and no source knows it (see
11
+ * the resume rules in `transactionState.ts`):
12
+ * (a) the resend age cap has passed, so the SDK never sends the bytes again.
13
+ * An unknown signing time never drops, and nor does one in the future:
14
+ * a refused resend does not mean that the cap passed;
15
+ * (b) a node answers "not found" for the digest in the same
16
+ * `BatchGetTransactions` response that finds one canary user transaction
17
+ * from before the earliest landing time and one from after the latest
18
+ * landing time + margin, and no node returns the digest. The canaries
19
+ * prove that this very response covers the whole landing window; a
20
+ * separate coverage request can reach another backend of a load-balanced
21
+ * RPC;
22
+ * (c) the LI.FI status API does not know the digest (veto only).
23
+ *
24
+ * Any lookup error leaves the outcome unknown and returns false. Each call
25
+ * to a node has `SUI_LOOKUP_TIMEOUT_MS` to answer; a node that does not
26
+ * counts as failed, so the next node is asked.
27
+ */
28
+ async function isSuiTransactionDropped(client, step, digest) {
29
+ const signedAt = step.execution?.signedAt;
30
+ if (signedAt === void 0 || Date.now() - signedAt < MAX_RESEND_AGE_MS) return false;
31
+ try {
32
+ const earliest = signedAt - CLOCK_SKEW_MARGIN_MS;
33
+ const latest = signedAt + MAX_RESEND_AGE_MS + CLOCK_SKEW_MARGIN_MS + SUI_HEAD_MARGIN_MS;
34
+ if (await lookUpWithCanaries(client, digest, await callSuiWithRetry(client, (suiClient) => findCanaries(suiClient, earliest, latest))) !== "not-found") return false;
35
+ return !await isKnownToStatusApi(client, step, digest);
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+ /**
41
+ * Any node may supply the canaries; the proof is in the lookup response.
42
+ * Throws when this node cannot supply them.
43
+ */
44
+ async function findCanaries(suiClient, earliest, latest) {
45
+ const tip = await getCheckpoint(suiClient);
46
+ if (tip.timestampMs <= latest) throw new Error("The chain is not yet past the latest landing time.");
47
+ let afterStart = await getCheckpoint(suiClient, tip.sequenceNumber > 120n ? tip.sequenceNumber - SUI_CANARY_TIP_OFFSET : 0n);
48
+ if (afterStart.timestampMs <= latest) afterStart = tip;
49
+ const after = await findUserTransaction(suiClient, afterStart, 1n, (checkpoint) => checkpoint.timestampMs > latest && checkpoint.sequenceNumber <= tip.sequenceNumber);
50
+ return {
51
+ before: await findUserTransaction(suiClient, await findCheckpointBefore(suiClient, tip, earliest), -1n, (checkpoint) => checkpoint.timestampMs < earliest),
52
+ after
53
+ };
54
+ }
55
+ /** A checkpoint older than `earliest`. Throws if none is found. */
56
+ async function findCheckpointBefore(suiClient, tip, earliest) {
57
+ let distance = BigInt(Math.ceil((tip.timestampMs - earliest) / 200));
58
+ for (let attempt = 0; attempt < 3; attempt++) {
59
+ const sequenceNumber = tip.sequenceNumber > distance ? tip.sequenceNumber - distance : 0n;
60
+ const checkpoint = await getCheckpoint(suiClient, sequenceNumber);
61
+ if (checkpoint.timestampMs < earliest) return checkpoint;
62
+ if (sequenceNumber === 0n) throw new Error("The chain starts after the earliest landing time.");
63
+ distance *= 2n;
64
+ }
65
+ throw new Error("No checkpoint before the earliest landing time was found.");
66
+ }
67
+ /**
68
+ * From `start`, steps one checkpoint at a time in `direction` over
69
+ * checkpoints without a user transaction, and returns the first user
70
+ * transaction digest. Every checkpoint on the way must be `inRange`.
71
+ */
72
+ async function findUserTransaction(suiClient, start, direction, inRange) {
73
+ let checkpoint = start;
74
+ for (let skipped = 0; inRange(checkpoint); skipped++) {
75
+ if (checkpoint.userTransactionDigest) return checkpoint.userTransactionDigest;
76
+ const next = checkpoint.sequenceNumber + direction;
77
+ if (skipped === MAX_SKIPPED_CHECKPOINTS || next < 0n) break;
78
+ checkpoint = await getCheckpoint(suiClient, next);
79
+ }
80
+ throw new Error("No checkpoint in range holds a user transaction.");
81
+ }
82
+ /**
83
+ * The latest checkpoint without `sequenceNumber`. Throws when the sequence
84
+ * number or the timestamp is missing.
85
+ */
86
+ async function getCheckpoint(suiClient, sequenceNumber) {
87
+ const { response } = await callWithinDeadline((abort) => suiClient.ledgerService.getCheckpoint({
88
+ checkpointId: sequenceNumber === void 0 ? { oneofKind: void 0 } : {
89
+ oneofKind: "sequenceNumber",
90
+ sequenceNumber
91
+ },
92
+ readMask: { paths: [
93
+ "sequence_number",
94
+ "summary.timestamp",
95
+ "transactions.digest",
96
+ "transactions.transaction.kind"
97
+ ] }
98
+ }, { abort }), SUI_LOOKUP_TIMEOUT_MS);
99
+ const checkpoint = response.checkpoint;
100
+ const timestamp = checkpoint?.summary?.timestamp;
101
+ const timestampMs = timestamp ? Number(timestamp.seconds) * 1e3 + Math.floor(timestamp.nanos / 1e6) : 0;
102
+ if (checkpoint?.sequenceNumber === void 0 || timestampMs <= 0) throw new Error("The checkpoint has no sequence number or timestamp.");
103
+ return {
104
+ sequenceNumber: checkpoint.sequenceNumber,
105
+ timestampMs,
106
+ userTransactionDigest: checkpoint.transactions.findLast(({ transaction }) => transaction?.kind?.kind === PROGRAMMABLE_TRANSACTION)?.digest
107
+ };
108
+ }
109
+ /**
110
+ * Asks every node with one batch request each. `found` as soon as one returns
111
+ * the digest; `not-found` when none returns it and at least one response
112
+ * finds both canaries but not the digest; `unknown` otherwise.
113
+ */
114
+ async function lookUpWithCanaries(client, digest, canaries) {
115
+ let coveringNotFound = 0;
116
+ try {
117
+ await callSuiWithRetry(client, async (suiClient) => {
118
+ const { response } = await callWithinDeadline((abort) => suiClient.ledgerService.batchGetTransactions({
119
+ digests: [
120
+ digest,
121
+ canaries.before,
122
+ canaries.after
123
+ ],
124
+ readMask: { paths: ["digest"] }
125
+ }, { abort }), SUI_LOOKUP_TIMEOUT_MS);
126
+ const [target, before, after] = response.transactions;
127
+ if (target?.result.oneofKind === "transaction" || response.transactions.some(({ result }) => result.oneofKind === "transaction" && result.transaction.digest === digest)) return;
128
+ const covers = response.transactions.length === 3 && before?.result.oneofKind === "transaction" && before.result.transaction.digest === canaries.before && after?.result.oneofKind === "transaction" && after.result.transaction.digest === canaries.after;
129
+ const notFound = target?.result.oneofKind === "error" && target.result.error.code === GrpcStatusCode.NOT_FOUND;
130
+ if (covers && notFound) coveringNotFound++;
131
+ throw new Error("The node does not return the transaction.");
132
+ });
133
+ return "found";
134
+ } catch {
135
+ return coveringNotFound > 0 ? "not-found" : "unknown";
136
+ }
137
+ }
138
+ //#endregion
139
+ export { isSuiTransactionDropped };
140
+
141
+ //# sourceMappingURL=isSuiTransactionDropped.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isSuiTransactionDropped.js","names":[],"sources":["../../../../../src/core/tasks/helpers/isSuiTransactionDropped.ts"],"sourcesContent":["import {\n CLOCK_SKEW_MARGIN_MS,\n isKnownToStatusApi,\n type LiFiStepExtended,\n MAX_RESEND_AGE_MS,\n type SDKClient,\n} from '@lifi/sdk'\nimport { GrpcStatusCode, GrpcTypes, type SuiGrpcClient } from '@mysten/sui/grpc'\nimport { callSuiWithRetry } from '../../../client/suiClient.js'\nimport {\n SUI_CANARY_TIP_OFFSET,\n SUI_HEAD_MARGIN_MS,\n SUI_LOOKUP_TIMEOUT_MS,\n SUI_MIN_CHECKPOINT_INTERVAL_MS,\n} from '../../constants.js'\nimport { callWithinDeadline } from './callWithinDeadline.js'\n\n// A canary search skips at most this many checkpoints without a user\n// transaction.\nconst MAX_SKIPPED_CHECKPOINTS = 10\n\n// The kind of a user transaction. System transactions (the consensus commit\n// prologue, randomness updates, programmable system transactions, epoch\n// changes) have other kinds.\nconst PROGRAMMABLE_TRANSACTION =\n GrpcTypes.TransactionKind_Kind.PROGRAMMABLE_TRANSACTION\n\ninterface CheckpointInfo {\n sequenceNumber: bigint\n timestampMs: number\n /**\n * The digest of the last user transaction of the checkpoint, the last one\n * whose kind is `PROGRAMMABLE_TRANSACTION`. A transaction without a kind\n * does not count.\n */\n userTransactionDigest?: string\n}\n\ninterface Canaries {\n /** Landed before the earliest landing time. */\n before: string\n /** Landed after the latest landing time + margin. */\n after: string\n}\n\n/**\n * True only when the digest can no longer land and no source knows it (see\n * the resume rules in `transactionState.ts`):\n * (a) the resend age cap has passed, so the SDK never sends the bytes again.\n * An unknown signing time never drops, and nor does one in the future:\n * a refused resend does not mean that the cap passed;\n * (b) a node answers \"not found\" for the digest in the same\n * `BatchGetTransactions` response that finds one canary user transaction\n * from before the earliest landing time and one from after the latest\n * landing time + margin, and no node returns the digest. The canaries\n * prove that this very response covers the whole landing window; a\n * separate coverage request can reach another backend of a load-balanced\n * RPC;\n * (c) the LI.FI status API does not know the digest (veto only).\n *\n * Any lookup error leaves the outcome unknown and returns false. Each call\n * to a node has `SUI_LOOKUP_TIMEOUT_MS` to answer; a node that does not\n * counts as failed, so the next node is asked.\n */\nexport async function isSuiTransactionDropped(\n client: SDKClient,\n step: LiFiStepExtended,\n digest: string\n): Promise<boolean> {\n const signedAt = step.execution?.signedAt\n if (signedAt === undefined || Date.now() - signedAt < MAX_RESEND_AGE_MS) {\n return false\n }\n try {\n // `signedAt` is the local clock; the skew margin widens the window on\n // both sides.\n const earliest = signedAt - CLOCK_SKEW_MARGIN_MS\n const latest =\n signedAt + MAX_RESEND_AGE_MS + CLOCK_SKEW_MARGIN_MS + SUI_HEAD_MARGIN_MS\n // `findCanaries` throws when a node cannot supply them, so that\n // `callSuiWithRetry` asks the next node.\n const canaries = await callSuiWithRetry(client, (suiClient) =>\n findCanaries(suiClient, earliest, latest)\n )\n if ((await lookUpWithCanaries(client, digest, canaries)) !== 'not-found') {\n return false\n }\n return !(await isKnownToStatusApi(client, step, digest))\n } catch {\n return false\n }\n}\n\n/**\n * Any node may supply the canaries; the proof is in the lookup response.\n * Throws when this node cannot supply them.\n */\nasync function findCanaries(\n suiClient: SuiGrpcClient,\n earliest: number,\n latest: number\n): Promise<Canaries> {\n const tip = await getCheckpoint(suiClient)\n if (tip.timestampMs <= latest) {\n throw new Error('The chain is not yet past the latest landing time.')\n }\n\n // Prefer a checkpoint behind the tip; the search moves toward the tip.\n let afterStart = await getCheckpoint(\n suiClient,\n tip.sequenceNumber > SUI_CANARY_TIP_OFFSET\n ? tip.sequenceNumber - SUI_CANARY_TIP_OFFSET\n : 0n\n )\n if (afterStart.timestampMs <= latest) {\n afterStart = tip\n }\n const after = await findUserTransaction(\n suiClient,\n afterStart,\n 1n,\n (checkpoint) =>\n checkpoint.timestampMs > latest &&\n checkpoint.sequenceNumber <= tip.sequenceNumber\n )\n\n const before = await findUserTransaction(\n suiClient,\n await findCheckpointBefore(suiClient, tip, earliest),\n -1n,\n (checkpoint) => checkpoint.timestampMs < earliest\n )\n return { before, after }\n}\n\n/** A checkpoint older than `earliest`. Throws if none is found. */\nasync function findCheckpointBefore(\n suiClient: SuiGrpcClient,\n tip: CheckpointInfo,\n earliest: number\n): Promise<CheckpointInfo> {\n // Estimated with the shortest interval, the guess lands at or before\n // `earliest`; step further back if the interval was even shorter.\n let distance = BigInt(\n Math.ceil((tip.timestampMs - earliest) / SUI_MIN_CHECKPOINT_INTERVAL_MS)\n )\n for (let attempt = 0; attempt < 3; attempt++) {\n const sequenceNumber =\n tip.sequenceNumber > distance ? tip.sequenceNumber - distance : 0n\n const checkpoint = await getCheckpoint(suiClient, sequenceNumber)\n if (checkpoint.timestampMs < earliest) {\n return checkpoint\n }\n if (sequenceNumber === 0n) {\n throw new Error('The chain starts after the earliest landing time.')\n }\n distance *= 2n\n }\n throw new Error('No checkpoint before the earliest landing time was found.')\n}\n\n/**\n * From `start`, steps one checkpoint at a time in `direction` over\n * checkpoints without a user transaction, and returns the first user\n * transaction digest. Every checkpoint on the way must be `inRange`.\n */\nasync function findUserTransaction(\n suiClient: SuiGrpcClient,\n start: CheckpointInfo,\n direction: bigint,\n inRange: (checkpoint: CheckpointInfo) => boolean\n): Promise<string> {\n let checkpoint = start\n for (let skipped = 0; inRange(checkpoint); skipped++) {\n if (checkpoint.userTransactionDigest) {\n return checkpoint.userTransactionDigest\n }\n const next = checkpoint.sequenceNumber + direction\n if (skipped === MAX_SKIPPED_CHECKPOINTS || next < 0n) {\n break\n }\n checkpoint = await getCheckpoint(suiClient, next)\n }\n throw new Error('No checkpoint in range holds a user transaction.')\n}\n\n/**\n * The latest checkpoint without `sequenceNumber`. Throws when the sequence\n * number or the timestamp is missing.\n */\nasync function getCheckpoint(\n suiClient: SuiGrpcClient,\n sequenceNumber?: bigint\n): Promise<CheckpointInfo> {\n const { response } = await callWithinDeadline(\n (abort) =>\n suiClient.ledgerService.getCheckpoint(\n {\n checkpointId:\n sequenceNumber === undefined\n ? { oneofKind: undefined }\n : { oneofKind: 'sequenceNumber', sequenceNumber },\n readMask: {\n paths: [\n 'sequence_number',\n 'summary.timestamp',\n 'transactions.digest',\n 'transactions.transaction.kind',\n ],\n },\n },\n { abort }\n ),\n SUI_LOOKUP_TIMEOUT_MS\n )\n const checkpoint = response.checkpoint\n const timestamp = checkpoint?.summary?.timestamp\n const timestampMs = timestamp\n ? Number(timestamp.seconds) * 1000 + Math.floor(timestamp.nanos / 1e6)\n : 0\n // A zero timestamp is the protobuf default, so it counts as missing.\n if (checkpoint?.sequenceNumber === undefined || timestampMs <= 0) {\n throw new Error('The checkpoint has no sequence number or timestamp.')\n }\n return {\n sequenceNumber: checkpoint.sequenceNumber,\n timestampMs,\n userTransactionDigest: checkpoint.transactions.findLast(\n ({ transaction }) => transaction?.kind?.kind === PROGRAMMABLE_TRANSACTION\n )?.digest,\n }\n}\n\n/**\n * Asks every node with one batch request each. `found` as soon as one returns\n * the digest; `not-found` when none returns it and at least one response\n * finds both canaries but not the digest; `unknown` otherwise.\n */\nasync function lookUpWithCanaries(\n client: SDKClient,\n digest: string,\n canaries: Canaries\n): Promise<'found' | 'not-found' | 'unknown'> {\n let coveringNotFound = 0\n try {\n await callSuiWithRetry(client, async (suiClient) => {\n const { response } = await callWithinDeadline(\n (abort) =>\n suiClient.ledgerService.batchGetTransactions(\n {\n digests: [digest, canaries.before, canaries.after],\n readMask: { paths: ['digest'] },\n },\n { abort }\n ),\n SUI_LOOKUP_TIMEOUT_MS\n )\n const [target, before, after] = response.transactions\n // A node that returns the digest vetoes, in any position.\n if (\n target?.result.oneofKind === 'transaction' ||\n response.transactions.some(\n ({ result }) =>\n result.oneofKind === 'transaction' &&\n result.transaction.digest === digest\n )\n ) {\n return\n }\n // Each canary must sit at its own request position: then the result at\n // the target position belongs to the target, even if a node ever\n // breaks the request order.\n const covers =\n response.transactions.length === 3 &&\n before?.result.oneofKind === 'transaction' &&\n before.result.transaction.digest === canaries.before &&\n after?.result.oneofKind === 'transaction' &&\n after.result.transaction.digest === canaries.after\n const notFound =\n target?.result.oneofKind === 'error' &&\n target.result.error.code === GrpcStatusCode.NOT_FOUND\n if (covers && notFound) {\n coveringNotFound++\n }\n // Throw so that `callSuiWithRetry` asks the next node as well.\n throw new Error('The node does not return the transaction.')\n })\n return 'found'\n } catch {\n return coveringNotFound > 0 ? 'not-found' : 'unknown'\n }\n}\n"],"mappings":"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"}
@@ -10,11 +10,12 @@ const parseSuiErrors = async (e, step, action) => {
10
10
  return new SDKError(baseError, step, action);
11
11
  };
12
12
  const handleSpecificErrors = (e) => {
13
- if (typeof e === "string" ? e.toLowerCase().includes("reject") : e.message?.toLowerCase().includes("reject")) return new TransactionError(LiFiErrorCode.SignatureRejected, e.message, e);
14
- if (e.message?.toLowerCase().includes("transaction") && (e.message?.toLowerCase().includes("failed") || e.message?.toLowerCase().includes("error"))) return new TransactionError(LiFiErrorCode.TransactionFailed, e.message, e);
15
- if (e.message?.includes("simulate") || e.message?.includes("simulation")) return new TransactionError(LiFiErrorCode.TransactionSimulationFailed, e.message, e);
16
13
  if (e instanceof BaseError) return e;
17
- return new UnknownError(e.message || ErrorMessage.UnknownError, e);
14
+ const message = typeof e?.message === "string" ? e.message : "";
15
+ const lowerCaseMessage = message.toLowerCase();
16
+ if (lowerCaseMessage.includes("transaction") && (lowerCaseMessage.includes("failed") || lowerCaseMessage.includes("error"))) return new TransactionError(LiFiErrorCode.TransactionFailed, message, e);
17
+ if (message.includes("simulate") || message.includes("simulation")) return new TransactionError(LiFiErrorCode.TransactionSimulationFailed, message, e);
18
+ return new UnknownError(message || ErrorMessage.UnknownError, e);
18
19
  };
19
20
  //#endregion
20
21
  export { parseSuiErrors };
@@ -1 +1 @@
1
- {"version":3,"file":"parseSuiErrors.js","names":[],"sources":["../../../src/errors/parseSuiErrors.ts"],"sourcesContent":["import {\n BaseError,\n ErrorMessage,\n type ExecutionAction,\n LiFiErrorCode,\n type LiFiStep,\n SDKError,\n TransactionError,\n UnknownError,\n} from '@lifi/sdk'\n\nexport const parseSuiErrors = async (\n e: Error,\n step?: LiFiStep,\n action?: ExecutionAction\n): Promise<SDKError> => {\n if (e instanceof SDKError) {\n e.step = e.step ?? step\n e.action = e.action ?? action\n return e\n }\n\n const baseError = handleSpecificErrors(e)\n\n return new SDKError(baseError, step, action)\n}\n\nconst handleSpecificErrors = (e: any) => {\n const isRejection =\n typeof e === 'string'\n ? e.toLowerCase().includes('reject')\n : e.message?.toLowerCase().includes('reject')\n\n if (isRejection) {\n return new TransactionError(LiFiErrorCode.SignatureRejected, e.message, e)\n }\n\n if (\n e.message?.toLowerCase().includes('transaction') &&\n (e.message?.toLowerCase().includes('failed') ||\n e.message?.toLowerCase().includes('error'))\n ) {\n return new TransactionError(LiFiErrorCode.TransactionFailed, e.message, e)\n }\n\n if (e.message?.includes('simulate') || e.message?.includes('simulation')) {\n return new TransactionError(\n LiFiErrorCode.TransactionSimulationFailed,\n e.message,\n e\n )\n }\n\n if (e instanceof BaseError) {\n return e\n }\n\n return new UnknownError(e.message || ErrorMessage.UnknownError, e)\n}\n"],"mappings":";;AAWA,MAAa,iBAAiB,OAC5B,GACA,MACA,WACsB;CACtB,IAAI,aAAa,UAAU;EACzB,EAAE,OAAO,EAAE,QAAQ;EACnB,EAAE,SAAS,EAAE,UAAU;EACvB,OAAO;CACT;CAEA,MAAM,YAAY,qBAAqB,CAAC;CAExC,OAAO,IAAI,SAAS,WAAW,MAAM,MAAM;AAC7C;AAEA,MAAM,wBAAwB,MAAW;CAMvC,IAJE,OAAO,MAAM,WACT,EAAE,YAAY,CAAC,CAAC,SAAS,QAAQ,IACjC,EAAE,SAAS,YAAY,CAAC,CAAC,SAAS,QAAQ,GAG9C,OAAO,IAAI,iBAAiB,cAAc,mBAAmB,EAAE,SAAS,CAAC;CAG3E,IACE,EAAE,SAAS,YAAY,CAAC,CAAC,SAAS,aAAa,MAC9C,EAAE,SAAS,YAAY,CAAC,CAAC,SAAS,QAAQ,KACzC,EAAE,SAAS,YAAY,CAAC,CAAC,SAAS,OAAO,IAE3C,OAAO,IAAI,iBAAiB,cAAc,mBAAmB,EAAE,SAAS,CAAC;CAG3E,IAAI,EAAE,SAAS,SAAS,UAAU,KAAK,EAAE,SAAS,SAAS,YAAY,GACrE,OAAO,IAAI,iBACT,cAAc,6BACd,EAAE,SACF,CACF;CAGF,IAAI,aAAa,WACf,OAAO;CAGT,OAAO,IAAI,aAAa,EAAE,WAAW,aAAa,cAAc,CAAC;AACnE"}
1
+ {"version":3,"file":"parseSuiErrors.js","names":[],"sources":["../../../src/errors/parseSuiErrors.ts"],"sourcesContent":["import {\n BaseError,\n ErrorMessage,\n type ExecutionAction,\n LiFiErrorCode,\n type LiFiStep,\n SDKError,\n TransactionError,\n UnknownError,\n} from '@lifi/sdk'\n\nexport const parseSuiErrors = async (\n e: Error,\n step?: LiFiStep,\n action?: ExecutionAction\n): Promise<SDKError> => {\n if (e instanceof SDKError) {\n e.step = e.step ?? step\n e.action = e.action ?? action\n return e\n }\n\n const baseError = handleSpecificErrors(e)\n\n return new SDKError(baseError, step, action)\n}\n\nconst handleSpecificErrors = (e: any): BaseError => {\n // A code the SDK set on purpose wins over message matching. A wallet\n // rejection is tagged where it happens (SuiSignAndExecuteTask), so \"reject\"\n // is not read here: a node or RPC message that says \"reject\" is not the\n // user's.\n if (e instanceof BaseError) {\n return e\n }\n\n // `e` can be any thrown value: also `undefined`, `null`, a string, or an\n // object whose `message` is not a string. A TypeError here would escape the\n // catch of the step executor.\n const message: string = typeof e?.message === 'string' ? e.message : ''\n const lowerCaseMessage = message.toLowerCase()\n\n if (\n lowerCaseMessage.includes('transaction') &&\n (lowerCaseMessage.includes('failed') || lowerCaseMessage.includes('error'))\n ) {\n return new TransactionError(LiFiErrorCode.TransactionFailed, message, e)\n }\n\n if (message.includes('simulate') || message.includes('simulation')) {\n return new TransactionError(\n LiFiErrorCode.TransactionSimulationFailed,\n message,\n e\n )\n }\n\n return new UnknownError(message || ErrorMessage.UnknownError, e)\n}\n"],"mappings":";;AAWA,MAAa,iBAAiB,OAC5B,GACA,MACA,WACsB;CACtB,IAAI,aAAa,UAAU;EACzB,EAAE,OAAO,EAAE,QAAQ;EACnB,EAAE,SAAS,EAAE,UAAU;EACvB,OAAO;CACT;CAEA,MAAM,YAAY,qBAAqB,CAAC;CAExC,OAAO,IAAI,SAAS,WAAW,MAAM,MAAM;AAC7C;AAEA,MAAM,wBAAwB,MAAsB;CAKlD,IAAI,aAAa,WACf,OAAO;CAMT,MAAM,UAAkB,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU;CACrE,MAAM,mBAAmB,QAAQ,YAAY;CAE7C,IACE,iBAAiB,SAAS,aAAa,MACtC,iBAAiB,SAAS,QAAQ,KAAK,iBAAiB,SAAS,OAAO,IAEzE,OAAO,IAAI,iBAAiB,cAAc,mBAAmB,SAAS,CAAC;CAGzE,IAAI,QAAQ,SAAS,UAAU,KAAK,QAAQ,SAAS,YAAY,GAC/D,OAAO,IAAI,iBACT,cAAc,6BACd,SACA,CACF;CAGF,OAAO,IAAI,aAAa,WAAW,aAAa,cAAc,CAAC;AACjE"}
@@ -0,0 +1,5 @@
1
+ import { ExtendedChain } from "@lifi/sdk";
2
+ //#region src/utils/getSuiTxLink.d.ts
3
+ export declare const getSuiTxLink: (chain: ExtendedChain, digest: string) => string;
4
+ //#endregion
5
+ //# sourceMappingURL=getSuiTxLink.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getSuiTxLink.d.ts","names":[],"sources":["../../../src/utils/getSuiTxLink.ts"],"mappings":";;qBAEa,eAAgB,OAAO,eAAe"}
@@ -0,0 +1,6 @@
1
+ //#region src/utils/getSuiTxLink.ts
2
+ const getSuiTxLink = (chain, digest) => `${chain.metamask.blockExplorerUrls[0]}txblock/${digest}`;
3
+ //#endregion
4
+ export { getSuiTxLink };
5
+
6
+ //# sourceMappingURL=getSuiTxLink.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getSuiTxLink.js","names":[],"sources":["../../../src/utils/getSuiTxLink.ts"],"sourcesContent":["import type { ExtendedChain } from '@lifi/sdk'\n\nexport const getSuiTxLink = (chain: ExtendedChain, digest: string): string =>\n `${chain.metamask.blockExplorerUrls[0]}txblock/${digest}`\n"],"mappings":";AAEA,MAAa,gBAAgB,OAAsB,WACjD,GAAG,MAAM,SAAS,kBAAkB,GAAG,UAAU"}
@@ -0,0 +1,39 @@
1
+ //#region src/utils/suiSignedTransaction.d.ts
2
+ export interface SuiSignedTransaction {
3
+ /** The BCS `TransactionData` bytes that were signed. */
4
+ bytes: Uint8Array;
5
+ /** The serialized signature returned by `signer.signTransaction`. */
6
+ signature: string;
7
+ /** The transaction digest, derived from `bytes`. */
8
+ digest: string;
9
+ }
10
+ /**
11
+ * Reads a signed transaction back from `ExecutionAction.txHex`
12
+ * (JSON `{ bytes: base64, signature }`).
13
+ *
14
+ * Returns `undefined` unless the bytes decode as a `TransactionData` and the
15
+ * signature decodes as non-empty base64, so the digest and the re-execution
16
+ * both work.
17
+ */
18
+ export declare function parseSuiSignedTransaction(txHex: string): SuiSignedTransaction | undefined;
19
+ /**
20
+ * Verifies that `signature` signs `bytes` and that the signer is the sender
21
+ * of the transaction, so stored bytes that were changed after signing are
22
+ * detected.
23
+ *
24
+ * Resolves `false` only for a definite failure: the bytes have no sender, or
25
+ * the signature is malformed, is not valid for the bytes, or is not the
26
+ * sender's. Rejects when the verification cannot run, so that such a failure
27
+ * never counts as damaged bytes. A well-formed zkLogin signature, also as a
28
+ * multisig member, needs a client to verify, so it rejects here.
29
+ */
30
+ export declare function verifySuiSignedTransaction(transaction: SuiSignedTransaction): Promise<boolean>;
31
+ /**
32
+ * Serializes signed transaction bytes for `ExecutionAction.txHex`.
33
+ *
34
+ * Returns `undefined` when the result would not read back with
35
+ * `parseSuiSignedTransaction`, so a stored value is always usable on resume.
36
+ */
37
+ export declare function serializeSuiSignedTransaction(bytes: Uint8Array, signature: string): string | undefined;
38
+ //#endregion
39
+ //# sourceMappingURL=suiSignedTransaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suiSignedTransaction.d.ts","names":[],"sources":["../../../src/utils/suiSignedTransaction.ts"],"mappings":";iBAKiB;;EAEf,OAAO;;EAEP;;EAEA;;;;;;;;;;wBAWc,0BACd,gBACC;;;;;;;;;;;;wBAuDmB,2BACpB,aAAa,uBACZ;;;;;;;wBAqBa,8BACd,OAAO,YACP"}
@@ -0,0 +1,73 @@
1
+ import { fromBase64, toBase64 } from "@mysten/sui/utils";
2
+ import { TransactionDataBuilder } from "@mysten/sui/transactions";
3
+ import { bcs } from "@mysten/sui/bcs";
4
+ import { isValidTransactionSignature } from "@mysten/sui/verify";
5
+ //#region src/utils/suiSignedTransaction.ts
6
+ /**
7
+ * Reads a signed transaction back from `ExecutionAction.txHex`
8
+ * (JSON `{ bytes: base64, signature }`).
9
+ *
10
+ * Returns `undefined` unless the bytes decode as a `TransactionData` and the
11
+ * signature decodes as non-empty base64, so the digest and the re-execution
12
+ * both work.
13
+ */
14
+ function parseSuiSignedTransaction(txHex) {
15
+ try {
16
+ const { bytes, signature } = JSON.parse(txHex);
17
+ if (typeof bytes !== "string" || typeof signature !== "string") return;
18
+ const transactionBytes = fromBase64(bytes);
19
+ if (!transactionBytes.length || !fromBase64(signature).length) return;
20
+ TransactionDataBuilder.fromBytes(transactionBytes);
21
+ if (!isCanonicalTransactionData(transactionBytes)) return;
22
+ return {
23
+ bytes: transactionBytes,
24
+ signature,
25
+ digest: TransactionDataBuilder.getDigestFromBytes(transactionBytes)
26
+ };
27
+ } catch {
28
+ return;
29
+ }
30
+ }
31
+ /** Whether the canonical BCS encoding of the parsed bytes is exactly `bytes`. */
32
+ function isCanonicalTransactionData(bytes) {
33
+ const canonical = bcs.TransactionData.serialize(bcs.TransactionData.parse(bytes)).toBytes();
34
+ return canonical.length === bytes.length && canonical.every((byte, index) => byte === bytes[index]);
35
+ }
36
+ /**
37
+ * Verifies that `signature` signs `bytes` and that the signer is the sender
38
+ * of the transaction, so stored bytes that were changed after signing are
39
+ * detected.
40
+ *
41
+ * Resolves `false` only for a definite failure: the bytes have no sender, or
42
+ * the signature is malformed, is not valid for the bytes, or is not the
43
+ * sender's. Rejects when the verification cannot run, so that such a failure
44
+ * never counts as damaged bytes. A well-formed zkLogin signature, also as a
45
+ * multisig member, needs a client to verify, so it rejects here.
46
+ */
47
+ async function verifySuiSignedTransaction(transaction) {
48
+ let sender;
49
+ try {
50
+ sender = TransactionDataBuilder.fromBytes(transaction.bytes).sender;
51
+ } catch {
52
+ return false;
53
+ }
54
+ if (!sender) return false;
55
+ return isValidTransactionSignature(transaction.bytes, transaction.signature, { address: sender });
56
+ }
57
+ /**
58
+ * Serializes signed transaction bytes for `ExecutionAction.txHex`.
59
+ *
60
+ * Returns `undefined` when the result would not read back with
61
+ * `parseSuiSignedTransaction`, so a stored value is always usable on resume.
62
+ */
63
+ function serializeSuiSignedTransaction(bytes, signature) {
64
+ const txHex = JSON.stringify({
65
+ bytes: toBase64(bytes),
66
+ signature
67
+ });
68
+ return parseSuiSignedTransaction(txHex) ? txHex : void 0;
69
+ }
70
+ //#endregion
71
+ export { parseSuiSignedTransaction, serializeSuiSignedTransaction, verifySuiSignedTransaction };
72
+
73
+ //# sourceMappingURL=suiSignedTransaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suiSignedTransaction.js","names":[],"sources":["../../../src/utils/suiSignedTransaction.ts"],"sourcesContent":["import { bcs } from '@mysten/sui/bcs'\nimport { TransactionDataBuilder } from '@mysten/sui/transactions'\nimport { fromBase64, toBase64 } from '@mysten/sui/utils'\nimport { isValidTransactionSignature } from '@mysten/sui/verify'\n\nexport interface SuiSignedTransaction {\n /** The BCS `TransactionData` bytes that were signed. */\n bytes: Uint8Array\n /** The serialized signature returned by `signer.signTransaction`. */\n signature: string\n /** The transaction digest, derived from `bytes`. */\n digest: string\n}\n\n/**\n * Reads a signed transaction back from `ExecutionAction.txHex`\n * (JSON `{ bytes: base64, signature }`).\n *\n * Returns `undefined` unless the bytes decode as a `TransactionData` and the\n * signature decodes as non-empty base64, so the digest and the re-execution\n * both work.\n */\nexport function parseSuiSignedTransaction(\n txHex: string\n): SuiSignedTransaction | undefined {\n try {\n const { bytes, signature } = JSON.parse(txHex) as {\n bytes?: unknown\n signature?: unknown\n }\n if (typeof bytes !== 'string' || typeof signature !== 'string') {\n return undefined\n }\n const transactionBytes = fromBase64(bytes)\n // The gRPC client decodes the signature before it sends, so a signature\n // that is not base64 never reaches the chain. `fromBase64('')` is an\n // empty array, not an error.\n if (!transactionBytes.length || !fromBase64(signature).length) {\n return undefined\n }\n // Throws on anything that is not a `TransactionData`.\n TransactionDataBuilder.fromBytes(transactionBytes)\n // `fromBytes` reads a `TransactionData` prefix and ignores the bytes after\n // it, which still change the digest.\n if (!isCanonicalTransactionData(transactionBytes)) {\n return undefined\n }\n return {\n bytes: transactionBytes,\n signature,\n digest: TransactionDataBuilder.getDigestFromBytes(transactionBytes),\n }\n } catch {\n return undefined\n }\n}\n\n/** Whether the canonical BCS encoding of the parsed bytes is exactly `bytes`. */\nfunction isCanonicalTransactionData(bytes: Uint8Array): boolean {\n const canonical = bcs.TransactionData.serialize(\n bcs.TransactionData.parse(bytes)\n ).toBytes()\n return (\n canonical.length === bytes.length &&\n canonical.every((byte, index) => byte === bytes[index])\n )\n}\n\n/**\n * Verifies that `signature` signs `bytes` and that the signer is the sender\n * of the transaction, so stored bytes that were changed after signing are\n * detected.\n *\n * Resolves `false` only for a definite failure: the bytes have no sender, or\n * the signature is malformed, is not valid for the bytes, or is not the\n * sender's. Rejects when the verification cannot run, so that such a failure\n * never counts as damaged bytes. A well-formed zkLogin signature, also as a\n * multisig member, needs a client to verify, so it rejects here.\n */\nexport async function verifySuiSignedTransaction(\n transaction: SuiSignedTransaction\n): Promise<boolean> {\n let sender: string | null\n try {\n sender = TransactionDataBuilder.fromBytes(transaction.bytes).sender\n } catch {\n return false\n }\n if (!sender) {\n return false\n }\n return isValidTransactionSignature(transaction.bytes, transaction.signature, {\n address: sender,\n })\n}\n\n/**\n * Serializes signed transaction bytes for `ExecutionAction.txHex`.\n *\n * Returns `undefined` when the result would not read back with\n * `parseSuiSignedTransaction`, so a stored value is always usable on resume.\n */\nexport function serializeSuiSignedTransaction(\n bytes: Uint8Array,\n signature: string\n): string | undefined {\n const txHex = JSON.stringify({ bytes: toBase64(bytes), signature })\n return parseSuiSignedTransaction(txHex) ? txHex : undefined\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAgB,0BACd,OACkC;CAClC,IAAI;EACF,MAAM,EAAE,OAAO,cAAc,KAAK,MAAM,KAAK;EAI7C,IAAI,OAAO,UAAU,YAAY,OAAO,cAAc,UACpD;EAEF,MAAM,mBAAmB,WAAW,KAAK;EAIzC,IAAI,CAAC,iBAAiB,UAAU,CAAC,WAAW,SAAS,CAAC,CAAC,QACrD;EAGF,uBAAuB,UAAU,gBAAgB;EAGjD,IAAI,CAAC,2BAA2B,gBAAgB,GAC9C;EAEF,OAAO;GACL,OAAO;GACP;GACA,QAAQ,uBAAuB,mBAAmB,gBAAgB;EACpE;CACF,QAAQ;EACN;CACF;AACF;;AAGA,SAAS,2BAA2B,OAA4B;CAC9D,MAAM,YAAY,IAAI,gBAAgB,UACpC,IAAI,gBAAgB,MAAM,KAAK,CACjC,CAAC,CAAC,QAAQ;CACV,OACE,UAAU,WAAW,MAAM,UAC3B,UAAU,OAAO,MAAM,UAAU,SAAS,MAAM,MAAM;AAE1D;;;;;;;;;;;;AAaA,eAAsB,2BACpB,aACkB;CAClB,IAAI;CACJ,IAAI;EACF,SAAS,uBAAuB,UAAU,YAAY,KAAK,CAAC,CAAC;CAC/D,QAAQ;EACN,OAAO;CACT;CACA,IAAI,CAAC,QACH,OAAO;CAET,OAAO,4BAA4B,YAAY,OAAO,YAAY,WAAW,EAC3E,SAAS,OACX,CAAC;AACH;;;;;;;AAQA,SAAgB,8BACd,OACA,WACoB;CACpB,MAAM,QAAQ,KAAK,UAAU;EAAE,OAAO,SAAS,KAAK;EAAG;CAAU,CAAC;CAClE,OAAO,0BAA0B,KAAK,IAAI,QAAQ,KAAA;AACpD"}
@@ -1,5 +1,5 @@
1
1
  //#region src/version.d.ts
2
2
  export declare const name = "@lifi/sdk-provider-sui";
3
- export declare const version = "4.2.7";
3
+ export declare const version = "4.2.9";
4
4
  //#endregion
5
5
  //# sourceMappingURL=version.d.ts.map
@@ -1,6 +1,6 @@
1
1
  //#region src/version.ts
2
2
  const name = "@lifi/sdk-provider-sui";
3
- const version = "4.2.7";
3
+ const version = "4.2.9";
4
4
  //#endregion
5
5
  export { name, version };
6
6
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk-provider-sui'\nexport const version = '4.2.7'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk-provider-sui'\nexport const version = '4.2.9'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifi/sdk-provider-sui",
3
- "version": "4.2.7",
3
+ "version": "4.2.9",
4
4
  "description": "LI.FI Sui SDK Provider for Any-to-Any Cross-Chain-Swap",
5
5
  "homepage": "https://github.com/lifinance/sdk",
6
6
  "bugs": {
@@ -28,8 +28,8 @@
28
28
  "./package.json": "./package.json"
29
29
  },
30
30
  "dependencies": {
31
- "@lifi/sdk": "4.10.0",
32
- "@mysten/sui": "^2.33.2"
31
+ "@lifi/sdk": "4.12.0",
32
+ "@mysten/sui": "^2.35.0"
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public"
@@ -1,4 +1,5 @@
1
1
  import {
2
+ ChainId,
2
3
  type SDKClient,
3
4
  type Token,
4
5
  type TokenAmount,
@@ -33,32 +34,47 @@ const getSuiBalanceDefault = async (
33
34
  tokens: Token[],
34
35
  walletAddress: string
35
36
  ): Promise<TokenAmount[]> => {
37
+ // The dedupe ids carry the RPC URLs of this SDK client. Two SDK clients
38
+ // with different URLs (one per tenant, each with its own API key) must not
39
+ // share a request. The lookup runs inside each settled entry, so a failed
40
+ // lookup leaves the amounts undefined, as a failed request does.
41
+ const rpcUrlsKey = client
42
+ .getRpcUrlsByChainId(ChainId.SUI)
43
+ .then((rpcUrls) => rpcUrls.join(' '))
36
44
  const [coins, checkpoint] = await Promise.allSettled([
37
- withDedupe(
38
- () =>
39
- callSuiWithRetry(client, async (suiClient) => {
40
- // listBalances is paginated; page through to collect every coin type.
41
- const balances: SuiClientTypes.Balance[] = []
42
- let cursor: string | null | undefined
43
- do {
44
- const page = await suiClient.core.listBalances({
45
- owner: walletAddress,
46
- cursor,
47
- })
48
- balances.push(...page.balances)
49
- cursor = page.hasNextPage ? page.cursor : null
50
- } while (cursor)
51
- return balances
52
- }),
53
- { id: `${getSuiBalanceDefault.name}.listBalances.${walletAddress}` }
45
+ rpcUrlsKey.then((urlsKey) =>
46
+ withDedupe(
47
+ () =>
48
+ callSuiWithRetry(client, async (suiClient) => {
49
+ // listBalances is paginated; page through to collect every coin type.
50
+ const balances: SuiClientTypes.Balance[] = []
51
+ let cursor: string | null | undefined
52
+ do {
53
+ const page = await suiClient.core.listBalances({
54
+ owner: walletAddress,
55
+ cursor,
56
+ })
57
+ balances.push(...page.balances)
58
+ cursor = page.hasNextPage ? page.cursor : null
59
+ } while (cursor)
60
+ return balances
61
+ }),
62
+ {
63
+ id: `${getSuiBalanceDefault.name}.listBalances.${walletAddress}.${urlsKey}`,
64
+ }
65
+ )
54
66
  ),
55
- withDedupe(
56
- () =>
57
- callSuiWithRetry(client, async (suiClient) => {
58
- const { response } = await suiClient.ledgerService.getServiceInfo({})
59
- return response.checkpointHeight ?? 0n
60
- }),
61
- { id: `${getSuiBalanceDefault.name}.getServiceInfo` }
67
+ rpcUrlsKey.then((urlsKey) =>
68
+ withDedupe(
69
+ () =>
70
+ callSuiWithRetry(client, async (suiClient) => {
71
+ const { response } = await suiClient.ledgerService.getServiceInfo(
72
+ {}
73
+ )
74
+ return response.checkpointHeight ?? 0n
75
+ }),
76
+ { id: `${getSuiBalanceDefault.name}.getServiceInfo.${urlsKey}` }
77
+ )
62
78
  ),
63
79
  ])
64
80
 
@@ -1,24 +1,23 @@
1
- import { ChainId, type SDKClient } from '@lifi/sdk'
1
+ import { ChainId, LruMap, type SDKClient } from '@lifi/sdk'
2
2
  import { SuiGrpcClient } from '@mysten/sui/grpc'
3
3
 
4
- const clients = new Map<string, SuiGrpcClient>()
4
+ // One client per RPC URL, shared by every SDK client in the process. The cap
5
+ // keeps a process that sees many URLs (one per tenant, or a changed
6
+ // configuration) from holding every client it ever built.
7
+ const clients = new LruMap<SuiGrpcClient>(64)
5
8
 
6
- /**
7
- * Initializes the Sui clients if they haven't been initialized yet.
8
- * @returns - Promise that resolves when clients are initialized.
9
- */
10
- const ensureClients = async (client: SDKClient): Promise<void> => {
11
- const rpcUrls = await client.getRpcUrlsByChainId(ChainId.SUI)
12
- for (const rpcUrl of rpcUrls) {
13
- if (!clients.get(rpcUrl)) {
14
- const client = new SuiGrpcClient({ network: 'mainnet', baseUrl: rpcUrl })
15
- clients.set(rpcUrl, client)
16
- }
9
+ const getSuiClient = (rpcUrl: string): SuiGrpcClient => {
10
+ let suiClient = clients.get(rpcUrl)
11
+ if (!suiClient) {
12
+ suiClient = new SuiGrpcClient({ network: 'mainnet', baseUrl: rpcUrl })
13
+ clients.set(rpcUrl, suiClient)
17
14
  }
15
+ return suiClient
18
16
  }
19
17
 
20
18
  /**
21
- * Calls a function on the SuiGrpcClient instances with retry logic.
19
+ * Calls a function on a SuiGrpcClient for each RPC URL of the SDK client, in
20
+ * order, until one call succeeds.
22
21
  * @param client - The SDK client
23
22
  * @param fn - The function to call, which receives a SuiGrpcClient instance.
24
23
  * @returns - The result of the function call.
@@ -27,12 +26,16 @@ export async function callSuiWithRetry<R>(
27
26
  client: SDKClient,
28
27
  fn: (client: SuiGrpcClient) => Promise<R>
29
28
  ): Promise<R> {
30
- // Ensure clients are initialized
31
- await ensureClients(client)
29
+ // Only the URLs of this SDK client: another SDK client's URL can carry
30
+ // another tenant's API key.
31
+ const rpcUrls = await client.getRpcUrlsByChainId(ChainId.SUI)
32
+ if (!rpcUrls.length) {
33
+ throw new Error('No Sui RPC URLs available')
34
+ }
32
35
  let lastError: any = null
33
- for (const client of clients.values()) {
36
+ for (const rpcUrl of rpcUrls) {
34
37
  try {
35
- const result = await fn(client)
38
+ const result = await fn(getSuiClient(rpcUrl))
36
39
  return result
37
40
  } catch (error) {
38
41
  lastError = error