@needmoretruth/nmts-cli 0.50.1 → 0.52.1

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 +28 -0
  2. package/README.ko.md +1 -1
  3. package/README.md +1 -1
  4. package/dist/api.js +3 -0
  5. package/dist/artifact-about.d.ts +1 -1
  6. package/dist/client-id.d.ts +11 -0
  7. package/dist/client-id.js +30 -0
  8. package/dist/commands/mcp.js +3 -0
  9. package/dist/commands/wallet-activity.d.ts +10 -6
  10. package/dist/commands/wallet-activity.js +17 -6
  11. package/dist/env-vars.d.ts +1 -1
  12. package/dist/env-vars.js +1 -1
  13. package/dist/extend-chain.d.ts +4 -6
  14. package/dist/extend-chain.js +25 -26
  15. package/dist/net-retry.js +14 -0
  16. package/dist/portable.d.ts +2 -0
  17. package/dist/portable.js +2 -0
  18. package/dist/product.d.ts +1 -1
  19. package/dist/product.js +1 -1
  20. package/dist/reach.d.ts +1 -1
  21. package/dist/shared/lib/storage-control/chain.d.ts +30 -29
  22. package/dist/shared/lib/storage-control/chain.js +14 -20
  23. package/dist/shared/lib/wallet/activity.d.ts +42 -48
  24. package/dist/shared/lib/wallet/activity.js +51 -30
  25. package/dist/shared/lib/wallet/address-history.d.ts +54 -0
  26. package/dist/shared/lib/wallet/address-history.js +313 -0
  27. package/dist/shared/lib/wallet/chain-calls.d.ts +44 -0
  28. package/dist/shared/lib/wallet/chain-calls.js +59 -0
  29. package/dist/storage-control-chain.js +5 -4
  30. package/dist/sui-execute.d.ts +54 -0
  31. package/dist/sui-execute.js +43 -0
  32. package/dist/sui-rpc.d.ts +16 -9
  33. package/dist/sui-rpc.js +53 -19
  34. package/dist/upload-wallet-chain.d.ts +3 -3
  35. package/dist/upload-wallet-chain.js +14 -22
  36. package/dist/wallet-activity-chain.d.ts +2 -2
  37. package/dist/wallet-activity-chain.js +12 -27
  38. package/dist/wallet-chain.js +19 -13
  39. package/dist/wallet-list-chain.d.ts +1 -1
  40. package/dist/wallet-list-chain.js +13 -14
  41. package/dist/wallet-send-chain.js +4 -3
  42. package/dist/wallet-sign-external.d.ts +19 -26
  43. package/dist/wallet-sign-external.js +13 -18
  44. package/dist/wallet-sign.js +19 -69
  45. package/dist/wallet-storage-chain.js +2 -3
  46. package/dist/wallet-swap-chain.d.ts +3 -6
  47. package/dist/wallet-swap-chain.js +16 -16
  48. package/dist/wallet-swap-quote.js +16 -17
  49. package/dist/walrus-write.js +6 -16
  50. package/dist/walrus.d.ts +13 -13
  51. package/dist/walrus.js +15 -15
  52. package/package.json +7 -4
  53. package/server.json +2 -2
  54. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +11 -11
  55. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  56. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +11 -11
@@ -41,10 +41,10 @@ export interface ActivityContext {
41
41
  /** The network name the explorer link is built for: `"mainnet"` or `"testnet"`. */
42
42
  network: string;
43
43
  }
