@esseyonsui/sui-mcp-v3 0.1.8 → 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 (52) 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/artifact-cache.d.ts +14 -0
  8. package/dist/artifact-cache.d.ts.map +1 -0
  9. package/dist/artifact-cache.js +48 -0
  10. package/dist/client.d.ts +1 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +5 -3
  13. package/dist/config.d.ts +2 -0
  14. package/dist/config.d.ts.map +1 -1
  15. package/dist/config.js +5 -0
  16. package/dist/fund.d.ts.map +1 -1
  17. package/dist/fund.js +2 -2
  18. package/dist/handles.d.ts +23 -0
  19. package/dist/handles.d.ts.map +1 -0
  20. package/dist/handles.js +142 -0
  21. package/dist/http.d.ts +6 -0
  22. package/dist/http.d.ts.map +1 -0
  23. package/dist/http.js +5 -0
  24. package/dist/init.d.ts +7 -0
  25. package/dist/init.d.ts.map +1 -1
  26. package/dist/init.js +18 -11
  27. package/dist/io.d.ts +22 -12
  28. package/dist/io.d.ts.map +1 -1
  29. package/dist/io.js +194 -142
  30. package/dist/keys.d.ts +2 -0
  31. package/dist/keys.d.ts.map +1 -1
  32. package/dist/keys.js +14 -1
  33. package/dist/main.js +21 -9
  34. package/dist/records.d.ts +21 -4
  35. package/dist/records.d.ts.map +1 -1
  36. package/dist/records.js +74 -21
  37. package/dist/reveal.d.ts +7 -0
  38. package/dist/reveal.d.ts.map +1 -0
  39. package/dist/reveal.js +40 -0
  40. package/dist/snapshot.d.ts +13 -0
  41. package/dist/snapshot.d.ts.map +1 -0
  42. package/dist/snapshot.js +29 -0
  43. package/dist/tools-badge.js +3 -3
  44. package/dist/tools-more.d.ts +9 -5
  45. package/dist/tools-more.d.ts.map +1 -1
  46. package/dist/tools-more.js +56 -12
  47. package/dist/tools-sales.d.ts.map +1 -1
  48. package/dist/tools-sales.js +34 -24
  49. package/dist/tools.d.ts +3 -0
  50. package/dist/tools.d.ts.map +1 -1
  51. package/dist/tools.js +64 -30
  52. package/package.json +4 -3
package/dist/io.js CHANGED
@@ -3,16 +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";
10
+ import { artifactCache } from "./artifact-cache.js";
11
+ import { graphqlClient, plainFetch } from "./http.js";
12
+ import { snapshot } from "./snapshot.js";
11
13
  export { TESTNET_GRAPHQL } from "./config.js";
12
14
  const require = createRequire(import.meta.url);
13
15
  const snarkjs = require("snarkjs");
14
16
  const INDEX_RETRIES = 15;
15
17
  const LOAN_PAGE = 50;
