@esseyonsui/sui-mcp-v3 0.1.9 → 0.2.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.
Files changed (49) hide show
  1. package/README.md +37 -7
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +2 -2
  4. package/dist/args.d.ts +11 -2
  5. package/dist/args.d.ts.map +1 -1
  6. package/dist/args.js +37 -10
  7. package/dist/client.d.ts +1 -1
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +5 -3
  10. package/dist/config.d.ts +2 -0
  11. package/dist/config.d.ts.map +1 -1
  12. package/dist/config.js +5 -0
  13. package/dist/fund.d.ts.map +1 -1
  14. package/dist/fund.js +2 -2
  15. package/dist/handles.d.ts +23 -0
  16. package/dist/handles.d.ts.map +1 -0
  17. package/dist/handles.js +142 -0
  18. package/dist/http.d.ts +6 -0
  19. package/dist/http.d.ts.map +1 -0
  20. package/dist/http.js +5 -0
  21. package/dist/init.d.ts +1 -0
  22. package/dist/init.d.ts.map +1 -1
  23. package/dist/init.js +10 -5
  24. package/dist/io.d.ts +19 -11
  25. package/dist/io.d.ts.map +1 -1
  26. package/dist/io.js +190 -136
  27. package/dist/keys.d.ts +2 -0
  28. package/dist/keys.d.ts.map +1 -1
  29. package/dist/keys.js +14 -1
  30. package/dist/main.js +19 -8
  31. package/dist/records.d.ts +17 -1
  32. package/dist/records.d.ts.map +1 -1
  33. package/dist/records.js +39 -5
  34. package/dist/reveal.d.ts +7 -0
  35. package/dist/reveal.d.ts.map +1 -0
  36. package/dist/reveal.js +40 -0
  37. package/dist/snapshot.d.ts +13 -0
  38. package/dist/snapshot.d.ts.map +1 -0
  39. package/dist/snapshot.js +29 -0
  40. package/dist/tools-badge.js +3 -3
  41. package/dist/tools-more.d.ts +9 -5
  42. package/dist/tools-more.d.ts.map +1 -1
  43. package/dist/tools-more.js +56 -12
  44. package/dist/tools-sales.d.ts.map +1 -1
  45. package/dist/tools-sales.js +34 -24
  46. package/dist/tools.d.ts +3 -0
  47. package/dist/tools.d.ts.map +1 -1
  48. package/dist/tools.js +64 -30
  49. package/package.json +4 -3
package/dist/io.d.ts CHANGED
@@ -1,14 +1,16 @@
1
1
  import type { Signer } from "@mysten/sui/cryptography";
2
2
  import { v3, type EsseyIo } from "@esseyonsui/sui-sdk-v3";
3
+ import { type Fetch } from "./http.ts";
3
4
  export { TESTNET_GRAPHQL } from "./config.ts";
4
5
  type Json = any;
5
- type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
6
6
  type Gql = (query: string, variables: Record<string, unknown>) => Promise<Json>;
