@zktx.io/sui-mcp 0.5.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 (218) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/@mysten-bcs-2.0.5-Apache-2.0.txt +205 -0
  3. package/LICENSES/@mysten-sui-2.17.0-Apache-2.0.txt +201 -0
  4. package/LICENSES/@mysten-utils-0.3.3-Apache-2.0.txt +205 -0
  5. package/LICENSES/fancy-canvas-2.1.0-MIT.txt +7 -0
  6. package/LICENSES/lightweight-charts-5.2.0-NOTICE.txt +2 -0
  7. package/README.md +288 -0
  8. package/dist/adapters/adapterLifecycleValidators.js +5 -0
  9. package/dist/adapters/adapterPromptSurfaces.js +60 -0
  10. package/dist/adapters/deepbook/deepbookHumanReviewProducer.js +178 -0
  11. package/dist/adapters/deepbook/deepbookQuotePolicy.js +112 -0
  12. package/dist/adapters/deepbook/deepbookReviewEvidence.js +507 -0
  13. package/dist/adapters/deepbook/deepbookReviewLifecycle.js +85 -0
  14. package/dist/adapters/deepbook/deepbookSwapIntent.js +79 -0
  15. package/dist/adapters/deepbook/deepbookTransactionMaterialProducer.js +254 -0
  16. package/dist/adapters/intentPlanFactories.js +51 -0
  17. package/dist/adapters/reviewAdapters.js +47 -0
  18. package/dist/core/action/adapterLifecycleValidation.js +12 -0
  19. package/dist/core/action/contractNameRegistry.js +151 -0
  20. package/dist/core/action/forbiddenFields.js +43 -0
  21. package/dist/core/action/humanReadableReviewEvidence.js +193 -0
  22. package/dist/core/action/humanReadableReviewProjectionVerifier.js +29 -0
  23. package/dist/core/action/ptbVisualizationProducer.js +71 -0
  24. package/dist/core/action/receiptPtbGraph.js +29 -0
  25. package/dist/core/action/reviewCheckResults.js +6 -0
  26. package/dist/core/action/reviewStateValidation.js +11 -0
  27. package/dist/core/action/reviewTimeSimulationEvidence.js +470 -0
  28. package/dist/core/action/schemas.js +491 -0
  29. package/dist/core/action/signableAdapterContract.js +998 -0
  30. package/dist/core/action/suiChainReceiptEvidence.js +106 -0
  31. package/dist/core/action/suiChainReceiptMapping.js +107 -0
  32. package/dist/core/action/suiChainReceiptReader.js +211 -0
  33. package/dist/core/action/suiChainReceiptVerifier.js +178 -0
  34. package/dist/core/action/swapHumanReadableReviewProjection.js +130 -0
  35. package/dist/core/action/swapQuotePolicyEvidence.js +271 -0
  36. package/dist/core/action/transactionFunding.js +244 -0
  37. package/dist/core/action/transactionObjectOwnershipEvidence.js +256 -0
  38. package/dist/core/action/transactionObjectOwnershipProducer.js +323 -0
  39. package/dist/core/action/types.js +33 -0
  40. package/dist/core/action/walletReviewContractAssembler.js +286 -0
  41. package/dist/core/activity/accountAssetTimeline.js +157 -0
  42. package/dist/core/activity/accountAssetTimelineUsdcReferences.js +120 -0
  43. package/dist/core/activity/activityStore.js +16 -0
  44. package/dist/core/activity/externalActivityCoverage.js +76 -0
  45. package/dist/core/activity/externalActivityTransactionStream.js +82 -0
  46. package/dist/core/activity/localDataService.js +296 -0
  47. package/dist/core/activity/localDataTypes.js +11 -0
  48. package/dist/core/activity/localDataValidation.js +439 -0
  49. package/dist/core/activity/schemaVersion.js +2 -0
  50. package/dist/core/activity/sqliteActivityStore.js +1068 -0
  51. package/dist/core/activity/sqliteActivityStoreRows.js +389 -0
  52. package/dist/core/activity/sqliteActivityStoreSchema.js +367 -0
  53. package/dist/core/activity/sqliteActivityStoreTypes.js +5 -0
  54. package/dist/core/activity/suiFunctionTarget.js +43 -0
  55. package/dist/core/activity/transactionActivityAccountEffects.js +186 -0
  56. package/dist/core/activity/transactionActivityAnalysis.js +295 -0
  57. package/dist/core/activity/transactionActivityClassifier.js +306 -0
  58. package/dist/core/activity/transactionActivityDetails.js +229 -0
  59. package/dist/core/activity/transactionActivityProtocolRules.js +218 -0
  60. package/dist/core/activity/transactionActivityScanPolicy.js +170 -0
  61. package/dist/core/activity/transactionActivityService.js +379 -0
  62. package/dist/core/activity/transactionActivityTypes.js +18 -0
  63. package/dist/core/eventlog/sink.js +35 -0
  64. package/dist/core/evidence/settlementFamilies.js +85 -0
  65. package/dist/core/evidence/userAnswerUse.js +1 -0
  66. package/dist/core/numeric/rawU64.js +63 -0
  67. package/dist/core/preferences/preferencesStore.js +26 -0
  68. package/dist/core/preferences/sqlitePreferencesRepository.js +136 -0
  69. package/dist/core/proposal/externalProposalReview.js +347 -0
  70. package/dist/core/proposal/schemas.js +208 -0
  71. package/dist/core/proposal/types.js +35 -0
  72. package/dist/core/read/amounts.js +14 -0
  73. package/dist/core/read/coinMetadata.js +60 -0
  74. package/dist/core/read/deepbookOfficialIndexerSource.js +373 -0
  75. package/dist/core/read/deepbookRawQuoteClient.js +86 -0
  76. package/dist/core/read/deepbookReadHelpers.js +321 -0
  77. package/dist/core/read/deepbookRegistry.js +157 -0
  78. package/dist/core/read/deepbookSourceOwners.js +159 -0
  79. package/dist/core/read/deepbookUsdcChartService.js +342 -0
  80. package/dist/core/read/intentEvidenceResponseFormatting.js +228 -0
  81. package/dist/core/read/readCardInputs.js +19 -0
  82. package/dist/core/read/readCardResult.js +40 -0
  83. package/dist/core/read/readResponseGuidance.js +402 -0
  84. package/dist/core/read/readService.js +1639 -0
  85. package/dist/core/read/readServiceTypes.js +88 -0
  86. package/dist/core/read/settlementParityFormatting.js +82 -0
  87. package/dist/core/read/walletReadHelpers.js +99 -0
  88. package/dist/core/review/reviewChecks.js +45 -0
  89. package/dist/core/review/reviewComputation.js +38 -0
  90. package/dist/core/review/reviewComputationResult.js +87 -0
  91. package/dist/core/session/cardSession.js +31 -0
  92. package/dist/core/session/cardSessionStore.js +204 -0
  93. package/dist/core/session/keyedRecordStore.js +18 -0
  94. package/dist/core/session/liveReviewSessionContract.js +3 -0
  95. package/dist/core/session/localSession.js +31 -0
  96. package/dist/core/session/privateReviewArtifacts.js +75 -0
  97. package/dist/core/session/reviewValidity.js +49 -0
  98. package/dist/core/session/sessionErrors.js +9 -0
  99. package/dist/core/session/sessionRecordStore.js +40 -0
  100. package/dist/core/session/sessionStore.js +655 -0
  101. package/dist/core/session/settingsSession.js +1 -0
  102. package/dist/core/session/settingsSessions.js +45 -0
  103. package/dist/core/session/sqliteCardStore.js +88 -0
  104. package/dist/core/session/sqliteSessionStore.js +213 -0
  105. package/dist/core/session/sqliteTransactionMaterialStore.js +64 -0
  106. package/dist/core/session/sqliteWalletWorkflowStore.js +821 -0
  107. package/dist/core/session/status.js +60 -0
  108. package/dist/core/session/transactionMaterialStore.js +221 -0
  109. package/dist/core/session/transactionRequest.js +72 -0
  110. package/dist/core/session/wait.js +79 -0
  111. package/dist/core/session/walletConnection.js +92 -0
  112. package/dist/core/session/walletRuntime.js +38 -0
  113. package/dist/core/session/walletWorkflow.js +608 -0
  114. package/dist/core/session/workflowState.js +80 -0
  115. package/dist/core/session/workflowView.js +150 -0
  116. package/dist/core/suiAddress.js +18 -0
  117. package/dist/core/suiEndpoint.js +72 -0
  118. package/dist/mcp/activeAccountResponse.js +24 -0
  119. package/dist/mcp/prompts.js +146 -0
  120. package/dist/mcp/registerTool.js +19 -0
  121. package/dist/mcp/resources.js +72 -0
  122. package/dist/mcp/responseGuidance.js +326 -0
  123. package/dist/mcp/result.js +17 -0
  124. package/dist/mcp/schemas.js +11 -0
  125. package/dist/mcp/server.js +32 -0
  126. package/dist/mcp/serverInfo.js +131 -0
  127. package/dist/mcp/toolErrors.js +118 -0
  128. package/dist/mcp/toolNames.js +58 -0
  129. package/dist/mcp/tools/account/index.js +44 -0
  130. package/dist/mcp/tools/action/prepareSuiActionReview.js +126 -0
  131. package/dist/mcp/tools/read/commonSchemas.js +43 -0
  132. package/dist/mcp/tools/read/deepbookReadTools.js +686 -0
  133. package/dist/mcp/tools/read/index.js +14 -0
  134. package/dist/mcp/tools/read/readToolHelpers.js +97 -0
  135. package/dist/mcp/tools/read/reviewActivityTools.js +179 -0
  136. package/dist/mcp/tools/read/serverStatusTools.js +100 -0
  137. package/dist/mcp/tools/read/transactionActivityOutput.js +371 -0
  138. package/dist/mcp/tools/read/transactionActivityTools.js +858 -0
  139. package/dist/mcp/tools/read/walletReadTools.js +734 -0
  140. package/dist/mcp/tools/session/executionResultTools.js +44 -0
  141. package/dist/mcp/tools/session/index.js +8 -0
  142. package/dist/mcp/tools/session/shared.js +36 -0
  143. package/dist/mcp/tools/session/statusTools.js +69 -0
  144. package/dist/mcp/tools/session/walletConnectionTools.js +69 -0
  145. package/dist/mcp/tools/settings/index.js +66 -0
  146. package/dist/mcp-app/account.html +3133 -0
  147. package/dist/mcp-app/account.notices.txt +973 -0
  148. package/dist/mcp-app/chart.html +3354 -0
  149. package/dist/mcp-app/chart.notices.txt +1194 -0
  150. package/dist/mcp-app/connect.html +3179 -0
  151. package/dist/mcp-app/connect.notices.txt +1012 -0
  152. package/dist/mcp-app/receipt.html +8430 -0
  153. package/dist/mcp-app/receipt.notices.txt +3549 -0
  154. package/dist/mcp-app/review.html +8430 -0
  155. package/dist/mcp-app/review.notices.txt +3549 -0
  156. package/dist/mcp-ui/contracts.js +31 -0
  157. package/dist/mcp-ui/readCards.js +28 -0
  158. package/dist/mcp-ui/tools.js +134 -0
  159. package/dist/review-app/brand-dark.svg +1 -0
  160. package/dist/review-app/brand-light.svg +1 -0
  161. package/dist/review-app/favicon.svg +1 -0
  162. package/dist/review-app/settings.css +1 -0
  163. package/dist/review-app/settings.js +1 -0
  164. package/dist/review-app/ui.css +809 -0
  165. package/dist/review-server/assets.js +48 -0
  166. package/dist/review-server/html.js +45 -0
  167. package/dist/review-server/http.js +47 -0
  168. package/dist/review-server/middleware/hostOrigin.js +48 -0
  169. package/dist/review-server/middleware/reviewToken.js +7 -0
  170. package/dist/review-server/reviewServerPolicy.js +1 -0
  171. package/dist/review-server/server.js +72 -0
  172. package/dist/review-server/settingsApi.js +158 -0
  173. package/dist/runtime/application.js +203 -0
  174. package/dist/runtime/config.js +97 -0
  175. package/dist/runtime/localSettingsService.js +198 -0
  176. package/dist/runtime/logger.js +66 -0
  177. package/dist/runtime/reviewDependencies.js +58 -0
  178. package/dist/runtime/reviewServerAcquire.js +93 -0
  179. package/dist/runtime/runtimeTermination.js +60 -0
  180. package/dist/runtime/shared/authenticatedFetch.js +127 -0
  181. package/dist/runtime/shared/control.js +93 -0
  182. package/dist/runtime/shared/dataAccess.js +66 -0
  183. package/dist/runtime/shared/mcpHttp.js +84 -0
  184. package/dist/runtime/shared/ownerLease.js +50 -0
  185. package/dist/runtime/shared/server.js +98 -0
  186. package/dist/runtime/shared/stdio.js +113 -0
  187. package/dist/runtime/smokeMainnetRead.js +391 -0
  188. package/dist/runtime/smokeMainnetReadAssertions.js +306 -0
  189. package/dist/runtime/smokeReview.js +40 -0
  190. package/dist/runtime/start.js +90 -0
  191. package/dist/runtime/suiEndpoint.js +97 -0
  192. package/dist/runtime/suiTransactionGraphqlMapping.js +200 -0
  193. package/dist/runtime/suiTransactionGraphqlQueries.js +231 -0
  194. package/dist/runtime/suiTransactionGraphqlSource.js +148 -0
  195. package/dist/runtime/walletConnectConfig.js +3 -0
  196. package/dist/runtime/walletConnectStorage.js +99 -0
  197. package/dist/runtime/walletConnectTransport.js +128 -0
  198. package/dist/runtime/walletSdkChild.js +3 -0
  199. package/dist/runtime/walletSdkChildRuntime.js +160 -0
  200. package/dist/runtime/walletSdkIpc.js +26 -0
  201. package/dist/runtime/walletSdkProcess.js +358 -0
  202. package/docs/AGENT_BEHAVIOR.md +524 -0
  203. package/docs/AGENT_DEVELOPMENT_POLICY.md +815 -0
  204. package/docs/FRONTEND_POLICY.md +534 -0
  205. package/docs/LOCAL_DB_ARCHITECTURE.md +381 -0
  206. package/docs/MCP_SETUP.md +742 -0
  207. package/docs/MCP_TOOLS.md +1318 -0
  208. package/docs/SDK_API.md +206 -0
  209. package/docs/SIGNABLE_ADAPTER_CONTRACT.md +396 -0
  210. package/docs/TRANSACTION_ACTIVITY_LOG.md +194 -0
  211. package/docs/UTILITY_INDEX.md +275 -0
  212. package/docs/WALLET_CONNECTION.md +238 -0
  213. package/docs/golden-scenarios/BEHAVIOR_MATRIX.md +166 -0
  214. package/docs/golden-scenarios/INTENT_EVIDENCE_GOLDEN_ANSWERS.md +161 -0
  215. package/docs/golden-scenarios/INTENT_EVIDENCE_MATRIX.md +259 -0
  216. package/package.json +79 -0
  217. package/protocols/deepbook-margin.md +15 -0
  218. package/protocols/deepbook-v3.md +24 -0