18
+ const SNAPSHOT_MS = 5_000;
16
19
  function graphql(url, fetch) {
17
20
  return async (query, variables) => {
18
21
  const res = await fetch(url, {
@@ -58,13 +61,28 @@ const grew = (n, id, field) => n.transaction.effects.objectChanges.nodes.some((c
58
61
  });
59
62
  const leaves = (pool) => pool.tree.next_index;
60
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
+ }
61
80
  /**
62
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
63
82
  * byte: a stand-in feed as the admin set it, a Pyth `PriceInfoObject` (same layout) as others last updated it.
64
83
  */
65
- async function readPrice(gql, market) {
66
- const m = (await objectOf(gql, market)).asMoveObject.contents.json;
67
- 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;
68
86
  const spot = BigInt(info.price.price.magnitude);
69
87
  const ema = BigInt(info.ema_price.price.magnitude);
70
88
  const expo = BigInt(info.price.expo.magnitude);
@@ -96,9 +114,8 @@ export function invertReading(spot, ema, spotExpo, emaExpo) {
96
114
  return { spot: scale(s, sExp), ema: scale(e, eExp), expo };
97
115
  }
98
116
  /** The stand-in oracle's `price::Reading`: publish_s is the older of the two feed timestamps. */
99
- async function readReading(gql, market) {
100
- const m = (await objectOf(gql, market)).asMoveObject.contents.json;
101
- 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;
102
119
  const [spotS, emaS] = [BigInt(f.price.timestamp), BigInt(f.ema_price.timestamp)];
103
120
  return {
104
121
  oracle: m.oracle,
@@ -110,14 +127,13 @@ async function readReading(gql, market) {
110
127
  };
111
128
  }
112
129
  const SEIZING = { liquidate: 5, claim_default: 7, fault_liquidate: 5 };
113
- /** A seized loan's last transaction is the seizing call; `p_spot` is the pure input at the call's p_spot position. */
114
- async function readSeizure(gql, loanId) {
115
- const prev = await gql(`query($id: SuiAddress!) { object(address: $id) { previousTransaction { digest } } }`, {
116
- id: loanId,
117
- });
118
- 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 });
119
- const kind = d.transaction.kind;
120
- 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 ?? []) {
121
137
  const name = c.function?.name;
122
138
  if (c.function?.module?.name !== "liquidation" || !(name in SEIZING))
123
139
  continue;
@@ -128,9 +144,8 @@ async function readSeizure(gql, loanId) {
128
144
  throw new Error("the loan's last transaction is not a seizure");
129
145
  }
130
146
  /** `now_s` is input 14 of `settle::settle` (`services/relayer-v3/src/kinds/loan.ts` settle). */
131
- async function readSettleTime(gql, loanId) {
132
- 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 });
133
- for (const t of d.transactions.nodes)
147
+ function settleTimeOf(txs) {
148
+ for (const t of txs)
134
149
  for (const c of t.kind?.commands?.nodes ?? [])
135
150
  if (c.function?.module?.name === "settle" && c.function.name === "settle")
136
151
  return BigInt(t.kind.inputs.nodes[c.arguments[14].ix].json);
@@ -146,10 +161,9 @@ const KEEPER_CT_ARG = {
146
161
  "liquidation.topup": 15,
147
162
  "liquidation.topup_by_borrower": 16,
148
163
  };
149
- async function readKeeperCt(gql, loanId) {
150
- 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) {
151
165
  let latest = null;
152
- for (const t of d.transactions.nodes)
166
+ for (const t of txs)
153
167
  for (const c of t.kind?.commands?.nodes ?? []) {
154
168
  const at = KEEPER_CT_ARG[`${c.function?.module?.name}.${c.function?.name}`];
155
169
  if (at === undefined)
@@ -160,10 +174,9 @@ async function readKeeperCt(gql, loanId) {
160
174
  throw new Error("no call wrote a keeper ciphertext for this loan");
161
175
  return latest;
162
176
  }
163
- async function readTopupDelivery(gql, loanId) {
164
- 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) {
165
178
  let latest = null;
166
- for (const t of d.transactions.nodes)
179
+ for (const t of txs)
167
180
  for (const c of t.kind?.commands?.nodes ?? []) {
168
181
  const name = c.function?.name;
169
182
  if (c.function?.module?.name !== "liquidation" || !(name in TOPUP_DELIVERY))
@@ -173,26 +186,6 @@ async function readTopupDelivery(gql, loanId) {
173
186
  }
174
187
  return latest;
175
188
  }
176
- /** The id of each object `digest` created, by type; null when the transaction is not indexed in time. */
177
- async function createdBy(gql, digest) {
178
- for (let i = 0; i < INDEX_RETRIES; i++) {
179
- const d = await gql(`query($d: String!) { transaction(digest: $d) { effects { objectChanges { nodes { address idCreated outputState { asMoveObject { contents { type { repr } } } } } } } } }`, { d: digest });
180
- const nodes = d.transaction?.effects?.objectChanges?.nodes;
181
- if (nodes)
182
- return nodes
183
- .filter((n) => n.idCreated)
184
- .map((n) => ({
185
- address: n.address,
186
- type: n.outputState?.asMoveObject?.contents?.type?.repr ?? "",
187
- }));
188
- await new Promise((r) => setTimeout(r, 2000));
189
- }
190
- return null;
191
- }
192
- async function readCreated(gql, digest) {
193
- const created = await createdBy(gql, digest);
194
- return created?.find((n) => /::loan::ShieldedLoan</.test(n.type))?.address ?? null;
195
- }
196
189
  /** Query shape as `scripts/v3/upgrade-testnet.ts:94` reads an owner. */
197
190
  async function readObjectRef(gql, id) {
198
191
  const d = await gql(`query($id: SuiAddress!) { object(address: $id) { version digest owner { __typename ... on AddressOwner { address { address } } } } }`, { id });
@@ -201,23 +194,6 @@ async function readObjectRef(gql, id) {
201
194
  const owner = d.object.owner?.__typename === "AddressOwner" ? d.object.owner.address.address : null;
202
195
  return { version: String(d.object.version), digest: String(d.object.digest), owner };
203
196
  }
204
- /** The `keeper::Badge` a `keeper::mint_badge` created; the SDK checks its holder, registry and role. */
205
- async function readBadge(gql, digest) {
206
- const created = await createdBy(gql, digest);
207
- const id = created?.find((n) => /::keeper::Badge$/.test(n.type))?.address;
208
- if (!id)
209
- return null;
210
- return { id, json: (await objectOf(gql, id)).asMoveObject.contents.json };
211
- }
212
- /** The `SaleRoom` and the `ItemVault` a `sale_room::open` created. */
213
- async function readSaleOpened(gql, digest) {
214
- const created = (await createdBy(gql, digest)) ?? [];
215
- const room = created.find((n) => /::sale_room::SaleRoom</.test(n.type))?.address;
216
- const vault = created.find((n) => /::vault::ItemVault</.test(n.type))?.address;
217
- if (!room || !vault)
218
- throw new Error(`transaction ${digest} created no sale room and vault`);
219
- return { room, vault };
220
- }
221
197
  const INDEX_POLLS = 20;
222
198
  /**
223
199
  * True once public GraphQL's latest checkpoint is stamped at or after `landedAtMs`, so every read it serves sees
@@ -234,28 +210,69 @@ export async function waitIndexed(gql, landedAtMs, pauseMs) {
234
210
  }
235
211
  return false;
236
212
  }
237
- /** The loan and its `Round` `round` (the current one when omitted), a `Table<u64, Round>` entry under `rounds`. */
238
- async function readLoan(gql, id, round) {
239
- const json = (await objectOf(gql, id)).asMoveObject.contents.json;
240
- const key = Buffer.alloc(8);
241
- key.writeBigUInt64LE(round ?? BigInt(json.round));
242
- 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") });
243
- return { json, round: d.address?.dynamicField?.value?.json };
244
- }
245
- /**
246
- * One page of every `ShieldedLoan` instantiation. The type is named by its origin package, which every upgrade
247
- * keeps. No `round` per row: that is one more read per loan, and `loans.request` reads it for the one picked.
248
- */
249
- async function readLoans(gql, origin, cursor) {
250
- 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 });
251
216
  return {
252
- loans: d.objects.nodes.map((n) => ({
217
+ rows: d.objects.nodes.map((n) => ({
253
218
  id: n.address,
254
219
  json: n.asMoveObject.contents.json,
220
+ owner: n.owner?.address?.address ?? null,
255
221
  })),
256
222
  next: d.objects.pageInfo.hasNextPage ? d.objects.pageInfo.endCursor : null,
257
223
  };
258
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
+ };
259
276
  /** `lock` and `sealed` are arguments 8 and 16 of `sale_room::bid` (`sale_room.move:245-268`). */
260
277
  const BID_LOCK_ARG = 8;
261
278
  const BID_SEALED_ARG = 16;
@@ -263,10 +280,9 @@ const BID_SEALED_ARG = 16;
263
280
  * The room stores each bid's EncryptedObject parsed, and GraphQL gives it back as a struct. The bytes `bid` took
264
281
  * are the call's own input, keyed here by the bid's lock.
265
282
  */
266
- async function sealedBids(gql, roomId) {
267
- 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) {
268
284
  const out = new Map();
269
- for (const t of d.transactions.nodes)
285
+ for (const t of txs)
270
286
  for (const c of t.kind?.commands?.nodes ?? []) {
271
287
  if (c.function?.module?.name !== "sale_room" || c.function.name !== "bid")
272
288
  continue;
@@ -275,51 +291,44 @@ async function sealedBids(gql, roomId) {
275
291
  }
276
292
  return out;
277
293
  }
278
- /** The `SaleRoom` fields, each bid's `sealed` replaced by the base64 bytes it was bid with. */
279
- async function readRoom(gql, id) {
280
- const json = (await objectOf(gql, id)).asMoveObject.contents.json;
281
- const sealed = await sealedBids(gql, id);
282
- const bids = json.bids.map((b) => ({ ...b, sealed: sealed.get(String(b.lock)) }));
283
- 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`) };
284
303
  }
285
- async function readRooms(gql, origin, cursor) {
286
- 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)) ?? []);
287
310
  return {
288
- rooms: d.objects.nodes.map((n) => ({
289
- id: n.address,
290
- json: n.asMoveObject.contents.json,
291
- })),
292
- 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)) })) },
293
312
  };
294
- }
295
- /** A `SaleRoom` does not name its vault (`sale_room.move:115-143`); the `ItemVault` names its room. */
296
- async function readVaultOf(gql, origin, room) {
297
- const want = normalizeSuiAddress(room);
298
- let after = null;
299
- for (;;) {
300
- 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 });
301
- const hit = d.objects.nodes.find((n) => normalizeSuiAddress(String(n.asMoveObject.contents.json.room_id)) === want);
302
- if (hit)
303
- return hit.address;
304
- if (!d.objects.pageInfo.hasNextPage)
305
- throw new Error(`room ${room} has no item vault`);
306
- after = d.objects.pageInfo.endCursor;
307
- }
313
+ };
314
+ async function vaultSet(gql, origin) {
315
+ return new Map((await allObjects(gql, `${origin}::vault::ItemVault`)).map((v) => [key(v.id), v]));
308
316
  }
309
317
  /** A sponsored sender must be one the chain has never seen: any transaction touching it, or a balance it holds. */
310
318
  async function readAddressUsed(gql, address) {
311
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 });
312
320
  return (d.address?.balances?.nodes?.length ?? 0) > 0 || (d.address?.transactions?.nodes?.length ?? 0) > 0;
313
321
  }
314
- function sealClient(config, url) {
322
+ function sealClient(config, url, fetch) {
315
323
  return new SealClient({
316
- suiClient: new SuiGraphQLClient({ url, network: "testnet" }),
324
+ suiClient: graphqlClient(url, fetch),
317
325
  serverConfigs: config.seal.servers.map((s) => ({
318
326
  objectId: s.objectId,
319
327
  weight: 1,
320
328
  aggregatorUrl: s.aggregatorUrl,
321
329
  })),
322
330
  verifyKeyServers: false,
331
+ fetch: fetch,
323
332
  });
324
333
  }
325
334
  /** A Seal key id is namespaced by the original id of the package whose `seal_approve*` releases it. */
@@ -329,8 +338,8 @@ function originOf(config, pkg = "loan") {
329
338
  throw new Error(`the deployment record has no ${pkg} package origin`);
330
339
  return id;
331
340
  }
332
- function sealerFor(config, url, garble) {
333
- const client = sealClient(config, url);
341
+ function sealerFor(config, url, fetch, garble) {
342
+ const client = sealClient(config, url, fetch);
334
343
  return async ({ id, data, aad, pkg, }) => (await client.encrypt({
335
344
  demType: DemType.Hmac256Ctr,
336
345
  threshold: config.seal.threshold,
@@ -345,8 +354,8 @@ function sealerFor(config, url, garble) {
345
354
  * A badge policy checks the session's own address, so the SDK hands over the badge holder's signer.
346
355
  * Returns the session key and the approve call's transaction kind bytes.
347
356
  */
348
- async function sealSession(config, url, { approve, pkg, signer: holder }) {
349
- const sui = new SuiGraphQLClient({ url, network: "testnet" });
357
+ async function sealSession(config, url, fetch, { approve, pkg, signer: holder }) {
358
+ const sui = graphqlClient(url, fetch);
350
359
  const signer = holder ?? Ed25519Keypair.generate();
351
360
  const address = signer.toSuiAddress();
352
361
  const sessionKey = await SessionKey.create({
@@ -369,60 +378,103 @@ async function sealSession(config, url, { approve, pkg, signer: holder }) {
369
378
  const txBytes = await tx.build({ client: sui, onlyTransactionKind: true });
370
379
  return { sessionKey, txBytes };
371
380
  }
372
- function unsealerFor(config, url) {
373
- const client = sealClient(config, url);
374
- 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)) });
375
384
  }
376
385
  /** Seal's per-server derived keys for `id`, the inputs `offer::slash` decrypts with on chain. */
377
- function deriverFor(config, url) {
378
- const client = sealClient(config, url);
386
+ function deriverFor(config, url, fetch) {
387
+ const client = sealClient(config, url, fetch);
379
388
  return async (r) => {
380
389
  const keys = await client.getDerivedKeys({
381
390
  id: Buffer.from(r.id).toString("hex"),
382
391
  threshold: config.seal.threshold,
383
- ...(await sealSession(config, url, r)),
392
+ ...(await sealSession(config, url, fetch, r)),
384
393
  });
385
394
  return new Map([...keys].map(([server, k]) => [server, Uint8Array.from(Buffer.from(k.toString(), "hex"))]));
386
395
  };
387
396
  }
388
397
  export function chainIo(config, o) {
389
- const fetch = o.fetch ?? ((url, init) => globalThis.fetch(url, init));
398
+ const fetch = o.fetch ? fixedHeaders(o.fetch) : plainFetch;
390
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)))) ?? [];
391
416
  const pools = config.objects.pools;
392
417
  const pkg = config.packages.pool;
418
+ const cache = o.artifactDir ? artifactCache(fetch, config.circuits, o.artifactDir) : undefined;
393
419
  const artifacts = (circuit) => {
394
420
  const local = o.localArtifacts?.[circuit];
395
421
  if (local)
396
422
  return Promise.resolve({ wasm: readFileSync(local.wasm), zkey: readFileSync(local.zkey) });
397
- return v3.loadCircuitArtifacts(fetch, config.circuits, circuit);
423
+ return cache ? cache.load(circuit) : v3.loadCircuitArtifacts(fetch, config.circuits, circuit);
398
424
  };
399
425
  return {
400
- waitIndexed: (landedAtMs) => waitIndexed(gql, landedAtMs, o.indexPauseMs ?? 1500),
426
+ prefetchArtifacts: () => cache?.prefetch(),
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
+ },
401
437
  prover: v3.groth16Prover(snarkjs.groth16, artifacts),
402
- readPrice: (market) => readPrice(gql, market),
403
- readReading: (market) => readReading(gql, market),
404
- readSeizure: (loanId) => readSeizure(gql, loanId),
405
- readSettleTime: (loanId) => readSettleTime(gql, loanId),
406
- readTopupDelivery: (loanId) => readTopupDelivery(gql, loanId),
407
- readKeeperCt: (loanId) => readKeeperCt(gql, loanId),
408
- readCreated: (digest) => readCreated(gql, digest),
409
- readBadge: (digest) => readBadge(gql, digest),
410
- 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
+ },
411
448
  readObjectRef: (id) => readObjectRef(gql, id),
412
- readRoom: (id) => readRoom(gql, id),
413
- readRooms: async (cursor) => readRooms(gql, originOf(config, "sale"), cursor),
414
- 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
+ },
415
461
  readAddressUsed: (address) => readAddressUsed(gql, address),
416
- readVault: async (id) => ({ json: (await objectOf(gql, id)).asMoveObject.contents.json }),
417
- readMarket: async (id) => (await objectOf(gql, id)).asMoveObject.contents.json,
418
- sealEncrypt: sealerFor(config, o.graphql, o.garble ?? (() => false)),
419
- sealDecrypt: unsealerFor(config, o.graphql),
420
- sealDerivedKeys: deriverFor(config, o.graphql),
421
- readLoan: (id, round) => readLoan(gql, id, round),
422
- 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
+ },
423
472
  priceUpdate: async () => Uint8Array.of(0),
424
473
  fundDeposit: o.fundDeposit,
425
- 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
+ },
426
478
  readSharedVersion: async (id) => String((await objectOf(gql, id)).owner.initialSharedVersion),
427
479
  readPool: async (coin) => {
428
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);
package/dist/main.js CHANGED
@@ -6,28 +6,33 @@ import { graphqlExecute, itemHandOver } from "./agent.js";
6
6
  import { clientOf, withInvite } from "./client.js";
7
7
  import { ConfigError, parseConfig } from "./config.js";
8
8
  import { agentDepositIo } from "./fund.js";
9
+ import { handlesFor } from "./handles.js";
10
+ import { plainFetch } from "./http.js";
9
11
  import { chainIo } from "./io.js";
10
- import { loadAgentKey, loadNoteSeed } from "./keys.js";
12
+ import { keyInside, loadAgentKey, loadNoteSeed } from "./keys.js";
11
13
  import { toolPace } from "./pace.js";
12
14
  import { serve } from "./protocol.js";
13
- import { fileRecords, recordKey } from "./records.js";
15
+ import { fileRecords, recordKey, stateKey } from "./records.js";
14
16
  import { bind } from "./tools.js";
15
17
  const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
16
18
  .version;
17
19
  const INSTRUCTIONS = "Essey V3 private testnet tools. Note and agent keys are files on this server, never tool arguments, and no tool " +
18
20
  "returns a key, seed, or spend secret. The invite, when there is one, is ESSEY_INVITE. Amounts are whole-number " +
19
- "strings in the coin's smallest unit. The server builds every proof itself and keeps loan terms, offer, seller " +
21
+ "strings in the coin's smallest unit. Unless the operator set ESSEY_MCP_OUTPUT=clear, results name ids, digests " +
22
+ "and amounts by handles (h_ and 16 hex digits); pass a handle wherever a tool takes that value. " +
23
+ "The server builds every proof itself and keeps loan terms, offer, seller " +
20
24
  "and bid records in its own files; no tool returns them. Borrow: essey_loan_open, wait for the window, " +
21
25
  "essey_loan_settle, essey_loan_repay, essey_loan_release. Lend: essey_loan_list, essey_loan_request, " +
22
26
  "essey_loan_offer, then essey_loan_collect after repay or essey_loan_reclaim if the offer lost. Refinance: " +
23
27
  "essey_loan_refi_open, lenders offer, essey_loan_refi_settle; the old lender calls essey_loan_collect. Keeper: " +
24
28
  "essey_keeper_judge, then essey_keeper_liquidate or essey_keeper_fault, after which the lender calls " +
25
- "essey_loan_fault_liquidate. essey_notes_deposit is paid from the agent wallet. Sell: put the item at " +
26
- "essey_agent_address, essey_sale_open, after close essey_sale_finish (essey_sale_slash each bid it names " +
29
+ "essey_loan_fault_liquidate. essey_notes_deposit is paid from the agent wallet. Sell: put the item at a fresh " +
30
+ "essey_item_address (essey_badge_grant does), essey_sale_open, after close essey_sale_finish (essey_sale_slash each bid it names " +
27
31
  "first); or essey_sale_cancel before any bid, or essey_sale_expire after the finish window, then " +
28
32
  "essey_sale_claim as seller. Buy: essey_sale_list, essey_sale_bid, and once the room ended essey_sale_claim as " +
29
33
  "bidder if won and essey_sale_reclaim (residual if won, else the deposit). A proved call may answer NOT_BEFORE " +
30
- "with notBeforeMs: nothing was sent; make the same call again at or after that time.";
34
+ "with notBeforeMs: nothing was sent; make the same call again at or after that time. A split essey_notes_withdraw " +
35
+ "or essey_notes_exit pays one piece; call essey_notes_withdraw_continue at or after notBeforeMs until left is 0.";
31
36
  /**
32
37
  * `source` is what `Essey.connect` takes: the URL, which names the v3api, or the parsed file. The io reads the
33
38
  * same record as JSON (Seal set, pools, circuit pins).
@@ -40,7 +45,7 @@ async function deploymentOf(cfg) {
40
45
  }
41
46
  async function fetchJson(url) {
42
47
  try {
43
- const res = await fetch(url);
48
+ const res = await plainFetch(url);
44
49
  if (res.status !== 200)
45
50
  throw new Error("status");
46
51
  return await res.json();
@@ -76,9 +81,12 @@ async function start() {
76
81
  const cfg = parseConfig(process.env);
77
82
  const agent = loadAgentKey(cfg.agentKeyFile);
78
83
  const seed = loadNoteSeed(cfg.noteKeyFile);
84
+ if (keyInside(cfg.noteKeyFile, cfg.stateFile))
85
+ process.stderr.write("essey-v3-mcp: ESSEY_NOTE_KEY_FILE is inside the state directory, so a copy of that directory opens the records; move it apart\n");
79
86
  try {
80
87
  const { source, raw } = await deploymentOf(cfg);
81
- const io = chainIo(raw, { graphql: cfg.graphql });
88
+ const io = chainIo(raw, { graphql: cfg.graphql, artifactDir: `${dirname(cfg.stateFile)}/artifacts` });
89
+ io.prefetchArtifacts()?.catch(() => { });
82
90
  const deliverSaleItem = itemHandOver({
83
91
  signer: agent,
84
92
  execute: graphqlExecute(cfg.graphql, agent),
@@ -89,17 +97,21 @@ async function start() {
89
97
  statePath: cfg.stateFile,
90
98
  config: source,
91
99
  seed,
100
+ stateKey: stateKey(seed),
92
101
  relayer: cfg.relayer,
93
102
  delays: cfg.delays,
94
103
  }, { ...io, ...agentDepositIo(raw, cfg.agentKeyFile, cfg.graphql), deliverSaleItem, pace: toolPace() });
95
104
  const sale = { agentAddress: agent.toSuiAddress(), vaultOf: io.readVaultOf };
96
105
  const client = withInvite(clientOf(essey, sale), cfg.invite);
106
+ const dir = dirname(cfg.stateFile);
107
+ const key = recordKey(seed);
97
108
  const tools = bind({
98
109
  client,
99
- records: fileRecords(dirname(cfg.stateFile), recordKey(seed)),
110
+ records: fileRecords(dir, key),
100
111
  redact: cfg.invite ? [cfg.invite] : [],
101
112
  onError: (line) => process.stderr.write(`essey-v3-mcp: ${line}\n`),
102
113
  waitIndexed: io.waitIndexed,
114
+ handles: handlesFor(cfg.output, dir, key),
103
115
  });
104
116
  process.stderr.write("essey-v3-mcp: testnet, note key and agent key files accepted\n");
105
117
  await serve(tools, { name: "essey-v3", version: VERSION, instructions: INSTRUCTIONS }, process.stdin, process.stdout);