44
- export interface RpcMoveCall {
45
- package?: string;
46
- module?: string;
47
- function?: string;
44
+ export interface ChainMoveCall {
45
+ package?: string | undefined;
46
+ module?: string | undefined;
47
+ function?: string | undefined;
48
48
  }
49
49
  /**
50
50
  * One command of a programmable transaction.
@@ -54,59 +54,52 @@ export interface RpcMoveCall {
54
54
  * ("no properties in common" — weak-type detection). The index signature says "any other field
55
55
  * is fine".
56
56
  */
57
- export interface RpcCommand {
58
- MoveCall?: RpcMoveCall;
57
+ export interface ChainCommand {
58
+ MoveCall?: ChainMoveCall | null | undefined;
59
59
  [other: string]: unknown;
60
60
  }
61
61
  /**
62
- * What can sit in a command slot — usually the shape above, but sometimes A BARE STRING (the
63
- * command list of an end-of-epoch transaction carries name-only entries). Our wallet transactions
64
- * never contain one, but the receiving type includes that branch, so it is accepted — and skipped.
62
+ * One transaction input — `{ Object: { SharedObject | ImmOrOwnedObject | Receiving: { objectId } } }`,
63
+ * `{ UnresolvedObject: { objectId } }`, or a pure value that carries no object. Read with checks
64
+ * rather than declared, for the same weak-type reason.
65
65
  */
66
- export type RpcCommandEntry = RpcCommand | string;
67
- /** One transaction input. The index signature is needed for the same reason (pure-value inputs have no `objectId`). */
68
- export interface RpcInput {
69
- objectId?: string;
70
- [other: string]: unknown;
71
- }
72
- export interface RpcBalanceChange {
73
- owner?: unknown;
74
- coinType?: string;
75
- amount?: string;
66
+ export type ChainInput = Readonly<Record<string, unknown>>;
67
+ export interface ChainBalanceChange {
68
+ address?: string | undefined;
69
+ coinType?: string | undefined;
70
+ amount?: string | undefined;
76
71
  }
77
- export interface RpcTransaction {
78
- digest?: string;
79
- timestampMs?: string | number | null;
80
- balanceChanges?: readonly RpcBalanceChange[] | null;
81
- effects?: {
82
- status?: {
83
- status?: string;
84
- };
85
- } | null;
72
+ export interface ChainTransaction {
73
+ digest?: string | undefined;
74
+ timestampMs?: string | number | null | undefined;
75
+ status?: {
76
+ success?: boolean | undefined;
77
+ } | null | undefined;
78
+ balanceChanges?: readonly ChainBalanceChange[] | null | undefined;
86
79
  transaction?: {
87
- data?: {
88
- sender?: string;
89
- gasData?: {
90
- owner?: string;
91
- };
92
- transaction?: {
93
- /** `ProgrammableTransaction` and the like. Not read, but it MUST be declared — for the same
94
- * reason as the index signatures: without it other kinds (`ChangeEpoch`) fail the type check. */
95
- kind?: string;
96
- inputs?: readonly RpcInput[];
97
- transactions?: readonly RpcCommandEntry[];
98
- };
99
- };
100
- } | null;
80
+ sender?: string | null | undefined;
81
+ gasData?: {
82
+ owner?: string | null | undefined;
83
+ } | undefined;
84
+ inputs?: readonly ChainInput[] | undefined;
85
+ commands?: readonly ChainCommand[] | undefined;
86
+ } | null | undefined;
101
87
  }
102
88
  /**
103
89
  * Put an address into one shape before comparing.
104
90
  *
105
91
  * ⚠ A Sui address can be written zero-padded or not (`0x2` and `0x000…02` are the same one). The
106
- * RPC's form and the one in our configuration can differ, and then THE SAME ADDRESS COMPARES AS
92
+ * chain's form and the one in our configuration can differ, and then THE SAME ADDRESS COMPARES AS
107
93
  * DIFFERENT — a gift would fall through to "send". So both are padded to 32 bytes first.
108
94
  */
109
95
  export declare function normalizeAddress(raw: string): string;
96
+ /**
97
+ * A coin type with its package address padded — `0x2::sui::SUI` and `0x000…02::sui::SUI` are one type.
98
+ *
99
+ * ⛔ The gRPC and GraphQL nodes write the long form, where JSON-RPC wrote the short one for SUI; a
100
+ * comparison against the short form alone would stop naming SUI anywhere in the list.
101
+ */
102
+ export declare function normalizeCoinType(raw: string): string;
110
103
  /**
111
104
  * One transaction → one row for a screen or a terminal.
112
105
  *
@@ -116,7 +109,7 @@ export declare function normalizeAddress(raw: string): string;
116
109
  * here goes down; donation comes before send because a more specific truth beats a less
117
110
  * specific one.
118
111
  */
119
- export declare function toActivityRow(tx: RpcTransaction, ctx: ActivityContext): ActivityRow;
112
+ export declare function toActivityRow(tx: ChainTransaction, ctx: ActivityContext): ActivityRow;
120
113
  /**
121
114
  * Where a person can look the transaction up themselves.
122
115
  *
@@ -128,11 +121,12 @@ export declare function toActivityRow(tx: RpcTransaction, ctx: ActivityContext):
128
121
  */
129
122
  export declare function explorerTxUrl(digest: string, network: string): string;
130
123
  /**
131
- * The two lists (sent, received) folded into one.
124
+ * Lists of rows folded into one — newest first, each digest once, at most `limit`.
132
125
  *
133
- * ⛔ THE RPC FILTER HAS NO OR — `FromAddress` and `ToAddress` cannot be asked for together, so
134
- * they are asked for twice and merged here. A transaction can appear on both sides, so
135
- * DUPLICATES ARE REMOVED BY DIGEST.
126
+ * ⭐ Since 2026-10-21 the chain is asked ONE question per page ("every transaction that moved this
127
+ * address's state" — the gRPC `affectedAddress` filter), where the retired JSON-RPC could only ask
128
+ * "sent" and "received" separately and this function merged the two. It still takes several lists,
129
+ * because a caller may page, and DUPLICATES ARE STILL REMOVED BY DIGEST.
136
130
  * ⚠ Rows with no time go LAST — treating a missing time as 0 would float "1970" to the top.
137
131
  */
138
132
  export declare function mergeActivity(groups: readonly (readonly ActivityRow[])[], limit: number): ActivityRow[];
@@ -33,16 +33,7 @@
33
33
  // `ActivityContext`, so the same file serves the browser (which reads its build's network) and
34
34
  // the command-line tool (which resolves the network at run time) without a fork.
35
35
  // ── Small readers ─────────────────────────────────────────────────────────────────────────────
36
- /** The address out of `{ AddressOwner: "0x…" }`. Other owner shapes (shared, immutable) have none → `null`. */
37
- function ownerAddress(owner) {
38
- if (typeof owner !== "object" || owner === null)
39
- return null;
40
- if (!("AddressOwner" in owner))
41
- return null;
42
- const value = owner.AddressOwner;
43
- return typeof value === "string" ? value : null;
44
- }
45
- /** The RPC gives the time as a string. Unreadable ⇒ `null`, NEVER an invented number. */
36
+ /** The chain gives the time as a number (or, from some nodes, a string). Unreadable ⇒ `null`, NEVER an invented number. */
46
37
  function readTimestamp(raw) {
47
38
  if (raw === null || raw === undefined)
48
39
  return null;
@@ -53,7 +44,7 @@ function readTimestamp(raw) {
53
44
  * Put an address into one shape before comparing.
54
45
  *
55
46
  * ⚠ A Sui address can be written zero-padded or not (`0x2` and `0x000…02` are the same one). The
56
- * RPC's form and the one in our configuration can differ, and then THE SAME ADDRESS COMPARES AS
47
+ * chain's form and the one in our configuration can differ, and then THE SAME ADDRESS COMPARES AS
57
48
  * DIFFERENT — a gift would fall through to "send". So both are padded to 32 bytes first.
58
49
  */
59
50
  export function normalizeAddress(raw) {
@@ -62,24 +53,50 @@ export function normalizeAddress(raw) {
62
53
  return raw.trim().toLowerCase();
63
54
  return `0x${body.padStart(64, "0")}`;
64
55
  }
56
+ /**
57
+ * A coin type with its package address padded — `0x2::sui::SUI` and `0x000…02::sui::SUI` are one type.
58
+ *
59
+ * ⛔ The gRPC and GraphQL nodes write the long form, where JSON-RPC wrote the short one for SUI; a
60
+ * comparison against the short form alone would stop naming SUI anywhere in the list.
61
+ */
62
+ export function normalizeCoinType(raw) {
63
+ const [address, ...rest] = raw.split("::");
64
+ return rest.length === 0 || address === undefined ? raw : [normalizeAddress(address), ...rest].join("::");
65
+ }
65
66
  /** Every Move call (empty for a pure transfer). */
66
67
  function moveCalls(tx) {
67
- const commands = tx.transaction?.data?.transaction?.transactions ?? [];
68
68
  const calls = [];
69
- for (const command of commands) {
70
- if (typeof command === "string")
71
- continue;
72
- if (command.MoveCall !== undefined)
69
+ for (const command of tx.transaction?.commands ?? []) {
70
+ if (command.MoveCall !== undefined && command.MoveCall !== null)
73
71
  calls.push(command.MoveCall);
74
72
  }
75
73
  return calls;
76
74
  }
75
+ /** `{ objectId }` → the id, anything else → null. */
76
+ function objectIdOf(value) {
77
+ return typeof value === "object" && value !== null && "objectId" in value && typeof value.objectId === "string"
78
+ ? value.objectId
79
+ : null;
80
+ }
81
+ /** The `objectId` one level down a tagged value — `{ $kind, SharedObject: { objectId } }` → the id. */
82
+ function idInside(value) {
83
+ if (typeof value !== "object" || value === null)
84
+ return null;
85
+ for (const inner of Object.values(value)) {
86
+ const id = objectIdOf(inner);
87
+ if (id !== null)
88
+ return id;
89
+ }
90
+ return null;
91
+ }
77
92
  /** Every object id among the inputs, zero-padded. */
78
93
  function inputObjectIds(tx) {
79
94
  const ids = new Set();
80
- for (const input of tx.transaction?.data?.transaction?.inputs ?? []) {
81
- if (typeof input.objectId === "string")
82
- ids.add(normalizeAddress(input.objectId));
95
+ for (const input of tx.transaction?.inputs ?? []) {
96
+ // A resolved object input is one level deeper than an unresolved one.
97
+ const id = idInside(input.Object) ?? objectIdOf(input.UnresolvedObject);
98
+ if (id !== null)
99
+ ids.add(normalizeAddress(id));
83
100
  }
84
101
  return ids;
85
102
  }
@@ -121,26 +138,29 @@ const WALRUS_FUNCTION_KIND = {
121
138
  export function toActivityRow(tx, ctx) {
122
139
  const me = normalizeAddress(ctx.address);
123
140
  const digest = typeof tx.digest === "string" ? tx.digest : "";
124
- const sender = normalizeAddress(tx.transaction?.data?.sender ?? "");
125
- const gasOwnerRaw = tx.transaction?.data?.gasData?.owner;
141
+ const sender = normalizeAddress(tx.transaction?.sender ?? "");
142
+ const gasOwnerRaw = tx.transaction?.gasData?.owner;
126
143
  const gasOwner = typeof gasOwnerRaw === "string" ? normalizeAddress(gasOwnerRaw) : sender;
127
144
  const pool = ctx.poolAddress === "" ? null : normalizeAddress(ctx.poolAddress);
128
145
  const gasPayer = gasOwner === sender ? "self" : pool !== null && gasOwner === pool ? "pool" : "other";
129
146
  const changes = [];
130
147
  let donationGain = false;
148
+ const wal = normalizeCoinType(ctx.walCoinType);
149
+ const sui = normalizeCoinType("0x2::sui::SUI");
131
150
  for (const change of tx.balanceChanges ?? []) {
132
- const owner = ownerAddress(change.owner);
133
- if (owner === null)
151
+ // A change whose owner is not an address (an object, a shared balance) has no `address` string.
152
+ if (typeof change.address !== "string")
134
153
  continue;
135
- const normalized = normalizeAddress(owner);
154
+ const normalized = normalizeAddress(change.address);
136
155
  const amount = change.amount === undefined ? 0n : amountOf(change.amount);
137
156
  // An entry whose figure we cannot read is skipped; the rest of the transaction is still a row.
138
157
  if (amount === null)
139
158
  continue;
140
159
  if (normalized === me) {
141
160
  const coinType = change.coinType ?? "";
161
+ const named = normalizeCoinType(coinType);
142
162
  changes.push({
143
- coin: coinType === ctx.walCoinType ? "WAL" : coinType === "0x2::sui::SUI" ? "SUI" : null,
163
+ coin: named === wal ? "WAL" : named === sui ? "SUI" : null,
144
164
  coinType,
145
165
  amount,
146
166
  });
@@ -181,7 +201,7 @@ export function toActivityRow(tx, ctx) {
181
201
  return {
182
202
  digest,
183
203
  atMs: readTimestamp(tx.timestampMs),
184
- failed: (tx.effects?.status?.status ?? "success") !== "success",
204
+ failed: tx.status?.success === false,
185
205
  gasPayer,
186
206
  kind,
187
207
  changes,
@@ -201,11 +221,12 @@ export function explorerTxUrl(digest, network) {
201
221
  return `https://suiscan.xyz/${network}/tx/${digest}`;
202
222
  }
203
223
  /**
204
- * The two lists (sent, received) folded into one.
224
+ * Lists of rows folded into one — newest first, each digest once, at most `limit`.
205
225
  *
206
- * ⛔ THE RPC FILTER HAS NO OR — `FromAddress` and `ToAddress` cannot be asked for together, so
207
- * they are asked for twice and merged here. A transaction can appear on both sides, so
208
- * DUPLICATES ARE REMOVED BY DIGEST.
226
+ * ⭐ Since 2026-10-21 the chain is asked ONE question per page ("every transaction that moved this
227
+ * address's state" — the gRPC `affectedAddress` filter), where the retired JSON-RPC could only ask
228
+ * "sent" and "received" separately and this function merged the two. It still takes several lists,
229
+ * because a caller may page, and DUPLICATES ARE STILL REMOVED BY DIGEST.
209
230
  * ⚠ Rows with no time go LAST — treating a missing time as 0 would float "1970" to the top.
210
231
  */
211
232
  export function mergeActivity(groups, limit) {
@@ -0,0 +1,54 @@
1
+ import { type SuiGrpcClient } from "@mysten/sui/grpc";
2
+ import type { SuiClientTypes } from "@mysten/sui/client";
3
+ /** What one row of history carries: the parsed transaction and every balance it moved. */
4
+ export type HistoryTransaction = SuiClientTypes.Transaction<{
5
+ transaction: true;
6
+ balanceChanges: true;
7
+ }>;
8
+ export interface AddressHistory {
9
+ /** Newest first, at most the `limit` asked for. */
10
+ transactions: HistoryTransaction[];
11
+ /** True when the whole history was looked through — false when some of it could not be read. */
12
+ complete: boolean;
13
+ }
14
+ /** Where history older than the node's window is read: the newest `limit` rows, newest first. */
15
+ export type DeeperHistory = (address: string, limit: number, signal?: AbortSignal) => Promise<HistoryTransaction[]>;
16
+ /**
17
+ * Sui's public GraphQL service per network (Mysten Labs). Measured 2026-10-21: the `affectedAddress`
18
+ * filter answered back to 2023 on both networks, in 0.2–0.9 s, with `access-control-allow-origin: *`.
19
+ * It is the only public operator of it, so it is the second tier and never the only one: a failure
20
+ * here leaves the answer `complete: false`, never "nothing there".
21
+ */
22
+ export declare const SUI_GRAPHQL_URLS: Readonly<Record<"mainnet" | "testnet", string>>;
23
+ /**
24
+ * How far above a node's lowest checkpoint a read starts. Mainnet seals about four checkpoints a
25
+ * second, so 20,000 is over an hour of the node pruning before the start falls out of its window
26
+ * again — and a refusal then simply moves it up (same margin as the chain service's gift reader).
27
+ */
28
+ export declare const WINDOW_MARGIN = 20000n;
29
+ /**
30
+ * The lowest checkpoint a node said it holds, read from its refusal, or `null` for any other error.
31
+ * Suiscan and Mysten Labs both answered `requested data below earliest available; lowest available
32
+ * checkpoint is <n>` on 2026-11-07.
33
+ */
34
+ export declare function lowestAvailable(e: unknown): bigint | null;
35
+ /**
36
+ * The newest transactions that moved `address`'s state, newest first.
37
+ *
38
+ * @param limit - how many to return at most; 1 is the cheapest "has this address any history".
39
+ * @param deeper - where to read past the node's window; `null` when the caller named its own node and
40
+ * asked for nothing else (the answer is then `complete: false` whenever the window ran out).
41
+ */
42
+ export declare function addressTransactions(client: Pick<SuiGrpcClient, "ledgerService">, address: string, limit: number, signal?: AbortSignal, deeper?: DeeperHistory | null): Promise<AddressHistory>;
43
+ /**
44
+ * Has `address` ever been in a transaction? Throws when nobody could finish looking — "nobody could
45
+ * tell" and "nothing is there" are opposite facts, and only the second may answer `false`.
46
+ */
47
+ export declare function hasAddressHistory(client: Pick<SuiGrpcClient, "ledgerService">, address: string, signal?: AbortSignal, deeper?: DeeperHistory | null): Promise<boolean>;
48
+ /**
49
+ * The deeper source over Sui's GraphQL service at `url`.
50
+ *
51
+ * ⛔ Anything but a clean answer throws — an error list, a missing page, a row of the wrong shape.
52
+ * The caller turns that into `complete: false`; it never becomes an empty history.
53
+ */
54
+ export declare function graphqlHistory(url: string, fetchFn?: (input: string, init: RequestInit) => Promise<Response>): DeeperHistory;
@@ -0,0 +1,313 @@
1
+ // The transactions that moved one address — asked of a Sui node over gRPC, and of Sui's GraphQL
2
+ // service for what the node no longer keeps. ⚠ PUBLISHED — copied byte-for-byte into the `nmts`
3
+ // command-line package; keep comments self-contained English.
4
+ //
5
+ // ⛔ WHY ONE QUESTION, WHERE THERE USED TO BE TWO (2026-10-21). The retired JSON-RPC could filter
6
+ // transactions by `FromAddress` or by `ToAddress` and had no OR, so "sent" and "received" were two
7
+ // queries everywhere — the wallet walk, the activity list, both in the browser and in the
8
+ // command-line tool. The gRPC ledger index has the filter that was actually meant:
9
+ // `affectedAddress` — every transaction after which this address owns, lost or changed an object,
10
+ // or whose address balance moved. Sending pays gas from the sender's coin, so a send is in it;
11
+ // receiving gives the address an object, so a receipt is in it.
12
+ //
13
+ // ⛔ A gRPC NODE KEEPS A WINDOW, NOT THE HISTORY (measured 2026-10-21). Each node answers only from
14
+ // the checkpoints it still holds, and says where that ends: a scan with nothing in it stops with
15
+ // `CHECKPOINT_BOUND` at the node's lowest available checkpoint. Mysten Labs' fullnode held about
16
+ // the last three weeks on both networks; Suiscan's held two weeks on mainnet and the last few
17
+ // SECONDS on testnet. So "the node found nothing" means "nothing lately" — a wallet funded in
18
+ // August and idle since read as never used, which is how a funded wallet vanishes from a screen.
19
+ // What the window does not cover is asked of Sui's public GraphQL service, which answered the same
20
+ // filter back to 2023 on both networks; its rows are read by the SAME parser as the node's (its
21
+ // `transactionJson` and `balanceChangesJson` are the gRPC messages written as JSON).
22
+ //
23
+ // ⛔ A REQUEST WITHOUT A START IS REFUSED (measured 2026-11-07). `ListTransactions` without
24
+ // `startCheckpoint` starts at genesis, and since about 2026-11-05 both Suiscan and Mysten Labs refuse
25
+ // that outright — "requested data below earliest available; lowest available checkpoint is <n>" —
26
+ // instead of stopping quietly at their window's edge. Every wallet walk and activity list then
27
+ // failed on Suiscan, and on Mysten for any address idle for a few weeks, before the deeper source
28
+ // was ever asked. So a refused read is sent again from a little above the checkpoint the refusal
29
+ // names, that floor is remembered per network, and the scan then ends at that start, which is the
30
+ // window's edge: what lies below it is the deeper source's to answer.
31
+ //
32
+ // ⛔ A SCAN THAT STOPPED SHORT IS NOT "NOTHING THERE". The node also bounds how much of its index one
33
+ // request reads; a request can end with fewer items than asked — even none — and say it stopped
34
+ // because of that bound (`SCAN_LIMIT`). This file follows the cursor for a bounded number of
35
+ // requests. Whatever it could not settle is `complete: false`, so a caller can tell "no history"
36
+ // from "did not finish looking".
37
+ //
38
+ // ⚠ It needs the gRPC client: the filter is a raw ledger-service filter, which the SDK's top-level
39
+ // `listTransactions` does not offer (it filters by sender or function only).
40
+ import { GrpcTypes, parseGrpcTransactionResponse } from "@mysten/sui/grpc";
41
+ /**
42
+ * Sui's public GraphQL service per network (Mysten Labs). Measured 2026-10-21: the `affectedAddress`
43
+ * filter answered back to 2023 on both networks, in 0.2–0.9 s, with `access-control-allow-origin: *`.
44
+ * It is the only public operator of it, so it is the second tier and never the only one: a failure
45
+ * here leaves the answer `complete: false`, never "nothing there".
46
+ */
47
+ export const SUI_GRAPHQL_URLS = {
48
+ mainnet: "https://graphql.mainnet.sui.io/graphql",
49
+ testnet: "https://graphql.testnet.sui.io/graphql",
50
+ };
51
+ /** How many requests one question may take before it answers with what it has. */
52
+ const MAX_REQUESTS = 8;
53
+ /**
54
+ * How far above a node's lowest checkpoint a read starts. Mainnet seals about four checkpoints a
55
+ * second, so 20,000 is over an hour of the node pruning before the start falls out of its window
56
+ * again — and a refusal then simply moves it up (same margin as the chain service's gift reader).
57
+ */
58
+ export const WINDOW_MARGIN = 20000n;
59
+ /** Refusals answered by moving the start up before the read counts as failed. */
60
+ const MAX_WINDOW_RETRIES = 2;
61
+ // The lowest checkpoint a node has named in a refusal, per network (or per client when it names none,
62
+ // as a test's fake does). Remembered so a page that asks many times pays the refusal once.
63
+ const floorByNetwork = new Map();
64
+ const floorByClient = new WeakMap();
65
+ function networkOf(client) {
66
+ return "network" in client && typeof client.network === "string" ? client.network : undefined;
67
+ }
68
+ function knownFloor(client) {
69
+ const network = networkOf(client);
70
+ return network === undefined ? floorByClient.get(client) : floorByNetwork.get(network);
71
+ }
72
+ function rememberFloor(client, floor) {
73
+ const network = networkOf(client);
74
+ if (network === undefined)
75
+ floorByClient.set(client, floor);
76
+ else
77
+ floorByNetwork.set(network, floor);
78
+ }
79
+ /**
80
+ * The lowest checkpoint a node said it holds, read from its refusal, or `null` for any other error.
81
+ * Suiscan and Mysten Labs both answered `requested data below earliest available; lowest available
82
+ * checkpoint is <n>` on 2026-11-07.
83
+ */
84
+ export function lowestAvailable(e) {
85
+ const message = e instanceof Error ? e.message : typeof e === "string" ? e : "";
86
+ const found = /lowest available checkpoint is (\d{1,20})/.exec(message);
87
+ return found === null || found[1] === undefined ? null : BigInt(found[1]);
88
+ }
89
+ /** The fields the parser reads for `{ transaction, balanceChanges }` (the SDK's own read mask, by name). */
90
+ const READ_MASK = [
91
+ "digest",
92
+ "transaction.digest",
93
+ "signatures",
94
+ "effects.status",
95
+ "timestamp",
96
+ "checkpoint",
97
+ "transaction.sender",
98
+ "transaction.gas_payment",
99
+ "transaction.expiration",
100
+ "transaction.kind",
101
+ "balance_changes",
102
+ ];
103
+ async function recentTransactions(client, address, limit, signal) {
104
+ const transactions = [];
105
+ let before;
106
+ for (let request = 0; request < MAX_REQUESTS; request += 1) {
107
+ let frontier;
108
+ let reachedCheckpoint;
109
+ let reason;
110
+ for (let attempt = 0;; attempt += 1) {
111
+ const floor = knownFloor(client);
112
+ const startCheckpoint = floor === undefined ? undefined : floor + WINDOW_MARGIN;
113
+ // Rows of one attempt are kept only if the attempt finishes: a refusal mid-stream adds nothing.
114
+ const rows = [];
115
+ frontier = undefined;
116
+ reachedCheckpoint = undefined;
117
+ reason = undefined;
118
+ try {
119
+ const call = client.ledgerService.listTransactions({
120
+ ...(startCheckpoint === undefined ? {} : { startCheckpoint }),
121
+ readMask: { paths: READ_MASK },
122
+ filter: {
123
+ terms: [
124
+ {
125
+ literals: [
126
+ { negated: false, predicate: { oneofKind: "affectedAddress", affectedAddress: { address } } },
127
+ ],
128
+ },
129
+ ],
130
+ },
131
+ options: {
132
+ limit: limit - transactions.length,
133
+ ordering: GrpcTypes.Ordering.DESCENDING,
134
+ ...(before === undefined ? {} : { before }),
135
+ },
136
+ }, signal === undefined ? {} : { abort: signal });
137
+ for await (const frame of call.responses) {
138
+ if (frame.watermark?.cursor !== undefined)
139
+ frontier = frame.watermark.cursor;
140
+ if (frame.watermark?.checkpoint !== undefined)
141
+ reachedCheckpoint = frame.watermark.checkpoint;
142
+ if (frame.transaction !== undefined && transactions.length + rows.length < limit) {
143
+ const parsed = parseGrpcTransactionResponse(frame.transaction, {
144
+ include: { transaction: true, balanceChanges: true },
145
+ });
146
+ const tx = parsed.Transaction ?? parsed.FailedTransaction;
147
+ if (tx !== undefined)
148
+ rows.push(tx);
149
+ }
150
+ if (frame.end !== undefined)
151
+ reason = frame.end.reason;
152
+ }
153
+ transactions.push(...rows);
154
+ break;
155
+ }
156
+ catch (e) {
157
+ const lowest = lowestAvailable(e);
158
+ // Anything else is a real failure, and so is a window that keeps moving past a fresh floor.
159
+ if (lowest === null || attempt >= MAX_WINDOW_RETRIES)
160
+ throw e;
161
+ rememberFloor(client, lowest);
162
+ }
163
+ }
164
+ if (transactions.length >= limit)
165
+ return { transactions, fromGenesis: true };
166
+ // A scan bound means "there may be more, carry on from here".
167
+ if (reason === GrpcTypes.QueryEndReason.SCAN_LIMIT && frontier !== undefined) {
168
+ before = frontier;
169
+ continue;
170
+ }
171
+ // ⛔ Newest-first, the scan ends at the oldest checkpoint the node still holds. Only when that is
172
+ // the chain's first checkpoint has it seen everything; any other ending is the window's edge.
173
+ return {
174
+ transactions,
175
+ fromGenesis: reason === GrpcTypes.QueryEndReason.CHECKPOINT_BOUND && reachedCheckpoint === 0n,
176
+ };
177
+ }
178
+ return { transactions, fromGenesis: false };
179
+ }
180
+ /** Newest first; rows the node gave win over the same rows from the deeper source (they are fresher). */
181
+ function mergeNewestFirst(recent, deeper, limit) {
182
+ const seen = new Set(recent.map((tx) => tx.digest));
183
+ const all = [...recent, ...deeper.filter((tx) => !seen.has(tx.digest))];
184
+ // A row without a time sorts last: it cannot be placed, and it must not push a dated row out.
185
+ const time = (tx) => tx.timestampMs ?? Number.NEGATIVE_INFINITY;
186
+ return all.sort((a, b) => time(b) - time(a)).slice(0, limit);
187
+ }
188
+ /**
189
+ * The newest transactions that moved `address`'s state, newest first.
190
+ *
191
+ * @param limit - how many to return at most; 1 is the cheapest "has this address any history".
192
+ * @param deeper - where to read past the node's window; `null` when the caller named its own node and
193
+ * asked for nothing else (the answer is then `complete: false` whenever the window ran out).
194
+ */
195
+ export async function addressTransactions(client, address, limit, signal, deeper = null) {
196
+ const recent = await recentTransactions(client, address, limit, signal);
197
+ if (recent.fromGenesis)
198
+ return { transactions: recent.transactions, complete: true };
199
+ if (deeper === null)
200
+ return { transactions: recent.transactions, complete: false };
201
+ try {
202
+ const older = await deeper(address, limit, signal);
203
+ return { transactions: mergeNewestFirst(recent.transactions, older, limit), complete: true };
204
+ }
205
+ catch {
206
+ // The node's rows stand; the answer says plainly that it is not the whole history.
207
+ return { transactions: recent.transactions, complete: false };
208
+ }
209
+ }
210
+ /**
211
+ * Has `address` ever been in a transaction? Throws when nobody could finish looking — "nobody could
212
+ * tell" and "nothing is there" are opposite facts, and only the second may answer `false`.
213
+ */
214
+ export async function hasAddressHistory(client, address, signal, deeper = null) {
215
+ const { transactions, complete } = await addressTransactions(client, address, 1, signal, deeper);
216
+ if (transactions.length > 0)
217
+ return true;
218
+ if (!complete)
219
+ throw new Error(`The chain did not finish looking for transactions of ${address}.`);
220
+ return false;
221
+ }
222
+ function asJson(value) {
223
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
224
+ return value;
225
+ }
226
+ if (Array.isArray(value)) {
227
+ const out = [];
228
+ for (const item of value) {
229
+ const json = asJson(item);
230
+ if (json === undefined)
231
+ return undefined;
232
+ out.push(json);
233
+ }
234
+ return out;
235
+ }
236
+ if (typeof value === "object") {
237
+ const out = {};
238
+ for (const [key, item] of Object.entries(value)) {
239
+ const json = asJson(item);
240
+ if (json === undefined)
241
+ return undefined;
242
+ out[key] = json;
243
+ }
244
+ return out;
245
+ }
246
+ return undefined;
247
+ }
248
+ const objectAt = (json) => json !== null && typeof json === "object" && !Array.isArray(json) ? json : undefined;
249
+ const QUERY = `query ($address: SuiAddress!, $last: Int!) {
250
+ transactions(last: $last, filter: { affectedAddress: $address }) {
251
+ nodes { digest transactionJson effects { status timestamp checkpoint { sequenceNumber } balanceChangesJson } }
252
+ }
253
+ }`;
254
+ /** One GraphQL row as the gRPC message the shared parser reads. `undefined` when its shape is off. */
255
+ function executedFromGraphql(node) {
256
+ const effects = objectAt(node["effects"]);
257
+ const digest = node["digest"];
258
+ const transactionJson = objectAt(node["transactionJson"]);
259
+ const timestamp = effects?.["timestamp"];
260
+ const checkpoint = objectAt(effects?.["checkpoint"])?.["sequenceNumber"];
261
+ const changes = effects?.["balanceChangesJson"];
262
+ if (typeof digest !== "string" || transactionJson === undefined || effects === undefined)
263
+ return undefined;
264
+ const ms = typeof timestamp === "string" ? Date.parse(timestamp) : Number.NaN;
265
+ const options = { ignoreUnknownFields: true };
266
+ return GrpcTypes.ExecutedTransaction.create({
267
+ digest,
268
+ transaction: GrpcTypes.Transaction.fromJson(transactionJson, options),
269
+ effects: GrpcTypes.TransactionEffects.create({ status: { success: effects["status"] === "SUCCESS" } }),
270
+ ...(Number.isFinite(ms) ? { timestamp: { seconds: BigInt(Math.floor(ms / 1000)), nanos: (ms % 1000) * 1_000_000 } } : {}),
271
+ ...(typeof checkpoint === "number" ? { checkpoint: BigInt(checkpoint) } : {}),
272
+ balanceChanges: Array.isArray(changes) ? changes.map((c) => GrpcTypes.BalanceChange.fromJson(c, options)) : [],
273
+ });
274
+ }
275
+ /**
276
+ * The deeper source over Sui's GraphQL service at `url`.
277
+ *
278
+ * ⛔ Anything but a clean answer throws — an error list, a missing page, a row of the wrong shape.
279
+ * The caller turns that into `complete: false`; it never becomes an empty history.
280
+ */
281
+ export function graphqlHistory(url, fetchFn = (input, init) => fetch(input, init)) {
282
+ return async (address, limit, signal) => {
283
+ const res = await fetchFn(url, {
284
+ method: "POST",
285
+ headers: { "content-type": "application/json" },
286
+ body: JSON.stringify({ query: QUERY, variables: { address, last: limit } }),
287
+ ...(signal === undefined ? {} : { signal }),
288
+ });
289
+ if (!res.ok)
290
+ throw new Error(`The history service answered HTTP ${res.status}.`);
291
+ const body = await res.json();
292
+ const top = objectAt(asJson(body));
293
+ if (top === undefined || top["errors"] !== undefined) {
294
+ throw new Error("The history service answered with an error.");
295
+ }
296
+ const nodes = objectAt(objectAt(top["data"])?.["transactions"])?.["nodes"];
297
+ if (!Array.isArray(nodes))
298
+ throw new Error("The history service answered without a list.");
299
+ const rows = [];
300
+ // `last: n` arrives oldest-first; the list here is newest-first.
301
+ for (const node of [...nodes].reverse()) {
302
+ const row = objectAt(node);
303
+ const executed = row === undefined ? undefined : executedFromGraphql(row);
304
+ if (executed === undefined)
305
+ throw new Error("The history service answered a row this build cannot read.");
306
+ const parsed = parseGrpcTransactionResponse(executed, { include: { transaction: true, balanceChanges: true } });
307
+ const tx = parsed.Transaction ?? parsed.FailedTransaction;
308
+ if (tx !== undefined)
309
+ rows.push(tx);
310
+ }
311
+ return rows;
312
+ };
313
+ }