@@ -0,0 +1,358 @@
1
+ import { fork } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { walletUnavailable, WalletUnavailableError, WalletUserRejectedError } from "../core/session/walletConnection.js";
5
+ import { WalletRunInterruptedError, WalletReplacementFailedError } from "../core/session/walletRuntime.js";
6
+ import { walletCommandSchema, walletEventSchema } from "./walletSdkIpc.js";
7
+ /** Owns one SDK process. Business authority and all database transitions remain
8
+ * in the workflow; a process event is never transaction approval. */
9
+ export class WalletSdkProcess {
10
+ options;
11
+ run = this.newRun();
12
+ state = this.starting(this.run.id, "process_start");
13
+ listener;
14
+ started = false;
15
+ closed = false;
16
+ replacement;
17
+ constructor(options) {
18
+ this.options = options;
19
+ }
20
+ newRun() {
21
+ let end;
22
+ const exit = new Promise((resolve) => { end = resolve; });
23
+ return { id: randomUUID(), fenced: false, serial: 0, pending: new Map(), exit, end, didExit: false, initialized: false, sdkReady: false };
24
+ }
25
+ starting(id, stage) {
26
+ return { status: "initializing", walletRunId: id, stage,
27
+ message: stage === "session_restore" ? "Restoring wallet connections…" : "Starting the wallet connection service…" };
28
+ }
29
+ get runId() { return this.run.id; }
30
+ availability() { return this.state; }
31
+ snapshot() { return this.run.snapshot; }
32
+ synchronize() {
33
+ const run = this.run;
34
+ if (!this.closed && !run.fenced && run.sdkReady && !run.initialized && run.snapshot) {
35
+ if (!this.emit({ type: "snapshot", runId: run.id, snapshot: run.snapshot, ready: true }))
36
+ this.state = {
37
+ status: "initializing", walletRunId: run.id, stage: "state_sync", message: "Wallet service state could not be saved. Check status to try again."
38
+ };
39
+ }
40
+ }
41
+ start(listener) {
42
+ if (this.started || this.closed)
43
+ throw new Error("Wallet service already started or closed.");
44
+ this.started = true;
45
+ this.listener = listener;
46
+ this.spawn(this.run);
47
+ }
48
+ emit(event) {
49
+ if (this.closed)
50
+ return false;
51
+ try {
52
+ this.listener?.(event);
53
+ return true;
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ }
59
+ failureReason() {
60
+ return this.state.status === "initializing" && this.state.stage !== "state_sync"
61
+ ? this.state.stage === "session_restore" ? "restoration_failed" : "initialization_failed" : "wallet_state_unavailable";
62
+ }
63
+ spawn(run) {
64
+ if (this.closed || run !== this.run || run.fenced)
65
+ return;
66
+ try {
67
+ if (!this.options.metadata)
68
+ throw new Error("Wallet service metadata is unavailable.");
69
+ const child = this.options.spawn?.() ?? fork(new URL("./walletSdkChild.js", import.meta.url), [], {
70
+ execPath: process.execPath, execArgv: [], stdio: ["ignore", "ignore", "ignore", "ipc"], serialization: "json"
71
+ });
72
+ run.child = child;
73
+ child.on("message", (raw) => this.receive(run, raw));
74
+ child.once("exit", () => this.exited(run));
75
+ child.once("error", () => {
76
+ this.lose(run, this.failureReason());
77
+ // Failed spawn has no process and therefore cannot emit exit.
78
+ if (child.pid === undefined)
79
+ this.exited(run);
80
+ });
81
+ child.once("disconnect", () => { if (!run.fenced && !run.didExit)
82
+ this.lose(run, this.failureReason()); });
83
+ this.send(run, { protocolVersion: 1, runId: run.id, type: "init", dataDirectory: this.options.dataDirectory,
84
+ projectId: this.options.projectId, metadata: this.options.metadata });
85
+ }
86
+ catch {
87
+ this.lose(run, "initialization_failed");
88
+ if (!run.child)
89
+ this.exited(run);
90
+ }
91
+ }
92
+ send(run, message) {
93
+ if (run !== this.run || run.fenced || this.closed || !run.child?.connected)
94
+ throw new WalletRunInterruptedError(run.id);
95
+ // A false return means backpressure, not permission to repeat the command.
96
+ run.child.send(walletCommandSchema.parse(message), (error) => { if (error)
97
+ this.lose(run, "wallet_state_unavailable"); });
98
+ }
99
+ receive(run, raw) {
100
+ if (this.closed || run !== this.run || run.fenced || run.didExit)
101
+ return;
102
+ const parsed = walletEventSchema.safeParse(raw);
103
+ if (!parsed.success) {
104
+ this.lose(run, "wallet_state_unavailable");
105
+ return;
106
+ }
107
+ const event = parsed.data;
108
+ if (event.runId !== run.id)
109
+ return;
110
+ if (event.type === "failure") {
111
+ this.lose(run, event.reason);
112
+ return;
113
+ }
114
+ if (event.type === "stage") {
115
+ if (run.initialized) {
116
+ this.lose(run, "wallet_state_unavailable");
117
+ return;
118
+ }
119
+ this.state = this.starting(run.id, event.stage);
120
+ if (!this.emit({ type: "stage", runId: run.id, stage: event.stage }))
121
+ this.lose(run, "wallet_state_unavailable");
122
+ return;
123
+ }
124
+ if (event.type === "snapshot") {
125
+ if (event.snapshot.runId !== run.id) {
126
+ this.lose(run, "wallet_state_unavailable");
127
+ return;
128
+ }
129
+ if (event.snapshot.sequence <= (run.snapshot?.sequence ?? 0))
130
+ return;
131
+ if (event.ready && run.sdkReady || !event.ready && !run.sdkReady) {
132
+ this.lose(run, "wallet_state_unavailable");
133
+ return;
134
+ }
135
+ const topics = new Set();
136
+ for (const session of event.snapshot.sessions) {
137
+ if (topics.has(session.topic) || session.status === "present" && session.session.topic !== session.topic) {
138
+ this.lose(run, "wallet_state_unavailable");
139
+ return;
140
+ }
141
+ topics.add(session.topic);
142
+ const prior = run.snapshot?.sessions.find((entry) => entry.topic === session.topic);
143
+ if (prior && (session.version < prior.version || session.version === prior.version && !isDeepStrictEqual(session, prior))) {
144
+ this.lose(run, "wallet_state_unavailable");
145
+ return;
146
+ }
147
+ }
148
+ const previous = run.snapshot;
149
+ run.snapshot = event.snapshot;
150
+ if (event.ready) {
151
+ run.sdkReady = true;
152
+ this.state = this.starting(run.id, "state_sync");
153
+ }
154
+ const ready = run.sdkReady && !run.initialized;
155
+ if (!this.emit({ type: "snapshot", runId: run.id, snapshot: event.snapshot, ...(previous ? { previous } : {}), ready })) {
156
+ if (ready)
157
+ this.state = { status: "initializing", walletRunId: run.id, stage: "state_sync", message: "Wallet service state could not be saved. Check status to try again." };
158
+ else
159
+ this.lose(run, "wallet_state_unavailable");
160
+ }
161
+ return;
162
+ }
163
+ const pending = run.pending.get(event.requestId);
164
+ if (!pending || pending.operationId !== event.operationId)
165
+ return;
166
+ if (event.type === "error") {
167
+ run.pending.delete(event.requestId);
168
+ const error = event.code === "rejected" ? new WalletUserRejectedError() : new Error("The wallet operation could not be confirmed.");
169
+ pending.reject(error);
170
+ pending.rejectApproval?.(error);
171
+ return;
172
+ }
173
+ if (event.type === "pairing" && pending.type === "connect" && !pending.paired) {
174
+ pending.paired = true;
175
+ pending.resolve(event);
176
+ return;
177
+ }
178
+ if (event.type === "connected" && pending.type === "connect" && pending.paired) {
179
+ run.pending.delete(event.requestId);
180
+ pending.approve?.(event.session);
181
+ return;
182
+ }
183
+ if (event.type === "disconnected" && pending.type === "disconnect" || event.type === "checked" && pending.type === "check_session" ||
184
+ event.type === "signed" && pending.type === "sign") {
185
+ run.pending.delete(event.requestId);
186
+ pending.resolve(event);
187
+ return;
188
+ }
189
+ this.lose(run, "wallet_state_unavailable");
190
+ }
191
+ publishReady(runId) {
192
+ const run = this.run;
193
+ if (this.closed || run.id !== runId || run.fenced || !run.snapshot)
194
+ throw new WalletRunInterruptedError(runId);
195
+ run.initialized = true;
196
+ this.state = { status: "available", walletRunId: run.id };
197
+ }
198
+ lose(run, reason) {
199
+ if (run !== this.run || run.fenced || this.closed)
200
+ return;
201
+ run.fenced = true;
202
+ this.state = walletUnavailable(reason, run.id);
203
+ this.emit({ type: "lost", runId: run.id, reason });
204
+ void this.terminate(run).catch(() => { });
205
+ }
206
+ fail(reason) { this.lose(this.run, reason); }
207
+ block(reason) {
208
+ this.run.fenced = true;
209
+ this.state = walletUnavailable(reason, this.run.id);
210
+ }
211
+ fence(runId) {
212
+ if (this.closed || this.run.id !== runId || this.state.status === "recovering")
213
+ throw new WalletRunInterruptedError(runId);
214
+ this.run.fenced = true;
215
+ this.state = { status: "recovering", walletRunId: runId, message: "Restarting the wallet connection service…" };
216
+ }
217
+ terminate(run) {
218
+ if (run.termination)
219
+ return run.termination;
220
+ return run.termination = this.stopProcess(run).catch((error) => { run.termination = undefined; throw error; });
221
+ }
222
+ async stopProcess(run) {
223
+ if (run.didExit)
224
+ return;
225
+ if (!run.child) {
226
+ this.exited(run);
227
+ return;
228
+ }
229
+ try {
230
+ if (!run.child.kill("SIGKILL") && run.child.exitCode === null && run.child.signalCode === null) {
231
+ if (run === this.run)
232
+ this.state = walletUnavailable("wallet_state_unavailable", run.id);
233
+ throw new Error("The wallet service process could not be stopped.");
234
+ }
235
+ }
236
+ catch {
237
+ if (run === this.run)
238
+ this.state = walletUnavailable("wallet_state_unavailable", run.id);
239
+ throw new Error("The wallet service process could not be stopped.");
240
+ }
241
+ await run.exit;
242
+ }
243
+ exited(run) {
244
+ if (run.didExit)
245
+ return;
246
+ if (!run.fenced && !this.closed) {
247
+ run.fenced = true;
248
+ const reason = this.failureReason();
249
+ this.state = walletUnavailable(reason, run.id);
250
+ this.emit({ type: "lost", runId: run.id, reason });
251
+ }
252
+ run.didExit = true;
253
+ const error = new WalletRunInterruptedError(run.id);
254
+ for (const pending of run.pending.values()) {
255
+ pending.reject(error);
256
+ pending.rejectApproval?.(error);
257
+ }
258
+ run.pending.clear();
259
+ this.emit({ type: "exit", runId: run.id });
260
+ run.end();
261
+ }
262
+ async replace(runId, beforeStart) {
263
+ const old = this.run;
264
+ if (old.id !== runId || !old.fenced || this.closed)
265
+ throw new WalletRunInterruptedError(runId);
266
+ const replacement = { run: old };
267
+ this.replacement = replacement;
268
+ try {
269
+ await this.terminate(old);
270
+ if (this.closed || this.run !== old || this.replacement !== replacement)
271
+ throw new WalletRunInterruptedError(runId);
272
+ const next = this.newRun();
273
+ // A failed reservation ends this attempt. Reads may save its failure,
274
+ // but only a new explicit admission may start another SDK process.
275
+ beforeStart(next.id);
276
+ this.run = next;
277
+ this.state = this.starting(next.id, "process_start");
278
+ this.spawn(next);
279
+ }
280
+ catch {
281
+ if (this.closed || this.run !== old || this.replacement !== replacement)
282
+ throw new WalletRunInterruptedError(runId);
283
+ this.state = walletUnavailable("wallet_state_unavailable", old.id);
284
+ throw new WalletReplacementFailedError(old.id);
285
+ }
286
+ finally {
287
+ if (this.replacement === replacement)
288
+ this.replacement = undefined;
289
+ }
290
+ }
291
+ dataReplaced() {
292
+ this.replacement = undefined;
293
+ const run = this.run;
294
+ run.fenced = true;
295
+ this.state = walletUnavailable("wallet_state_unavailable", run.id);
296
+ void this.terminate(run).catch(() => { });
297
+ }
298
+ async close() {
299
+ if (this.closed)
300
+ return this.run.exit;
301
+ this.closed = true;
302
+ this.replacement = undefined;
303
+ this.run.fenced = true;
304
+ await this.terminate(this.run);
305
+ }
306
+ bind() {
307
+ const run = this.run;
308
+ const assertCurrent = () => {
309
+ if (run !== this.run || run.fenced || this.closed)
310
+ throw new WalletRunInterruptedError(run.id);
311
+ if (this.state.status !== "available")
312
+ throw new WalletUnavailableError("wallet_state_unavailable", this.state.message);
313
+ };
314
+ assertCurrent();
315
+ const call = (input, operationId, approval) => {
316
+ assertCurrent();
317
+ const requestId = ++run.serial;
318
+ return new Promise((resolve, reject) => {
319
+ run.pending.set(requestId, { operationId, type: input.type, resolve, reject, ...approval });
320
+ try {
321
+ this.send(run, { ...input, protocolVersion: 1, runId: run.id, requestId, operationId });
322
+ }
323
+ catch (error) {
324
+ run.pending.delete(requestId);
325
+ reject(error);
326
+ }
327
+ });
328
+ };
329
+ return { runId: run.id, assertCurrent,
330
+ connect: async (operationId) => {
331
+ let approve, rejectApproval;
332
+ const approval = new Promise((resolve, reject) => { approve = resolve; rejectApproval = reject; });
333
+ void approval.catch(() => { });
334
+ const reply = await call({ type: "connect" }, operationId, { approve, rejectApproval });
335
+ assertCurrent();
336
+ if (reply.type !== "pairing")
337
+ throw new Error("Wallet pairing response is unavailable.");
338
+ return { uri: reply.uri, expiresAt: reply.expiresAt, approval };
339
+ },
340
+ disconnect: async (topic, operationId) => { await call({ type: "disconnect", topic }, operationId); assertCurrent(); },
341
+ checkSession: async (topic, operationId) => {
342
+ const reply = await call({ type: "check_session", topic }, operationId);
343
+ assertCurrent();
344
+ if (reply.type !== "checked" || reply.observation.topic !== topic || !run.snapshot || run.snapshot.sequence < reply.sequence ||
345
+ run.snapshot.sessions.find((item) => item.topic === topic)?.version !== reply.observation.version) {
346
+ throw new Error("The wallet session changed during confirmation.");
347
+ }
348
+ return reply.observation;
349
+ },
350
+ sign: async (input, operationId) => {
351
+ const reply = await call({ ...input, type: "sign" }, operationId);
352
+ assertCurrent();
353
+ if (reply.type !== "signed")
354
+ throw new Error("The wallet signature response is unavailable.");
355
+ return { transactionBytes: reply.transactionBytes, signature: reply.signature, sessionVersion: reply.sessionVersion };
356
+ } };
357
+ }
358
+ }