7
7
  export type ChainIoOptions = {
8
8
  graphql: string;
9
9
  fetch?: Fetch;
10
10
  /** Pause between index polls after a step lands; tests pass 0. */
11
11
  indexPauseMs?: number;
12
+ /** How long one walk of the loan, room and vault sets serves lookups (PRV-32); 0 walks for every lookup. */
13
+ snapshotMs?: number;
12
14
  /** Circuit name to local `{ wasm, zkey }` paths, for a circuit `/v3/config` does not serve yet. */
13
15
  localArtifacts?: Record<string, {
14
16
  wasm: string;
@@ -52,6 +54,7 @@ type SealRequest = {
52
54
  };
53
55
  export declare function chainIo(config: Json, o: ChainIoOptions): {
54
56
  prefetchArtifacts: () => Promise<void> | undefined;
57
+ /** A landed step makes every held walk stale. */
55
58
  waitIndexed: (landedAtMs: number) => Promise<boolean>;
56
59
  prover: v3.Prover;
57
60
  readPrice: (market: string) => Promise<{
@@ -74,13 +77,12 @@ export declare function chainIo(config: Json, o: ChainIoOptions): {
74
77
  readSettleTime: (loanId: string) => Promise<bigint>;
75
78
  readTopupDelivery: (loanId: string) => Promise<[bigint, bigint, bigint] | null>;
76
79
  readKeeperCt: (loanId: string) => Promise<Uint8Array<ArrayBufferLike>>;
77
- readBadge: (digest: string) => Promise<{
78
- id: string;
79
- json: any;
80
- } | null>;
81
- readSaleOpened: (digest: string) => Promise<{
82
- room: string;
83
- vault: string;
80
+ readBadges: (cursor: string | null) => Promise<{
81
+ badges: {
82
+ id: string;
83
+ json: any;
84
+ }[];
85
+ next: string | null;
84
86
  }>;
85
87
  readObjectRef: (id: string) => Promise<{
86
88
  version: string;
@@ -91,7 +93,10 @@ export declare function chainIo(config: Json, o: ChainIoOptions): {
91
93
  json: any;
92
94
  }>;
93
95
  readRooms: (cursor: string | null) => Promise<{
94
- rooms: any;
96
+ rooms: {
97
+ id: string;
98
+ json: any;
99
+ }[];
95
100
  next: string | null;
96
101
  }>;
97
102
  readVaultOf: (room: string) => Promise<string>;
@@ -117,7 +122,10 @@ export declare function chainIo(config: Json, o: ChainIoOptions): {
117
122
  round: any;
118
123
  }>;
119
124
  readLoans: (cursor: string | null) => Promise<{
120
- loans: any;
125
+ loans: {
126
+ id: string;
127
+ json: any;
128
+ }[];
121
129
  next: string | null;
122
130
  }>;
123
131
  priceUpdate: () => Promise<Uint8Array<ArrayBuffer>>;
@@ -126,7 +134,7 @@ export declare function chainIo(config: Json, o: ChainIoOptions): {
126
134
  value: bigint;
127
135
  sender: string;
128
136
  }) => Promise<void>) | undefined;
129
- readFeeCommit: (coin: string) => Promise<bigint>;
137
+ readFeeCommit: (coin: string, lane: string) => Promise<bigint>;
130
138
  readSharedVersion: (id: string) => Promise<string>;
131
139
  readPool: (coin: string) => Promise<{
132
140
  commitments: {
package/dist/io.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"io.d.ts","sourceRoot":"","sources":["../src/io.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAMvD,OAAO,EAAE,EAAE,EAAE,KAAK,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAI1D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAQ9C,KAAK,IAAI,GAAG,GAAG,CAAC;AAChB,KAAK,KAAK,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpE,KAAK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AC;AAC3F,KAAK,WAAW,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAC;IAAC,IAAI,EAAE,OAAO,EAAE,CAAA;CAAE,CAAC;AAEhF,KAAK,WAAW,GAAG;IAAE,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IAAC,GAAG,CAAC,EAAE,WAAW,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAwD7G,wBAAgB,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,cAAc;;IAmCnD,iDAAiD;8BACjB,MAAM;;wBAQZ,MAAM;;;;;0BACJ,MAAM;gBAzXd,MAAM;gBACL,MAAM;;;;;;0BAyXC,MAAM;;;;6BACH,MAAM;gCACH,MAAM;2BACX,MAAM;yBACR,MAAM,GAAG,IAAI;;;;;;;wBAIpB,MAAM;;;;;mBACL,MAAM;;;wBACD,MAAM,GAAG,IAAI;;;;;;;wBAIb,MAAM;+BAML,MAAM;oBACX,MAAM;;;qBACL,MAAM;2CAjJ5B;QACD,EAAE,EAAE,UAAU,CAAC;QACf,IAAI,EAAE,UAAU,CAAC;QACjB,GAAG,CAAC,EAAE,UAAU,CAAC;QACjB,GAAG,CAAC,EAAE,WAAW,CAAC;KACnB;qBAqDgB,WAAW,GAAG;QAAE,MAAM,EAAE,UAAU,CAAA;KAAE;yBAOpC,WAAW,GAAG;QAAE,EAAE,EAAE,UAAU,CAAA;KAAE;mBAoF1B,MAAM,UAAU,MAAM;;;;wBAEjB,MAAM,GAAG,IAAI;;;;;;;;;;;;;0BAMX,MAAM,QAAQ,MAAM;4BAIlB,MAAM;qBACb,MAAM;;;;;;;;EAkBhC"}
package/dist/io.js CHANGED
@@ -3,17 +3,19 @@ import { randomBytes } from "node:crypto";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { createRequire } from "node:module";
5
5
  import { DemType, SealClient, SessionKey } from "@mysten/seal";
6
- import { SuiGraphQLClient } from "@mysten/sui/graphql";
7
6
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
8
7
  import { Transaction } from "@mysten/sui/transactions";
9
8
  import { normalizeSuiAddress } from "@mysten/sui/utils";
10
- import { v3 } from "@esseyonsui/sui-sdk-v3";
9
+ import { fixedHeaders, v3 } from "@esseyonsui/sui-sdk-v3";
11
10
  import { artifactCache } from "./artifact-cache.js";
11
+ import { graphqlClient, plainFetch } from "./http.js";
12
+ import { snapshot } from "./snapshot.js";
12
13
  export { TESTNET_GRAPHQL } from "./config.js";
13
14
  const require = createRequire(import.meta.url);
14
15
  const snarkjs = require("snarkjs");
15
16
  const INDEX_RETRIES = 15;
16
17
  const LOAN_PAGE = 50;
18
+ const SNAPSHOT_MS = 5_000;
17
19
  function graphql(url, fetch) {
18
20
  return async (query, variables) => {
19
21
  const res = await fetch(url, {
@@ -59,13 +61,28 @@ const grew = (n, id, field) => n.transaction.effects.objectChanges.nodes.some((c
59
61
  });
60
62
  const leaves = (pool) => pool.tree.next_index;
61
63
  const spent = (pool) => pool.nullifiers.size;
64
+ /** Each id's Move fields, in one query that names every id: `o<i>: object(address: $a<i>)`. */
65
+ async function objectsById(gql, ids) {
66
+ const decl = ids.map((_, i) => `$a${i}: SuiAddress!`).join(", ");
67
+ const fields = ids.map((_, i) => `o${i}: object(address: $a${i}) { asMoveObject { contents { json } } }`);
68
+ const d = await gql(`query(${decl}) { ${fields.join(" ")} }`, Object.fromEntries(ids.map((id, i) => [`a${i}`, id])));
69
+ return new Map(ids.map((id, i) => [key(id), onChain(d[`o${i}`]?.asMoveObject?.contents?.json, id)]));
70
+ }
71
+ /**
72
+ * FOLLOWUPS #9: every market in the deployment record and every feed they read, so a price read names no pair.
73
+ * There are few markets; the ids are sorted so every walk sends the same query.
74
+ */
75
+ async function marketSet(gql, ids) {
76
+ const markets = await objectsById(gql, [...ids].sort());
77
+ const feeds = await objectsById(gql, [...new Set([...markets.values()].map((m) => String(m.feed_id)))].sort());
78
+ return new Map([...markets].map(([id, market]) => [id, { market, feed: feeds.get(key(market.feed_id)) }]));
79
+ }
62
80
  /**
63
81
  * The io fetches no Pyth update, so every price kind reads the market's feed as it stands and the update is one zero
64
82
  * byte: a stand-in feed as the admin set it, a Pyth `PriceInfoObject` (same layout) as others last updated it.
65
83
  */
66
- async function readPrice(gql, market) {
67
- const m = (await objectOf(gql, market)).asMoveObject.contents.json;
68
- const info = (await objectOf(gql, m.feed_id)).asMoveObject.contents.json.price_info.price_feed;
84
+ function priceOf({ market: m, feed }) {
85
+ const info = feed.price_info.price_feed;
69
86
  const spot = BigInt(info.price.price.magnitude);
70
87
  const ema = BigInt(info.ema_price.price.magnitude);
71
88
  const expo = BigInt(info.price.expo.magnitude);
@@ -97,9 +114,8 @@ export function invertReading(spot, ema, spotExpo, emaExpo) {
97
114
  return { spot: scale(s, sExp), ema: scale(e, eExp), expo };
98
115
  }
99
116
  /** The stand-in oracle's `price::Reading`: publish_s is the older of the two feed timestamps. */
100
- async function readReading(gql, market) {
101
- const m = (await objectOf(gql, market)).asMoveObject.contents.json;
102
- const f = (await objectOf(gql, m.feed_id)).asMoveObject.contents.json.price_info.price_feed;
117
+ function readingOf({ market: m, feed }) {
118
+ const f = feed.price_info.price_feed;
103
119
  const [spotS, emaS] = [BigInt(f.price.timestamp), BigInt(f.ema_price.timestamp)];
104
120
  return {
105
121
  oracle: m.oracle,
@@ -111,14 +127,13 @@ async function readReading(gql, market) {
111
127
  };
112
128
  }
113
129
  const SEIZING = { liquidate: 5, claim_default: 7, fault_liquidate: 5 };
114
- /** A seized loan's last transaction is the seizing call; `p_spot` is the pure input at the call's p_spot position. */
115
- async function readSeizure(gql, loanId) {
116
- const prev = await gql(`query($id: SuiAddress!) { object(address: $id) { previousTransaction { digest } } }`, {
117
- id: loanId,
118
- });
119
- const d = await gql(`query($d: String!) { transaction(digest: $d) { kind { ... on ProgrammableTransaction { inputs(first: 50) { nodes { ... on MoveValue { json } } } commands { nodes { ... on MoveCallCommand { function { name module { name } } arguments { ... on Input { ix } } } } } } } } }`, { d: prev.object.previousTransaction.digest });
120
- const kind = d.transaction.kind;
121
- for (const c of kind.commands.nodes) {
130
+ /**
131
+ * A seized loan's last transaction is the seizing call, which emits `LoanUpdated` (`liquidation.move:377,404,629`);
132
+ * `p_spot` is the pure input at the call's p_spot position.
133
+ */
134
+ function seizureOf(txs) {
135
+ const kind = txs.at(-1)?.kind;
136
+ for (const c of kind?.commands?.nodes ?? []) {
122
137
  const name = c.function?.name;
123
138
  if (c.function?.module?.name !== "liquidation" || !(name in SEIZING))
124
139
  continue;
@@ -129,9 +144,8 @@ async function readSeizure(gql, loanId) {
129
144
  throw new Error("the loan's last transaction is not a seizure");
130
145
  }
131
146
  /** `now_s` is input 14 of `settle::settle` (`services/relayer-v3/src/kinds/loan.ts` settle). */
132
- async function readSettleTime(gql, loanId) {
133
- const d = await gql(`query($id: SuiAddress!) { transactions(filter: { affectedObject: $id }, first: 50) { nodes { kind { ... on ProgrammableTransaction { inputs(first: 50) { nodes { ... on MoveValue { json } } } commands { nodes { ... on MoveCallCommand { function { name module { name } } arguments { ... on Input { ix } } } } } } } } } }`, { id: loanId });
134
- for (const t of d.transactions.nodes)
147
+ function settleTimeOf(txs) {
148
+ for (const t of txs)
135
149
  for (const c of t.kind?.commands?.nodes ?? [])
136
150
  if (c.function?.module?.name === "settle" && c.function.name === "settle")
137
151
  return BigInt(t.kind.inputs.nodes[c.arguments[14].ix].json);
@@ -147,10 +161,9 @@ const KEEPER_CT_ARG = {
147
161
  "liquidation.topup": 15,
148
162
  "liquidation.topup_by_borrower": 16,
149
163
  };
150
- async function readKeeperCt(gql, loanId) {
151
- const d = await gql(`query($id: SuiAddress!) { transactions(filter: { affectedObject: $id }, last: 50) { nodes { kind { ... on ProgrammableTransaction { inputs(first: 50) { nodes { ... on MoveValue { json } } } commands { nodes { ... on MoveCallCommand { function { name module { name } } arguments { ... on Input { ix } } } } } } } } } }`, { id: loanId });
164
+ function keeperCtOf(txs) {
152
165
  let latest = null;
153
- for (const t of d.transactions.nodes)
166
+ for (const t of txs)
154
167
  for (const c of t.kind?.commands?.nodes ?? []) {
155
168
  const at = KEEPER_CT_ARG[`${c.function?.module?.name}.${c.function?.name}`];
156
169
  if (at === undefined)
@@ -161,10 +174,9 @@ async function readKeeperCt(gql, loanId) {
161
174
  throw new Error("no call wrote a keeper ciphertext for this loan");
162
175
  return latest;
163
176
  }
164
- async function readTopupDelivery(gql, loanId) {
165
- const d = await gql(`query($id: SuiAddress!) { transactions(filter: { affectedObject: $id }, last: 50) { nodes { kind { ... on ProgrammableTransaction { inputs(first: 50) { nodes { ... on MoveValue { json } } } commands { nodes { ... on MoveCallCommand { function { name module { name } } arguments { ... on Input { ix } } } } } } } } } }`, { id: loanId });
177
+ function topupDeliveryOf(txs) {
166
178
  let latest = null;
167
- for (const t of d.transactions.nodes)
179
+ for (const t of txs)
168
180
  for (const c of t.kind?.commands?.nodes ?? []) {
169
181
  const name = c.function?.name;
170
182
  if (c.function?.module?.name !== "liquidation" || !(name in TOPUP_DELIVERY))
@@ -174,22 +186,6 @@ async function readTopupDelivery(gql, loanId) {
174
186
  }
175
187
  return latest;
176
188
  }
177
- /** The id of each object `digest` created, by type; null when the transaction is not indexed in time. */
178
- async function createdBy(gql, digest) {
179
- for (let i = 0; i < INDEX_RETRIES; i++) {
180
- const d = await gql(`query($d: String!) { transaction(digest: $d) { effects { objectChanges { nodes { address idCreated outputState { asMoveObject { contents { type { repr } } } } } } } } }`, { d: digest });
181
- const nodes = d.transaction?.effects?.objectChanges?.nodes;
182
- if (nodes)
183
- return nodes
184
- .filter((n) => n.idCreated)
185
- .map((n) => ({
186
- address: n.address,
187
- type: n.outputState?.asMoveObject?.contents?.type?.repr ?? "",
188
- }));
189
- await new Promise((r) => setTimeout(r, 2000));
190
- }
191
- return null;
192
- }
193
189
  /** Query shape as `scripts/v3/upgrade-testnet.ts:94` reads an owner. */
194
190
  async function readObjectRef(gql, id) {
195
191
  const d = await gql(`query($id: SuiAddress!) { object(address: $id) { version digest owner { __typename ... on AddressOwner { address { address } } } } }`, { id });
@@ -198,23 +194,6 @@ async function readObjectRef(gql, id) {
198
194
  const owner = d.object.owner?.__typename === "AddressOwner" ? d.object.owner.address.address : null;
199
195
  return { version: String(d.object.version), digest: String(d.object.digest), owner };
200
196
  }
201
- /** The `keeper::Badge` a `keeper::mint_badge` created; the SDK checks its holder, registry and role. */
202
- async function readBadge(gql, digest) {
203
- const created = await createdBy(gql, digest);
204
- const id = created?.find((n) => /::keeper::Badge$/.test(n.type))?.address;
205
- if (!id)
206
- return null;
207
- return { id, json: (await objectOf(gql, id)).asMoveObject.contents.json };
208
- }
209
- /** The `SaleRoom` and the `ItemVault` a `sale_room::open` created. */
210
- async function readSaleOpened(gql, digest) {
211
- const created = (await createdBy(gql, digest)) ?? [];
212
- const room = created.find((n) => /::sale_room::SaleRoom</.test(n.type))?.address;
213
- const vault = created.find((n) => /::vault::ItemVault</.test(n.type))?.address;
214
- if (!room || !vault)
215
- throw new Error(`transaction ${digest} created no sale room and vault`);
216
- return { room, vault };
217
- }
218
197
  const INDEX_POLLS = 20;
219
198
  /**
220
199
  * True once public GraphQL's latest checkpoint is stamped at or after `landedAtMs`, so every read it serves sees
@@ -231,28 +210,69 @@ export async function waitIndexed(gql, landedAtMs, pauseMs) {
231
210
  }
232
211
  return false;
233
212
  }
234
- /** The loan and its `Round` `round` (the current one when omitted), a `Table<u64, Round>` entry under `rounds`. */
235
- async function readLoan(gql, id, round) {
236
- const json = (await objectOf(gql, id)).asMoveObject.contents.json;
237
- const key = Buffer.alloc(8);
238
- key.writeBigUInt64LE(round ?? BigInt(json.round));
239
- const d = await gql(`query($t: SuiAddress!, $k: Base64!) { address(address: $t) { dynamicField(name: { type: "u64", bcs: $k }) { value { ... on MoveValue { json } } } } }`, { t: json.rounds.id, k: key.toString("base64") });
240
- return { json, round: d.address?.dynamicField?.value?.json };
241
- }
242
- /**
243
- * One page of every `ShieldedLoan` instantiation. The type is named by its origin package, which every upgrade
244
- * keeps. No `round` per row: that is one more read per loan, and `loans.request` reads it for the one picked.
245
- */
246
- async function readLoans(gql, origin, cursor) {
247
- const d = await gql(`query($t: String!, $a: String) { objects(first: ${LOAN_PAGE}, after: $a, filter: { type: $t }) { nodes { address asMoveObject { contents { json } } } pageInfo { hasNextPage endCursor } } }`, { t: `${origin}::loan::ShieldedLoan`, a: cursor });
213
+ /** One page of every object of `type`, every instantiation of it when `type` names no type arguments. */
214
+ async function objectsPage(gql, type, cursor) {
215
+ const d = await gql(`query($t: String!, $a: String) { objects(first: ${LOAN_PAGE}, after: $a, filter: { type: $t }) { nodes { address owner { ... on ObjectOwner { address { address } } } asMoveObject { contents { json } } } pageInfo { hasNextPage endCursor } } }`, { t: type, a: cursor });
248
216
  return {
249
- loans: d.objects.nodes.map((n) => ({
217
+ rows: d.objects.nodes.map((n) => ({
250
218
  id: n.address,
251
219
  json: n.asMoveObject.contents.json,
220
+ owner: n.owner?.address?.address ?? null,
252
221
  })),
253
222
  next: d.objects.pageInfo.hasNextPage ? d.objects.pageInfo.endCursor : null,
254
223
  };
255
224
  }
225
+ async function allObjects(gql, type) {
226
+ const out = [];
227
+ for (let cursor = null;;) {
228
+ const page = await objectsPage(gql, type, cursor);
229
+ out.push(...page.rows);
230
+ if (page.next === null)
231
+ return out;
232
+ cursor = page.next;
233
+ }
234
+ }
235
+ const key = (id) => normalizeSuiAddress(id);
236
+ function onChain(hit, id) {
237
+ if (hit === undefined)
238
+ throw new Error(`object ${id} is not on chain`);
239
+ return hit;
240
+ }
241
+ /** Each object's transactions, oldest first, from every event of `type`; the event's `id` names the object. */
242
+ async function txsByEvent(gql, type) {
243
+ const out = new Map();
244
+ for (let after = null;;) {
245
+ const d = await gql(`query($t: String!, $a: String) { events(first: 50, after: $a, filter: { type: $t }) { nodes { contents { json } transaction { kind { ... on ProgrammableTransaction { inputs(first: 50) { nodes { ... on MoveValue { json } } } commands { nodes { ... on MoveCallCommand { function { name module { name } } arguments { ... on Input { ix } } } } } } } } } pageInfo { hasNextPage endCursor } } }`, { t: type, a: after });
246
+ for (const n of d.events.nodes) {
247
+ const id = key(String(n.contents.json.id));
248
+ out.set(id, [...(out.get(id) ?? []), { kind: n.transaction?.kind }]);
249
+ }
250
+ if (!d.events.pageInfo.hasNextPage)
251
+ return out;
252
+ after = d.events.pageInfo.endCursor;
253
+ }
254
+ }
255
+ /**
256
+ * Every `ShieldedLoan` and every `Round` field of every loan's `rounds` table (`loan.move:88-127`). A field's owner
257
+ * is the table, and its `json.value` is what a `dynamicField` read of that key returns.
258
+ */
259
+ async function loanSet(gql, origin) {
260
+ const loans = new Map();
261
+ for (const l of await allObjects(gql, `${origin}::loan::ShieldedLoan`))
262
+ loans.set(key(l.id), l.json);
263
+ const rounds = new Map();
264
+ for (const r of await allObjects(gql, `0x2::dynamic_field::Field<u64, ${origin}::loan::Round>`))
265
+ if (r.owner)
266
+ rounds.set(`${key(r.owner)}:${r.json.name}`, r.json.value);
267
+ return { loans, rounds };
268
+ }
269
+ /** The loan and its `Round` `round` (the current one when omitted), picked from the whole loan set. */
270
+ const loanOf = (set, id, round) => {
271
+ const json = set.loans.get(key(id));
272
+ if (!json)
273
+ return undefined;
274
+ return { json, round: set.rounds.get(`${key(json.rounds.id)}:${round ?? json.round}`) };
275
+ };
256
276
  /** `lock` and `sealed` are arguments 8 and 16 of `sale_room::bid` (`sale_room.move:245-268`). */
257
277
  const BID_LOCK_ARG = 8;
258
278
  const BID_SEALED_ARG = 16;
@@ -260,10 +280,9 @@ const BID_SEALED_ARG = 16;
260
280
  * The room stores each bid's EncryptedObject parsed, and GraphQL gives it back as a struct. The bytes `bid` took
261
281
  * are the call's own input, keyed here by the bid's lock.
262
282
  */
263
- async function sealedBids(gql, roomId) {
264
- const d = await gql(`query($id: SuiAddress!) { transactions(filter: { affectedObject: $id }, last: 50) { nodes { kind { ... on ProgrammableTransaction { inputs(first: 50) { nodes { ... on MoveValue { json } } } commands { nodes { ... on MoveCallCommand { function { name module { name } } arguments { ... on Input { ix } } } } } } } } } }`, { id: roomId });
283
+ function sealedBids(txs) {
265
284
  const out = new Map();
266
- for (const t of d.transactions.nodes)
285
+ for (const t of txs)
267
286
  for (const c of t.kind?.commands?.nodes ?? []) {
268
287
  if (c.function?.module?.name !== "sale_room" || c.function.name !== "bid")
269
288
  continue;
@@ -272,51 +291,44 @@ async function sealedBids(gql, roomId) {
272
291
  }
273
292
  return out;
274
293
  }
275
- /** The `SaleRoom` fields, each bid's `sealed` replaced by the base64 bytes it was bid with. */
276
- async function readRoom(gql, id) {
277
- const json = (await objectOf(gql, id)).asMoveObject.contents.json;
278
- const sealed = await sealedBids(gql, id);
279
- const bids = json.bids.map((b) => ({ ...b, sealed: sealed.get(String(b.lock)) }));
280
- return { json: { ...json, bids } };
294
+ /**
295
+ * Every `SaleRoom`, then every `RoomUpdated` with its transaction: `bid` emits it (`sale_room.move:301`), and walking
296
+ * events after objects means every bid a room lists has its transaction here.
297
+ */
298
+ async function roomSet(gql, origin) {
299
+ const rooms = new Map();
300
+ for (const r of await allObjects(gql, `${origin}::sale_room::SaleRoom`))
301
+ rooms.set(key(r.id), r.json);
302
+ return { rooms, txs: await txsByEvent(gql, `${origin}::sale_room::RoomUpdated`) };
281
303
  }
282
- async function readRooms(gql, origin, cursor) {
283
- const d = await gql(`query($t: String!, $a: String) { objects(first: ${LOAN_PAGE}, after: $a, filter: { type: $t }) { nodes { address asMoveObject { contents { json } } } pageInfo { hasNextPage endCursor } } }`, { t: `${origin}::sale_room::SaleRoom`, a: cursor });
304
+ /** The `SaleRoom` fields, each bid's `sealed` replaced by the base64 bytes it was bid with. */
305
+ const roomOf = (set, id) => {
306
+ const json = set.rooms.get(key(id));
307
+ if (!json)
308
+ return undefined;
309
+ const sealed = sealedBids(set.txs.get(key(id)) ?? []);
284
310
  return {
285
- rooms: d.objects.nodes.map((n) => ({
286
- id: n.address,
287
- json: n.asMoveObject.contents.json,
288
- })),
289
- next: d.objects.pageInfo.hasNextPage ? d.objects.pageInfo.endCursor : null,
311
+ json: { ...json, bids: json.bids.map((b) => ({ ...b, sealed: sealed.get(String(b.lock)) })) },
290
312
  };
291
- }
292
- /** A `SaleRoom` does not name its vault (`sale_room.move:115-143`); the `ItemVault` names its room. */
293
- async function readVaultOf(gql, origin, room) {
294
- const want = normalizeSuiAddress(room);
295
- let after = null;
296
- for (;;) {
297
- const d = await gql(`query($t: String!, $a: String) { objects(first: ${LOAN_PAGE}, after: $a, filter: { type: $t }) { nodes { address asMoveObject { contents { json } } } pageInfo { hasNextPage endCursor } } }`, { t: `${origin}::vault::ItemVault`, a: after });
298
- const hit = d.objects.nodes.find((n) => normalizeSuiAddress(String(n.asMoveObject.contents.json.room_id)) === want);
299
- if (hit)
300
- return hit.address;
301
- if (!d.objects.pageInfo.hasNextPage)
302
- throw new Error(`room ${room} has no item vault`);
303
- after = d.objects.pageInfo.endCursor;
304
- }
313
+ };
314
+ async function vaultSet(gql, origin) {
315
+ return new Map((await allObjects(gql, `${origin}::vault::ItemVault`)).map((v) => [key(v.id), v]));
305
316
  }
306
317
  /** A sponsored sender must be one the chain has never seen: any transaction touching it, or a balance it holds. */
307
318
  async function readAddressUsed(gql, address) {
308
319
  const d = await gql(`query($a: SuiAddress!) { address(address: $a) { balances(first: 1) { nodes { totalBalance } } transactions(first: 1, relation: AFFECTED) { nodes { digest } } } }`, { a: address });
309
320
  return (d.address?.balances?.nodes?.length ?? 0) > 0 || (d.address?.transactions?.nodes?.length ?? 0) > 0;
310
321
  }
311
- function sealClient(config, url) {
322
+ function sealClient(config, url, fetch) {
312
323
  return new SealClient({
313
- suiClient: new SuiGraphQLClient({ url, network: "testnet" }),
324
+ suiClient: graphqlClient(url, fetch),
314
325
  serverConfigs: config.seal.servers.map((s) => ({
315
326
  objectId: s.objectId,
316
327
  weight: 1,
317
328
  aggregatorUrl: s.aggregatorUrl,
318
329
  })),
319
330
  verifyKeyServers: false,
331
+ fetch: fetch,
320
332
  });
321
333
  }
322
334
  /** A Seal key id is namespaced by the original id of the package whose `seal_approve*` releases it. */
@@ -326,8 +338,8 @@ function originOf(config, pkg = "loan") {
326
338
  throw new Error(`the deployment record has no ${pkg} package origin`);
327
339
  return id;
328
340
  }
329
- function sealerFor(config, url, garble) {
330
- const client = sealClient(config, url);
341
+ function sealerFor(config, url, fetch, garble) {
342
+ const client = sealClient(config, url, fetch);
331
343
  return async ({ id, data, aad, pkg, }) => (await client.encrypt({
332
344
  demType: DemType.Hmac256Ctr,
333
345
  threshold: config.seal.threshold,
@@ -342,8 +354,8 @@ function sealerFor(config, url, garble) {
342
354
  * A badge policy checks the session's own address, so the SDK hands over the badge holder's signer.
343
355
  * Returns the session key and the approve call's transaction kind bytes.
344
356
  */
345
- async function sealSession(config, url, { approve, pkg, signer: holder }) {
346
- const sui = new SuiGraphQLClient({ url, network: "testnet" });
357
+ async function sealSession(config, url, fetch, { approve, pkg, signer: holder }) {
358
+ const sui = graphqlClient(url, fetch);
347
359
  const signer = holder ?? Ed25519Keypair.generate();
348
360
  const address = signer.toSuiAddress();
349
361
  const sessionKey = await SessionKey.create({
@@ -366,25 +378,41 @@ async function sealSession(config, url, { approve, pkg, signer: holder }) {
366
378
  const txBytes = await tx.build({ client: sui, onlyTransactionKind: true });
367
379
  return { sessionKey, txBytes };
368
380
  }
369
- function unsealerFor(config, url) {
370
- const client = sealClient(config, url);
371
- return async (r) => client.decrypt({ data: r.sealed, ...(await sealSession(config, url, r)) });
381
+ function unsealerFor(config, url, fetch) {
382
+ const client = sealClient(config, url, fetch);
383
+ return async (r) => client.decrypt({ data: r.sealed, ...(await sealSession(config, url, fetch, r)) });
372
384
  }
373
385
  /** Seal's per-server derived keys for `id`, the inputs `offer::slash` decrypts with on chain. */
374
- function deriverFor(config, url) {
375
- const client = sealClient(config, url);
386
+ function deriverFor(config, url, fetch) {
387
+ const client = sealClient(config, url, fetch);
376
388
  return async (r) => {
377
389
  const keys = await client.getDerivedKeys({
378
390
  id: Buffer.from(r.id).toString("hex"),
379
391
  threshold: config.seal.threshold,
380
- ...(await sealSession(config, url, r)),
392
+ ...(await sealSession(config, url, fetch, r)),
381
393
  });
382
394
  return new Map([...keys].map(([server, k]) => [server, Uint8Array.from(Buffer.from(k.toString(), "hex"))]));
383
395
  };
384
396
  }
385
397
  export function chainIo(config, o) {
386
- const fetch = o.fetch ?? ((url, init) => globalThis.fetch(url, init));
398
+ const fetch = o.fetch ? fixedHeaders(o.fetch) : plainFetch;
387
399
  const gql = graphql(o.graphql, fetch);
400
+ const ttl = o.snapshotMs ?? SNAPSHOT_MS;
401
+ const loanOrigin = () => originOf(config, "loan");
402
+ const saleOrigin = () => originOf(config, "sale");
403
+ const loans = snapshot(() => loanSet(gql, loanOrigin()), ttl);
404
+ const loanTxs = snapshot(() => txsByEvent(gql, `${loanOrigin()}::loan::LoanUpdated`), ttl);
405
+ const rooms = snapshot(() => roomSet(gql, saleOrigin()), ttl);
406
+ const vaults = snapshot(() => vaultSet(gql, saleOrigin()), ttl);
407
+ const markets = snapshot(() => marketSet(gql, Object.values(config.objects.markets ?? {}).filter((id) => !!id)), ttl);
408
+ const sets = [loans, loanTxs, rooms, vaults, markets];
409
+ const marketOf = async (id) => {
410
+ const hit = await markets.find((m) => m.get(key(id)));
411
+ if (!hit)
412
+ throw new Error(`market ${id} is not in the deployment record`);
413
+ return hit;
414
+ };
415
+ const txsOf = async (loanId) => (await loanTxs.find((m) => m.get(key(loanId)))) ?? [];
388
416
  const pools = config.objects.pools;
389
417
  const pkg = config.packages.pool;
390
418
  const cache = o.artifactDir ? artifactCache(fetch, config.circuits, o.artifactDir) : undefined;
@@ -396,31 +424,57 @@ export function chainIo(config, o) {
396
424
  };
397
425
  return {
398
426
  prefetchArtifacts: () => cache?.prefetch(),
399
- waitIndexed: (landedAtMs) => waitIndexed(gql, landedAtMs, o.indexPauseMs ?? 1500),
427
+ /** A landed step makes every held walk stale. */
428
+ waitIndexed: async (landedAtMs) => {
429
+ try {
430
+ return await waitIndexed(gql, landedAtMs, o.indexPauseMs ?? 1500);
431
+ }
432
+ finally {
433
+ for (const s of sets)
434
+ s.drop();
435
+ }
436
+ },
400
437
  prover: v3.groth16Prover(snarkjs.groth16, artifacts),
401
- readPrice: (market) => readPrice(gql, market),
402
- readReading: (market) => readReading(gql, market),
403
- readSeizure: (loanId) => readSeizure(gql, loanId),
404
- readSettleTime: (loanId) => readSettleTime(gql, loanId),
405
- readTopupDelivery: (loanId) => readTopupDelivery(gql, loanId),
406
- readKeeperCt: (loanId) => readKeeperCt(gql, loanId),
407
- readBadge: (digest) => readBadge(gql, digest),
408
- readSaleOpened: (digest) => readSaleOpened(gql, digest),
438
+ readPrice: async (market) => priceOf(await marketOf(market)),
439
+ readReading: async (market) => readingOf(await marketOf(market)),
440
+ readSeizure: async (loanId) => seizureOf(await txsOf(loanId)),
441
+ readSettleTime: async (loanId) => settleTimeOf(await txsOf(loanId)),
442
+ readTopupDelivery: async (loanId) => topupDeliveryOf(await txsOf(loanId)),
443
+ readKeeperCt: async (loanId) => keeperCtOf(await txsOf(loanId)),
444
+ readBadges: async (cursor) => {
445
+ const page = await objectsPage(gql, `${loanOrigin()}::keeper::Badge`, cursor);
446
+ return { badges: page.rows.map(({ id, json }) => ({ id, json })), next: page.next };
447
+ },
409
448
  readObjectRef: (id) => readObjectRef(gql, id),
410
- readRoom: (id) => readRoom(gql, id),
411
- readRooms: async (cursor) => readRooms(gql, originOf(config, "sale"), cursor),
412
- readVaultOf: async (room) => readVaultOf(gql, originOf(config, "sale"), room),
449
+ readRoom: async (id) => onChain(await rooms.find((s) => roomOf(s, id)), id),
450
+ readRooms: async (cursor) => {
451
+ const page = await objectsPage(gql, `${saleOrigin()}::sale_room::SaleRoom`, cursor);
452
+ return { rooms: page.rows.map(({ id, json }) => ({ id, json })), next: page.next };
453
+ },
454
+ readVaultOf: async (room) => {
455
+ const want = key(room);
456
+ const hit = await vaults.find((m) => [...m.values()].find((v) => key(String(v.json.room_id)) === want));
457
+ if (!hit)
458
+ throw new Error(`room ${room} has no item vault`);
459
+ return hit.id;
460
+ },
413
461
  readAddressUsed: (address) => readAddressUsed(gql, address),
414
- readVault: async (id) => ({ json: (await objectOf(gql, id)).asMoveObject.contents.json }),
415
- readMarket: async (id) => (await objectOf(gql, id)).asMoveObject.contents.json,
416
- sealEncrypt: sealerFor(config, o.graphql, o.garble ?? (() => false)),
417
- sealDecrypt: unsealerFor(config, o.graphql),
418
- sealDerivedKeys: deriverFor(config, o.graphql),
419
- readLoan: (id, round) => readLoan(gql, id, round),
420
- readLoans: (cursor) => readLoans(gql, config.packageOrigins.loan, cursor),
462
+ readVault: async (id) => ({ json: onChain(await vaults.find((m) => m.get(key(id))), id).json }),
463
+ readMarket: async (id) => (await marketOf(id)).market,
464
+ sealEncrypt: sealerFor(config, o.graphql, fetch, o.garble ?? (() => false)),
465
+ sealDecrypt: unsealerFor(config, o.graphql, fetch),
466
+ sealDerivedKeys: deriverFor(config, o.graphql, fetch),
467
+ readLoan: async (id, round) => onChain(await loans.find((s) => loanOf(s, id, round)), id),
468
+ readLoans: async (cursor) => {
469
+ const page = await objectsPage(gql, `${loanOrigin()}::loan::ShieldedLoan`, cursor);
470
+ return { loans: page.rows.map(({ id, json }) => ({ id, json })), next: page.next };
471
+ },
421
472
  priceUpdate: async () => Uint8Array.of(0),
422
473
  fundDeposit: o.fundDeposit,
423
- readFeeCommit: async (coin) => BigInt((await objectOf(gql, config.objects.feeConfigs[coin])).asMoveObject.contents.json.fee_commit),
474
+ readFeeCommit: async (coin, lane) => {
475
+ const ids = lane === "edge" ? config.objects.edgeFeeConfigs : config.objects.feeConfigs;
476
+ return BigInt((await objectOf(gql, ids[coin])).asMoveObject.contents.json.fee_commit);
477
+ },
424
478
  readSharedVersion: async (id) => String((await objectOf(gql, id)).owner.initialSharedVersion),
425
479
  readPool: async (coin) => {
426
480
  const id = pools[coin];
package/dist/keys.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
2
+ /** PRV-36b: a note key inside the state file's directory travels with every copy of the sealed records and state. */
3
+ export declare function keyInside(noteKeyFile: string, stateFile: string): boolean;
2
4
  /** The `suiprivkey` text `essey-sui-mcp-v3-init` writes. A refusal names the variable and not the file's text. */
3
5
  export declare function loadAgentKey(path: string): Ed25519Keypair;
4
6
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAqB9D,kHAAkH;AAClH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAczD;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAYrD"}
1
+ {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AA6B9D,qHAAqH;AACrH,wBAAgB,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAEzE;AAED,kHAAkH;AAClH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAczD;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAYrD"}
package/dist/keys.js CHANGED
@@ -1,4 +1,5 @@
1
- import { lstatSync, readFileSync } from "node:fs";
1
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
2
+ import { dirname, resolve, sep } from "node:path";
2
3
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
3
4
  import { ConfigError } from "./config.js";
4
5
  function fail(msg) {
@@ -20,6 +21,18 @@ function statKey(path, what, max) {
20
21
  if (st.size < 1 || st.size > max)
21
22
  fail(`${what} must be a key file`);
22
23
  }
24
+ const real = (p) => {
25
+ try {
26
+ return realpathSync(p);
27
+ }
28
+ catch {
29
+ return resolve(p);
30
+ }
31
+ };
32
+ /** PRV-36b: a note key inside the state file's directory travels with every copy of the sealed records and state. */
33
+ export function keyInside(noteKeyFile, stateFile) {
34
+ return real(noteKeyFile).startsWith(`${real(dirname(stateFile))}${sep}`);
35
+ }
23
36
  /** The `suiprivkey` text `essey-sui-mcp-v3-init` writes. A refusal names the variable and not the file's text. */
24
37
  export function loadAgentKey(path) {
25
38
  statKey(path, "ESSEY_AGENT_KEY_FILE", 4096);