@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,82 @@
1
+ export function transactionTimestampInHalfOpenRange(transaction, from, to) {
2
+ return transaction.timestamp !== undefined && transaction.timestamp >= from && transaction.timestamp < to;
3
+ }
4
+ export function canonicalExternalActivityTransactions(rows) {
5
+ const byDigest = new Map();
6
+ for (const row of rows) {
7
+ const existing = byDigest.get(row.digest);
8
+ if (existing === undefined || compareCanonicalTransactionPreference(row, existing) < 0) {
9
+ byDigest.set(row.digest, row);
10
+ }
11
+ }
12
+ return [...byDigest.values()].sort(compareExternalActivityTransactionsDescending);
13
+ }
14
+ export function buildExternalActivityTransactionStreamResult(input) {
15
+ return {
16
+ dataScope: {
17
+ account: input.scope.account,
18
+ from: input.from,
19
+ to: input.to,
20
+ recordCount: input.transactionCount
21
+ },
22
+ accountSource: input.scope.accountSource,
23
+ accountKnown: input.scope.accountId !== undefined,
24
+ truncated: input.truncated,
25
+ transactionCount: input.transactionCount,
26
+ transactions: input.transactions
27
+ };
28
+ }
29
+ function compareCanonicalTransactionPreference(a, b) {
30
+ const detailComparison = Number(b.details !== undefined) - Number(a.details !== undefined);
31
+ if (detailComparison !== 0) {
32
+ return detailComparison;
33
+ }
34
+ const relationshipComparison = relationshipPreference(b.relationship) - relationshipPreference(a.relationship);
35
+ if (relationshipComparison !== 0) {
36
+ return relationshipComparison;
37
+ }
38
+ return compareExternalActivityTransactionsDescending(a, b);
39
+ }
40
+ function relationshipPreference(relationship) {
41
+ return relationship === "affected" ? 1 : 0;
42
+ }
43
+ export function compareExternalActivityTransactionsDescending(a, b) {
44
+ const checkpointComparison = compareOptionalIntegerStringsDesc(a.checkpoint, b.checkpoint);
45
+ if (checkpointComparison !== 0) {
46
+ return checkpointComparison;
47
+ }
48
+ const timestampComparison = compareOptionalStringsDesc(a.timestamp, b.timestamp);
49
+ if (timestampComparison !== 0) {
50
+ return timestampComparison;
51
+ }
52
+ return b.digest.localeCompare(a.digest);
53
+ }
54
+ function compareOptionalStringsDesc(a, b) {
55
+ if (a === undefined && b === undefined) {
56
+ return 0;
57
+ }
58
+ if (a === undefined) {
59
+ return 1;
60
+ }
61
+ if (b === undefined) {
62
+ return -1;
63
+ }
64
+ return b.localeCompare(a);
65
+ }
66
+ function compareOptionalIntegerStringsDesc(a, b) {
67
+ if (a === undefined && b === undefined) {
68
+ return 0;
69
+ }
70
+ if (a === undefined) {
71
+ return 1;
72
+ }
73
+ if (b === undefined) {
74
+ return -1;
75
+ }
76
+ const delta = BigInt(b) - BigInt(a);
77
+ if (delta < 0n)
78
+ return -1;
79
+ if (delta > 0n)
80
+ return 1;
81
+ return 0;
82
+ }
@@ -0,0 +1,296 @@
1
+ import { hasUnsettledWalletWork } from "../session/sqliteWalletWorkflowStore.js";
2
+ import { DB_USER_VERSION } from "./schemaVersion.js";
3
+ import { SuiEndpointError, parseGraphqlUrl, parseGrpcUrl } from "../suiEndpoint.js";
4
+ import { LOCAL_DATA_EXPORT_FORMAT, LOCAL_DATA_NETWORK, LocalDataError } from "./localDataTypes.js";
5
+ import { activeAccountChange, countsForPayload, invalidBackup, maxNumber, parseLocalDataEnvelope, suiGraphqlUrlFromPayload, suiGrpcUrlFromPayload } from "./localDataValidation.js";
6
+ export * from "./localDataTypes.js";
7
+ export class SqliteLocalDataService {
8
+ db;
9
+ options;
10
+ validateAdapterLifecycle;
11
+ constructor(db, options, validateAdapterLifecycle) {
12
+ this.db = db;
13
+ this.options = options;
14
+ this.validateAdapterLifecycle = validateAdapterLifecycle;
15
+ }
16
+ now() { return this.options.now?.() ?? new Date(); }
17
+ async getDataCounts() {
18
+ return this.currentDataCounts();
19
+ }
20
+ currentDataCounts() {
21
+ return this.db.transaction(() => {
22
+ this.options.advanceRequestDeadlines(this.now());
23
+ return this.getDataCountsSync();
24
+ }).immediate();
25
+ }
26
+ async exportLocalData(now = new Date()) {
27
+ return this.db.transaction(() => {
28
+ const envelope = {
29
+ schemaVersion: DB_USER_VERSION,
30
+ format: LOCAL_DATA_EXPORT_FORMAT,
31
+ network: LOCAL_DATA_NETWORK,
32
+ exportedAt: now.toISOString(),
33
+ data: {
34
+ accounts: this.selectAll("accounts"),
35
+ activeAccountContext: this.selectAll("active_account_context"),
36
+ reviewSessions: this.selectAll("review_sessions"),
37
+ reviewStateSnapshots: this.selectAll("review_state_snapshots"),
38
+ reviewStatusTransitions: this.selectAll("review_status_transitions"),
39
+ reviewExecutions: this.selectAll("review_executions"),
40
+ reviewRequests: this.selectAll("review_requests"),
41
+ externalActivityScans: this.selectAll("external_activity_scans"),
42
+ externalActivityTransactions: this.selectAll("external_activity_transactions"),
43
+ localSettings: this.selectAll("local_settings")
44
+ }
45
+ };
46
+ return parseLocalDataEnvelope(envelope, {
47
+ validateAdapterLifecycle: this.validateAdapterLifecycle
48
+ });
49
+ })();
50
+ }
51
+ async previewImportLocalData(input) {
52
+ const envelope = parseLocalDataEnvelope(input, {
53
+ validateAdapterLifecycle: this.validateAdapterLifecycle
54
+ });
55
+ return {
56
+ status: "valid",
57
+ format: envelope.format,
58
+ network: envelope.network,
59
+ exportedAt: envelope.exportedAt,
60
+ currentCounts: this.currentDataCounts(),
61
+ incomingCounts: countsForPayload(envelope.data),
62
+ willReplace: true,
63
+ activeAccountChange: activeAccountChange(this.selectAll("accounts"), this.selectAll("active_account_context"), envelope.data.accounts, envelope.data.activeAccountContext),
64
+ restartRequiredAfterImport: true,
65
+ };
66
+ }
67
+ async importLocalDataReplace(input, _now = new Date()) {
68
+ const envelope = await this.parseAndVerifyImportEnvelope(input);
69
+ this.db.transaction(() => {
70
+ // Endpoint verification may have outlived the original request window.
71
+ // Evaluate the current owner state inside the actual replacement transaction.
72
+ const now = this.now();
73
+ this.options.advanceRequestDeadlines(now);
74
+ if (hasUnsettledWalletWork(this.db, now))
75
+ throw new LocalDataError("input_invalid", "A wallet request is still unsettled.", { reason: "wallet_request_unsettled" });
76
+ this.resetLocalDataTables();
77
+ this.insertAccounts(envelope.data.accounts);
78
+ this.insertActiveAccountContext(envelope.data.activeAccountContext);
79
+ this.insertReviewSessions(envelope.data.reviewSessions);
80
+ this.insertReviewStateSnapshots(envelope.data.reviewStateSnapshots);
81
+ this.insertReviewRequests(envelope.data.reviewRequests);
82
+ this.insertReviewStatusTransitions(envelope.data.reviewStatusTransitions);
83
+ this.insertReviewExecutions(envelope.data.reviewExecutions);
84
+ this.insertExternalActivityScans(envelope.data.externalActivityScans);
85
+ this.insertExternalActivityTransactions(envelope.data.externalActivityTransactions);
86
+ this.insertLocalSettings(envelope.data.localSettings);
87
+ this.syncSqliteSequences(envelope.data);
88
+ })();
89
+ this.options.onDataReplaced?.();
90
+ return {
91
+ status: "imported",
92
+ dataCounts: this.getDataCountsSync(),
93
+ sessionsInvalidated: true
94
+ };
95
+ }
96
+ async resetLocalData(now = this.now()) {
97
+ this.db.transaction(() => {
98
+ this.options.advanceRequestDeadlines(now);
99
+ if (hasUnsettledWalletWork(this.db, now))
100
+ throw new LocalDataError("input_invalid", "A wallet request is still unsettled.", { reason: "wallet_request_unsettled" });
101
+ this.resetLocalDataTables();
102
+ this.insertDefaultSuiGrpcUrl(now);
103
+ })();
104
+ this.options.onDataReplaced?.();
105
+ return {
106
+ status: "reset",
107
+ dataCounts: this.getDataCountsSync(),
108
+ sessionsInvalidated: true
109
+ };
110
+ }
111
+ resetLocalDataTables() {
112
+ for (const table of [
113
+ "live_read_cards",
114
+ "live_execution_details",
115
+ "live_request_authority",
116
+ "live_wallet_connections",
117
+ "live_transaction_materials",
118
+ "live_private_review_artifacts",
119
+ "live_review_sessions",
120
+ "live_settings_sessions",
121
+ "external_activity_transactions",
122
+ "external_activity_scans",
123
+ "review_state_snapshots",
124
+ "review_status_transitions",
125
+ "review_executions",
126
+ "review_requests",
127
+ "review_sessions",
128
+ "coin_metadata_cache",
129
+ "active_account_context",
130
+ "accounts",
131
+ "local_settings"
132
+ ]) {
133
+ this.db.prepare(`DELETE FROM ${table}`).run();
134
+ }
135
+ this.db.prepare("DELETE FROM sqlite_sequence WHERE name IN ('accounts', 'review_state_snapshots', 'review_status_transitions')").run();
136
+ }
137
+ insertDefaultSuiGrpcUrl(now) {
138
+ const statement = this.db.prepare(`INSERT INTO local_settings (key, value_json, updated_at)
139
+ VALUES (?, ?, ?)`);
140
+ statement.run("suiGrpcUrl", JSON.stringify(parseGrpcUrl(this.options.suiGrpcUrl)), now.toISOString());
141
+ statement.run("suiGraphqlUrl", JSON.stringify(parseGraphqlUrl(this.options.suiGraphqlUrl)), now.toISOString());
142
+ }
143
+ getDataCountsSync() {
144
+ return {
145
+ accounts: this.count("accounts"),
146
+ reviewSessions: this.count("review_sessions"),
147
+ reviewStateSnapshots: this.count("review_state_snapshots"),
148
+ reviewStatusTransitions: this.count("review_status_transitions"),
149
+ reviewExecutions: this.count("review_executions"),
150
+ reviewRequests: this.count("review_requests"),
151
+ outcomeUnknownRequests: this.db.prepare("SELECT COUNT(*) AS count FROM review_requests WHERE request_status='outcome_unknown'").get().count,
152
+ externalActivityScans: this.count("external_activity_scans"),
153
+ externalActivityTransactions: this.count("external_activity_transactions"),
154
+ localSettings: this.count("local_settings")
155
+ };
156
+ }
157
+ count(table) {
158
+ return this.db.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get().count;
159
+ }
160
+ selectAll(table) {
161
+ return this.db.prepare(`SELECT * FROM ${table} ORDER BY rowid ASC`).all();
162
+ }
163
+ insertAccounts(rows) {
164
+ const statement = this.db.prepare(`INSERT INTO accounts (id, sui_address, first_seen_at, last_used_at, first_source, last_source)
165
+ VALUES (?, ?, ?, ?, ?, ?)`);
166
+ for (const row of rows) {
167
+ statement.run(row.id, row.sui_address, row.first_seen_at, row.last_used_at, row.first_source, row.last_source);
168
+ }
169
+ }
170
+ insertActiveAccountContext(rows) {
171
+ const statement = this.db.prepare(`INSERT INTO active_account_context (id, account_id, source, set_at, wallet_name, wallet_id)
172
+ VALUES (?, ?, ?, ?, ?, ?)`);
173
+ for (const row of rows) {
174
+ statement.run(row.id, row.account_id, row.source, row.set_at, row.wallet_name ?? null, row.wallet_id ?? null);
175
+ }
176
+ }
177
+ insertReviewSessions(rows) {
178
+ const statement = this.db.prepare(`INSERT INTO review_sessions
179
+ (id, plan_id, action_kind, adapter_id, protocol, account_id, current_status, plan_json, intent_json, created_at, updated_at, current_attempt_id, opened_at)
180
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
181
+ for (const row of rows) {
182
+ statement.run(row.id, row.plan_id, row.action_kind, row.adapter_id, row.protocol, row.account_id, row.current_status, row.plan_json, row.intent_json, row.created_at, row.updated_at, row.current_attempt_id, row.opened_at);
183
+ }
184
+ }
185
+ insertReviewStateSnapshots(rows) {
186
+ const statement = this.db.prepare(`INSERT INTO review_state_snapshots
187
+ (id, review_session_id, plan_id, account_id, status, blocked_reason, refresh_reason, state_json, updated_at, recorded_at, review_revision)
188
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
189
+ for (const row of rows) {
190
+ statement.run(row.id, row.review_session_id, row.plan_id, row.account_id, row.status, row.blocked_reason, row.refresh_reason, row.state_json, row.updated_at, row.recorded_at, row.review_revision);
191
+ }
192
+ }
193
+ insertReviewStatusTransitions(rows) {
194
+ const statement = this.db.prepare(`INSERT INTO review_status_transitions
195
+ (id, review_session_id, event, from_status, to_status, account_id, reason, transitioned_at, domain, attempt_id)
196
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
197
+ for (const row of rows) {
198
+ statement.run(row.id, row.review_session_id, row.event, row.from_status, row.to_status, row.account_id, row.reason, row.transitioned_at, row.domain, row.attempt_id);
199
+ }
200
+ }
201
+ insertReviewRequests(rows) {
202
+ const insert = this.db.prepare(`INSERT INTO review_requests
203
+ (attempt_id,review_session_id,plan_id,review_revision,account_id,transaction_digest,review_state_json,request_status,
204
+ revision,reason,created_at,updated_at,signature_verified_at,submitted_at)
205
+ VALUES (@attempt_id,@review_session_id,@plan_id,@review_revision,@account_id,@transaction_digest,@review_state_json,@request_status,
206
+ @revision,@reason,@created_at,@updated_at,@signature_verified_at,@submitted_at)`);
207
+ for (const row of rows)
208
+ insert.run(row);
209
+ }
210
+ insertReviewExecutions(rows) {
211
+ const statement = this.db.prepare(`INSERT INTO review_executions
212
+ (review_session_id, plan_id, account_id, status, tx_digest, explorer_url, failure_reason, result_json, recorded_at, updated_at, attempt_id)
213
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
214
+ for (const row of rows) {
215
+ statement.run(row.review_session_id, row.plan_id, row.account_id, row.status, row.tx_digest, row.explorer_url, row.failure_reason, row.result_json, row.recorded_at, row.updated_at, row.attempt_id);
216
+ }
217
+ }
218
+ insertExternalActivityScans(rows) {
219
+ const statement = this.db.prepare(`INSERT INTO external_activity_scans
220
+ (scan_id, kind, account_id, relationship, input_digest, from_checkpoint, to_checkpoint,
221
+ from_timestamp, to_timestamp, limit_count, request_cursor, response_cursor, endpoint_host,
222
+ chain_identifier, fetched_at, stored_count, skipped_count, has_more, window_complete,
223
+ incomplete_reason)
224
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
225
+ for (const row of rows) {
226
+ statement.run(row.scan_id, row.kind, row.account_id, row.relationship, row.input_digest, row.from_checkpoint, row.to_checkpoint, row.from_timestamp, row.to_timestamp, row.limit_count, row.request_cursor, row.response_cursor, row.endpoint_host, row.chain_identifier, row.fetched_at, row.stored_count, row.skipped_count, row.has_more, row.window_complete, row.incomplete_reason);
227
+ }
228
+ }
229
+ insertExternalActivityTransactions(rows) {
230
+ const statement = this.db.prepare(`INSERT INTO external_activity_transactions
231
+ (account_id, digest, relationship, checkpoint, timestamp, status, known_sender_account_id,
232
+ first_scan_id, last_scan_id, first_fetched_at, last_fetched_at, detail_json)
233
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
234
+ for (const row of rows) {
235
+ statement.run(row.account_id, row.digest, row.relationship, row.checkpoint, row.timestamp, row.status, row.known_sender_account_id, row.first_scan_id, row.last_scan_id, row.first_fetched_at, row.last_fetched_at, row.detail_json);
236
+ }
237
+ }
238
+ insertLocalSettings(rows) {
239
+ const statement = this.db.prepare(`INSERT INTO local_settings (key, value_json, updated_at)
240
+ VALUES (?, ?, ?)`);
241
+ for (const row of rows) {
242
+ statement.run(row.key, row.value_json, row.updated_at);
243
+ }
244
+ }
245
+ syncSqliteSequences(data) {
246
+ const sequenceRows = [
247
+ ["accounts", maxNumber(data.accounts.map((row) => row.id))],
248
+ ["review_state_snapshots", maxNumber(data.reviewStateSnapshots.map((row) => row.id))],
249
+ ["review_status_transitions", maxNumber(data.reviewStatusTransitions.map((row) => row.id))]
250
+ ];
251
+ const update = this.db.prepare("UPDATE sqlite_sequence SET seq = ? WHERE name = ?");
252
+ const insert = this.db.prepare("INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)");
253
+ for (const [name, seq] of sequenceRows) {
254
+ if (seq > 0) {
255
+ const result = update.run(seq, name);
256
+ if (result.changes === 0) {
257
+ insert.run(name, seq);
258
+ }
259
+ }
260
+ }
261
+ }
262
+ async parseAndVerifyImportEnvelope(input) {
263
+ const envelope = parseLocalDataEnvelope(input, {
264
+ validateAdapterLifecycle: this.validateAdapterLifecycle
265
+ });
266
+ await this.verifyImportedSuiGrpcUrl(suiGrpcUrlFromPayload(envelope.data));
267
+ await this.verifyImportedSuiGraphqlUrl(suiGraphqlUrlFromPayload(envelope.data));
268
+ return envelope;
269
+ }
270
+ async verifyImportedSuiGrpcUrl(url) {
271
+ try {
272
+ await this.options.verifySuiGrpcUrl(url);
273
+ }
274
+ catch (error) {
275
+ if (error instanceof SuiEndpointError) {
276
+ throw invalidBackup("invalid_sui_grpc_url_endpoint", { endpointReason: error.kind });
277
+ }
278
+ throw new LocalDataError("internal_error", "Could not verify imported Sui gRPC endpoint", {
279
+ message: "Could not verify imported Sui gRPC endpoint"
280
+ });
281
+ }
282
+ }
283
+ async verifyImportedSuiGraphqlUrl(url) {
284
+ try {
285
+ await this.options.verifySuiGraphqlUrl(url);
286
+ }
287
+ catch (error) {
288
+ if (error instanceof SuiEndpointError) {
289
+ throw invalidBackup("invalid_sui_graphql_url_endpoint", { endpointReason: error.kind });
290
+ }
291
+ throw new LocalDataError("internal_error", "Could not verify imported Sui GraphQL endpoint", {
292
+ message: "Could not verify imported Sui GraphQL endpoint"
293
+ });
294
+ }
295
+ }
296
+ }
@@ -0,0 +1,11 @@
1
+ export const LOCAL_DATA_EXPORT_FORMAT = "sui-mcp.local-data";
2
+ export const LOCAL_DATA_NETWORK = "mainnet";
3
+ export class LocalDataError extends Error {
4
+ kind;
5
+ details;
6
+ constructor(kind, message, details = {}) {
7
+ super(message);
8
+ this.kind = kind;
9
+ this.details = details;
10
+ }
11
+ }