@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,321 @@
1
+ import { formatRawAmount, normalizeCoinType, parseDisplayAmountToRaw } from "./coinMetadata.js";
2
+ import { MAX_RAW_U64, parseRawU64 } from "../numeric/rawU64.js";
3
+ import { parseSuiAddress } from "../suiAddress.js";
4
+ import { DEEPBOOK_OFFICIAL_INDEXER_CANONICAL_USDC_COIN_TYPE, DEEPBOOK_OFFICIAL_INDEXER_PRICE_CONVENTION } from "./deepbookOfficialIndexerSource.js";
5
+ import { DEEPBOOK_OFFICIAL_INDEXER_CANDLE_USE, DEEPBOOK_OFFICIAL_INDEXER_RESPONSE_TEXT, DEEPBOOK_SDK_SIMULATION_SOURCE_BASE } from "./deepbookSourceOwners.js";
6
+ import { DEEPBOOK_ACCOUNT_QUANTITY_KIND, DEEPBOOK_MID_PRICE_SEMANTICS_KIND, DEEPBOOK_QUOTE_QUANTITY_KIND, DEEPBOOK_USDC_PRICE_HISTORY_QUANTITY_KIND, DEEPBOOK_USDC_PRICE_HISTORY_UNSUPPORTED_CLAIMS, ReadServiceInputError } from "./readServiceTypes.js";
7
+ export const MAX_DEEPBOOK_QUOTE_RAW_AMOUNT = MAX_RAW_U64;
8
+ export function parseDeepbookRawU64(value, field, options = {}) {
9
+ return parseRawU64(value, field, options);
10
+ }
11
+ export function deepbookDisplayQuantitySemantics() {
12
+ return {
13
+ kind: DEEPBOOK_ACCOUNT_QUANTITY_KIND,
14
+ rawAmountAvailable: false,
15
+ notFor: ["signing", "funding", "route_liquidity", "withdrawal_readiness", "transaction_building"]
16
+ };
17
+ }
18
+ export function deepbookMidPriceSemantics() {
19
+ return {
20
+ kind: DEEPBOOK_MID_PRICE_SEMANTICS_KIND,
21
+ allowedUse: "deepbook_pool_mid_price_snapshot",
22
+ globalMarketPriceAvailable: false,
23
+ fiatUsdCashOutAvailable: false,
24
+ externalMarketPriceConversionAvailable: false,
25
+ externalMarketLookupAvailable: false,
26
+ usdPegAssumptionAvailable: false,
27
+ bankCashOutEstimateAvailable: false,
28
+ quoteComparisonAvailable: false,
29
+ priceImpactAvailable: false,
30
+ venueComparisonAvailable: false,
31
+ routeRecommendationAvailable: false,
32
+ profitAndLossAvailable: false,
33
+ costBasisAvailable: false,
34
+ notFor: [
35
+ "global_market_price",
36
+ "fiat_usd_cash_out",
37
+ "external_market_price_conversion",
38
+ "external_market_lookup",
39
+ "usd_peg_assumption",
40
+ "bank_cash_out_estimate",
41
+ "price_impact",
42
+ "mid_price_slippage",
43
+ "quote_vs_mid_slippage",
44
+ "effective_quote_price",
45
+ "venue_comparison",
46
+ "best_route",
47
+ "route_recommendation",
48
+ "transaction_building",
49
+ "signing_data",
50
+ "signing_readiness",
51
+ "profit_or_pnl",
52
+ "cost_basis"
53
+ ]
54
+ };
55
+ }
56
+ export function deepbookQuoteQuantitySemantics(inputAmountKind) {
57
+ return {
58
+ kind: DEEPBOOK_QUOTE_QUANTITY_KIND,
59
+ inputAmountKind,
60
+ allowedUse: "indicative_deepbook_pool_quote",
61
+ rawAmountAvailable: true,
62
+ rawEvidenceField: "rawQuote",
63
+ paymentCoverageAvailable: false,
64
+ shortfallContributionAvailable: false,
65
+ routeDependentPaymentSupportAvailable: false,
66
+ requiresIntentEvidenceForCoverage: true,
67
+ canUseForPaymentAnswer: false,
68
+ canUseForShortfallAnswer: false,
69
+ doNotCombineWithPaymentAnswer: true,
70
+ requiredPaymentAnswerTool: "read.preview_intent_evidence",
71
+ paymentAnswerUseBlockedReason: "quote_output_is_price_reference_not_payment_answer",
72
+ requiredPaymentAnswerField: "responseSummary",
73
+ fiatUsdCashOutAvailable: false,
74
+ externalMarketPriceConversionAvailable: false,
75
+ externalMarketLookupAvailable: false,
76
+ usdPegAssumptionAvailable: false,
77
+ bankCashOutEstimateAvailable: false,
78
+ profitAndLossAvailable: false,
79
+ costBasisAvailable: false,
80
+ priceImpactAvailable: false,
81
+ midPriceSlippageAvailable: false,
82
+ venueComparisonAvailable: false,
83
+ routeRecommendationAvailable: false,
84
+ notFor: [
85
+ "signing",
86
+ "funding",
87
+ "payment_coverage",
88
+ "shortfall_contribution",
89
+ "route_dependent_payment_support",
90
+ "route_liquidity",
91
+ "min_out",
92
+ "liquidity_verdict",
93
+ "price_impact",
94
+ "mid_price_slippage",
95
+ "quote_vs_mid_slippage",
96
+ "effective_price",
97
+ "venue_comparison",
98
+ "best_route",
99
+ "route_recommendation",
100
+ "transaction_building",
101
+ "fiat_usd_cash_out",
102
+ "external_market_price_conversion",
103
+ "external_market_lookup",
104
+ "usd_peg_assumption",
105
+ "bank_cash_out_estimate",
106
+ "profit_or_pnl",
107
+ "cost_basis"
108
+ ]
109
+ };
110
+ }
111
+ export function deepbookUsdcPriceHistoryQuantitySemantics() {
112
+ return {
113
+ kind: DEEPBOOK_USDC_PRICE_HISTORY_QUANTITY_KIND,
114
+ ...DEEPBOOK_OFFICIAL_INDEXER_CANDLE_USE,
115
+ liveQuoteAvailable: false,
116
+ historicalMidPriceAvailable: false,
117
+ globalMarketPriceAvailable: false,
118
+ fiatUsdCashOutAvailable: false,
119
+ routeRecommendationAvailable: false,
120
+ transactionBuildingAvailable: false,
121
+ signingReadinessAvailable: false,
122
+ profitAndLossAvailable: false,
123
+ costBasisAvailable: false,
124
+ notFor: [
125
+ "fiat_usd_cash_out",
126
+ "usd_peg_assumption",
127
+ "global_market_price",
128
+ "historical_mid_price",
129
+ "live_quote",
130
+ "route_recommendation",
131
+ "best_route",
132
+ "transaction_building",
133
+ "signing_data",
134
+ "signing_readiness",
135
+ "profit_or_pnl",
136
+ "cost_basis"
137
+ ]
138
+ };
139
+ }
140
+ export function deepbookUsdcPriceHistoryResponseSummary() {
141
+ return {
142
+ questionKind: "deepbook_usdc_price_history",
143
+ evidenceKind: "official_deepbook_indexer_candles",
144
+ sourceStatement: DEEPBOOK_OFFICIAL_INDEXER_RESPONSE_TEXT.sourceStatement,
145
+ usdcDisclaimer: DEEPBOOK_OFFICIAL_INDEXER_RESPONSE_TEXT.usdcDisclaimer,
146
+ candleMeaning: "Each candle is returned by the DeepBookV3 official Indexer for the requested interval.",
147
+ excludedFromConclusion: [...DEEPBOOK_USDC_PRICE_HISTORY_UNSUPPORTED_CLAIMS]
148
+ };
149
+ }
150
+ export function deepbookUsdcPriceHistoryPairFromOfficialPool(pool) {
151
+ return {
152
+ poolName: pool.pool_name,
153
+ poolId: pool.pool_id,
154
+ baseAsset: {
155
+ symbol: pool.base_asset_symbol,
156
+ coinType: normalizeCoinType(pool.base_asset_id),
157
+ decimals: pool.base_asset_decimals
158
+ },
159
+ quoteAsset: {
160
+ symbol: "USDC",
161
+ coinType: normalizeCoinType(DEEPBOOK_OFFICIAL_INDEXER_CANONICAL_USDC_COIN_TYPE),
162
+ decimals: pool.quote_asset_decimals
163
+ },
164
+ priceConvention: DEEPBOOK_OFFICIAL_INDEXER_PRICE_CONVENTION
165
+ };
166
+ }
167
+ export function deepbookAccountInventorySource(methods) {
168
+ return {
169
+ ...DEEPBOOK_SDK_SIMULATION_SOURCE_BASE,
170
+ methods
171
+ };
172
+ }
173
+ export function normalizeOptionalManagerAddress(value) {
174
+ if (value === undefined) {
175
+ return undefined;
176
+ }
177
+ const normalized = parseSuiAddress(value);
178
+ if (normalized === undefined) {
179
+ throw new ReadServiceInputError("input_invalid", "managerAddress must be a valid Sui address", {
180
+ field: "managerAddress",
181
+ value
182
+ });
183
+ }
184
+ return normalized;
185
+ }
186
+ export function normalizeManagerAddresses(values) {
187
+ return values.map((value) => {
188
+ const normalized = parseSuiAddress(value);
189
+ if (normalized === undefined) {
190
+ throw new Error("DeepBook BalanceManager ID was not a valid Sui address");
191
+ }
192
+ return normalized;
193
+ });
194
+ }
195
+ // Account inventory v1 exposes only ledger and rebate balances; governance,
196
+ // stake, volume, and AccountInfo.open_orders need separate review before export.
197
+ export function toDeepbookAccountSummary(accountInfo) {
198
+ return {
199
+ epoch: accountInfo.epoch,
200
+ settledBalances: assertDeepbookDisplayBalances(accountInfo.settled_balances, "accountSummary.settledBalances"),
201
+ owedBalances: assertDeepbookDisplayBalances(accountInfo.owed_balances, "accountSummary.owedBalances"),
202
+ unclaimedRebates: assertDeepbookDisplayBalances(accountInfo.unclaimed_rebates, "accountSummary.unclaimedRebates")
203
+ };
204
+ }
205
+ export function assertDeepbookDisplayBalances(balances, field) {
206
+ assertDeepbookDisplayNumber(balances.base, `${field}.base`);
207
+ assertDeepbookDisplayNumber(balances.quote, `${field}.quote`);
208
+ assertDeepbookDisplayNumber(balances.deep, `${field}.deep`);
209
+ return balances;
210
+ }
211
+ export function parseQuoteDisplayAmount(displayAmount, decimals) {
212
+ let rawAmount;
213
+ try {
214
+ rawAmount = parseDisplayAmountToRaw(displayAmount, decimals);
215
+ }
216
+ catch (error) {
217
+ throw new ReadServiceInputError("input_invalid", "amountDisplay must be a positive unsigned decimal string within verified decimals", {
218
+ field: "amountDisplay",
219
+ value: displayAmount,
220
+ decimals,
221
+ reason: error instanceof Error ? error.message : "unknown"
222
+ });
223
+ }
224
+ if (!/^[1-9]\d*$/.test(rawAmount)) {
225
+ throw new ReadServiceInputError("input_invalid", "amountDisplay must convert to a positive raw integer amount", {
226
+ field: "amountDisplay",
227
+ value: displayAmount,
228
+ decimals,
229
+ rawAmount
230
+ });
231
+ }
232
+ if (BigInt(rawAmount) > MAX_DEEPBOOK_QUOTE_RAW_AMOUNT) {
233
+ throw new ReadServiceInputError("input_invalid", "amountDisplay must convert to a raw integer amount that fits the DeepBook u64 quote input", {
234
+ field: "amountDisplay",
235
+ value: displayAmount,
236
+ decimals,
237
+ rawAmount,
238
+ maxRawAmount: MAX_DEEPBOOK_QUOTE_RAW_AMOUNT.toString()
239
+ });
240
+ }
241
+ return rawAmount;
242
+ }
243
+ export function parseRawAmount(value) {
244
+ try {
245
+ return parseDeepbookRawU64(value, "amountRaw", { positive: true });
246
+ }
247
+ catch (error) {
248
+ const reason = error instanceof Error ? error.message : "amountRaw is invalid";
249
+ if (reason === "amountRaw must fit u64") {
250
+ throw new ReadServiceInputError("input_invalid", "amountRaw must fit the DeepBook u64 quote input", {
251
+ field: "amountRaw",
252
+ value,
253
+ maxRawAmount: MAX_DEEPBOOK_QUOTE_RAW_AMOUNT.toString()
254
+ });
255
+ }
256
+ throw new ReadServiceInputError("input_invalid", "amountRaw must be a positive integer string", {
257
+ field: "amountRaw",
258
+ value
259
+ });
260
+ }
261
+ }
262
+ export function assertValidDeepbookMidPrice(poolKey, midPrice) {
263
+ if (!Number.isFinite(midPrice) || midPrice <= 0) {
264
+ throw new ReadServiceInputError("quote_unavailable", "DeepBook mid price is unavailable for this pool", {
265
+ poolKey,
266
+ source: "midPrice"
267
+ });
268
+ }
269
+ return midPrice;
270
+ }
271
+ export function assertValidDeepbookQuote(poolKey, direction, quote) {
272
+ for (const [field, value] of Object.entries(quote)) {
273
+ if (typeof value !== "string" || !/^\d+(?:\.\d+)?$/.test(value)) {
274
+ throw new ReadServiceInputError("quote_unavailable", "DeepBook quote display amount is unavailable", {
275
+ poolKey,
276
+ direction,
277
+ field
278
+ });
279
+ }
280
+ }
281
+ return quote;
282
+ }
283
+ export function toDeepbookDisplayQuoteFromRaw(quote, units) {
284
+ return {
285
+ baseOut: rawToDeepbookDisplayAmount(quote.baseOutRaw, units.baseDecimals),
286
+ quoteOut: rawToDeepbookDisplayAmount(quote.quoteOutRaw, units.quoteDecimals),
287
+ deepRequired: rawToDeepbookDisplayAmount(quote.deepRequiredRaw, units.deepDecimals)
288
+ };
289
+ }
290
+ export function assertPositiveInteger(value, field, max) {
291
+ if (!Number.isInteger(value) || value < 1) {
292
+ throw new ReadServiceInputError("input_invalid", `${field} must be a positive integer`, {
293
+ field,
294
+ value
295
+ });
296
+ }
297
+ if (max !== undefined && value > max) {
298
+ throw new ReadServiceInputError("input_invalid", `${field} must be less than or equal to ${max}`, {
299
+ field,
300
+ value,
301
+ max
302
+ });
303
+ }
304
+ }
305
+ function assertDeepbookDisplayNumber(value, field) {
306
+ if (!Number.isFinite(value)) {
307
+ throw new Error(`DeepBook account inventory display number is unavailable for ${field}`);
308
+ }
309
+ }
310
+ function rawToDeepbookDisplayAmount(raw, decimals) {
311
+ try {
312
+ return formatRawAmount(raw, decimals);
313
+ }
314
+ catch (error) {
315
+ throw new ReadServiceInputError("quote_unavailable", "DeepBook raw quote return value cannot be displayed", {
316
+ raw,
317
+ decimals,
318
+ reason: error instanceof Error ? error.message : "unknown"
319
+ });
320
+ }
321
+ }
@@ -0,0 +1,157 @@
1
+ import { mainnetCoins, mainnetPools } from "@mysten/deepbook-v3";
2
+ import { DEEPBOOK_SCALAR_UNIT_SOURCE, decimalsFromScalar, normalizeCoinType } from "./coinMetadata.js";
3
+ import { ReadServiceInputError } from "./readServiceTypes.js";
4
+ export const PINNED_DEEPBOOK_COINS = mainnetCoins;
5
+ // Curated DeepBook USDC chart pairs: the meaningful Sui-ecosystem base tokens worth
6
+ // featuring against USDC, in display order. This is a deliberate editorial allowlist
7
+ // — NOT a dynamic volume cut — so the chart shows a stable, hand-picked set and never
8
+ // surfaces the dead/dust pools the indexer also lists (stable-vs-stable, wrapped
9
+ // duplicates, single-trade listings). Each entry is a token judged worth registering
10
+ // on its own merits:
11
+ // SUI — Sui L1 gas / native token
12
+ // DEEP — DeepBook protocol token (this venue's own token)
13
+ // WAL — Walrus decentralized storage (Mysten)
14
+ // NS — SuiNS name service
15
+ // IKA — Ika MPC / dWallet network
16
+ // XBTC — Bitcoin on Sui
17
+ // USDT — Tether USD stablecoin
18
+ // Edit this list to change which pairs the chart offers; order here is display order.
19
+ const CURATED_USDC_CHART_BASE_ORDER = new Map(["SUI", "DEEP", "WAL", "NS", "IKA", "XBTC", "USDT"].map((symbol, index) => [symbol, index]));
20
+ // Filter the chart pool list to the curated base tokens (by symbol) in curated
21
+ // display order. Matching is by base SYMBOL because the indexer's pool name can
22
+ // differ from the SDK pool key (e.g. BWETH_USDC vs BETH_USDC).
23
+ export function curateUsdcChartPools(pools) {
24
+ return pools
25
+ .filter((pool) => CURATED_USDC_CHART_BASE_ORDER.has(pool.baseAsset.symbol))
26
+ .sort((left, right) => (CURATED_USDC_CHART_BASE_ORDER.get(left.baseAsset.symbol) ?? 0) -
27
+ (CURATED_USDC_CHART_BASE_ORDER.get(right.baseAsset.symbol) ?? 0));
28
+ }
29
+ export function listDeepbookTokenRegistry(coins = PINNED_DEEPBOOK_COINS) {
30
+ assertDeepbookScalars(coins);
31
+ const poolKeysBySymbol = new Map();
32
+ for (const [poolKey, pool] of Object.entries(mainnetPools)) {
33
+ for (const symbol of [pool.baseCoin, pool.quoteCoin]) {
34
+ const current = poolKeysBySymbol.get(symbol) ?? [];
35
+ current.push(poolKey);
36
+ poolKeysBySymbol.set(symbol, current);
37
+ }
38
+ }
39
+ return Object.entries(coins)
40
+ .map(([symbol, coin]) => toDeepbookTokenRegistryEntry(symbol, coin, (poolKeysBySymbol.get(symbol) ?? []).sort()))
41
+ .sort((left, right) => left.symbol.localeCompare(right.symbol));
42
+ }
43
+ export function deepbookUnitForCoinType(coinType, coins) {
44
+ const entry = findDeepbookCoinEntry(coinType, coins);
45
+ if (!entry) {
46
+ return undefined;
47
+ }
48
+ const decimals = decimalsFromScalar(entry.coin.scalar);
49
+ if (decimals === undefined) {
50
+ throw invalidDeepbookScalar(entry.symbol, entry.coin.scalar);
51
+ }
52
+ return { decimals, symbol: entry.symbol, name: entry.symbol };
53
+ }
54
+ export function findDeepbookCoinEntry(normalizedCoinType, coins) {
55
+ // Validate the whole pinned token unit registry before using any DeepBook
56
+ // coin match so one bad scalar cannot make the registry look partially trustworthy.
57
+ assertDeepbookScalars(coins);
58
+ for (const [symbol, coin] of Object.entries(coins)) {
59
+ if (normalizeCoinType(coin.type) === normalizedCoinType) {
60
+ return { symbol, coin };
61
+ }
62
+ }
63
+ return undefined;
64
+ }
65
+ export function getDeepbookCoinEntryBySymbol(symbol, coins) {
66
+ assertDeepbookScalars(coins);
67
+ const coin = coins[symbol];
68
+ if (!coin) {
69
+ throw new ReadServiceInputError("registry_miss", "DeepBook pool coin is missing from the pinned token registry", {
70
+ symbol
71
+ });
72
+ }
73
+ return { symbol, coin };
74
+ }
75
+ export function canonicalDeepbookSymbol(symbol, coins = PINNED_DEEPBOOK_COINS) {
76
+ const trimmed = symbol.trim();
77
+ if (!trimmed) {
78
+ return undefined;
79
+ }
80
+ const matches = Object.keys(coins).filter((candidate) => candidate.toLowerCase() === trimmed.toLowerCase());
81
+ return matches.length === 1 ? matches[0] : undefined;
82
+ }
83
+ export function getKnownPool(poolKey) {
84
+ const pool = mainnetPools[poolKey];
85
+ if (!pool) {
86
+ throw new ReadServiceInputError("registry_miss", "Unknown DeepBook mainnet pool key", { poolKey });
87
+ }
88
+ return pool;
89
+ }
90
+ export function resolveDeepbookPoolForSymbols(input) {
91
+ const matches = [];
92
+ for (const [poolKey, pool] of Object.entries(mainnetPools)) {
93
+ if (pool.baseCoin === input.sourceSymbol && pool.quoteCoin === input.targetSymbol) {
94
+ matches.push({
95
+ poolKey,
96
+ pool,
97
+ direction: "base_to_quote",
98
+ sourceSymbol: input.sourceSymbol,
99
+ targetSymbol: input.targetSymbol
100
+ });
101
+ }
102
+ if (pool.quoteCoin === input.sourceSymbol && pool.baseCoin === input.targetSymbol) {
103
+ matches.push({
104
+ poolKey,
105
+ pool,
106
+ direction: "quote_to_base",
107
+ sourceSymbol: input.sourceSymbol,
108
+ targetSymbol: input.targetSymbol
109
+ });
110
+ }
111
+ }
112
+ if (matches.length === 1) {
113
+ return matches[0];
114
+ }
115
+ if (matches.length > 1) {
116
+ throw new ReadServiceInputError("registry_miss", "DeepBook symbol pair resolves to multiple mainnet pools", {
117
+ sourceSymbol: input.sourceSymbol,
118
+ targetSymbol: input.targetSymbol,
119
+ poolKeys: matches.map((match) => match.poolKey)
120
+ });
121
+ }
122
+ throw new ReadServiceInputError("registry_miss", "DeepBook symbol pair is not a known direct mainnet pool", {
123
+ sourceSymbol: input.sourceSymbol,
124
+ targetSymbol: input.targetSymbol
125
+ });
126
+ }
127
+ export function invalidDeepbookScalar(symbol, scalar) {
128
+ return new ReadServiceInputError("registry_miss", "DeepBook token scalar is not a power of ten", {
129
+ symbol,
130
+ scalar
131
+ });
132
+ }
133
+ function toDeepbookTokenRegistryEntry(symbol, coin, poolKeys) {
134
+ const decimals = decimalsFromScalar(coin.scalar);
135
+ if (decimals === undefined) {
136
+ throw invalidDeepbookScalar(symbol, coin.scalar);
137
+ }
138
+ return {
139
+ symbol,
140
+ address: coin.address,
141
+ type: coin.type,
142
+ scalar: coin.scalar,
143
+ decimals,
144
+ unitSource: DEEPBOOK_SCALAR_UNIT_SOURCE,
145
+ ...(coin.feed === undefined ? {} : { feed: coin.feed }),
146
+ ...(coin.currencyId === undefined ? {} : { currencyId: coin.currencyId }),
147
+ ...(coin.priceInfoObjectId === undefined ? {} : { priceInfoObjectId: coin.priceInfoObjectId }),
148
+ poolKeys
149
+ };
150
+ }
151
+ function assertDeepbookScalars(coins) {
152
+ for (const [symbol, coin] of Object.entries(coins)) {
153
+ if (decimalsFromScalar(coin.scalar) === undefined) {
154
+ throw invalidDeepbookScalar(symbol, coin.scalar);
155
+ }
156
+ }
157
+ }
@@ -0,0 +1,159 @@
1
+ import { DEEPBOOK_OFFICIAL_INDEXER_PRICE_CONVENTION, DEEPBOOK_OFFICIAL_INDEXER_SOURCE_STATEMENT } from "./deepbookOfficialIndexerSource.js";
2
+ import { DEEPBOOK_SCALAR_UNIT_SOURCE } from "./coinMetadata.js";
3
+ export const DEEPBOOK_SOURCE_OWNER_GROUPS = {
4
+ pinnedSdkMetadata: {
5
+ label: "pinned DeepBook SDK metadata",
6
+ owns: ["token metadata", "pool metadata", "scalar metadata", "symbol metadata", "package metadata"]
7
+ },
8
+ sdkSimulation: {
9
+ label: "DeepBook SDK simulation through Sui gRPC",
10
+ owns: ["orderbook snapshots", "mid-price snapshots", "raw quote evidence", "display quote evidence", "account inventory"]
11
+ },
12
+ directSuiGrpcAndLocalMaterial: {
13
+ label: "direct Sui gRPC plus local material stores",
14
+ owns: ["wallet balances", "object facts", "transaction material", "review-time simulation", "receipt reads"]
15
+ },
16
+ officialIndexerRest: {
17
+ label: "DeepBookV3 official Indexer REST",
18
+ owns: ["USDC-quoted candle history", "price-at-time candles", "chart candles", "account-timeline USDC candle references"]
19
+ },
20
+ localTransactionActivity: {
21
+ label: "local SQLite transaction activity plus local protocol rules",
22
+ owns: ["account net-flow bars", "protocolMatches"]
23
+ },
24
+ guidanceOnly: {
25
+ label: "guidance and test enforcement only",
26
+ owns: ["runtime source wording", "unsupported-use wording", "source-policy tests"]
27
+ }
28
+ };
29
+ export const DEEPBOOK_ANSWER_USE = {
30
+ officialUsdcCandleHistory: "official_deepbook_usdc_candle_history",
31
+ officialCandleAvailabilityForRequestedUtcRange: "official_candle_availability_for_the_requested_utc_range",
32
+ officialUsdcCandleForRequestedTime: "official_deepbook_usdc_candle_for_requested_time",
33
+ representativeClosePriceForMatchedCandle: "representative_close_price_for_the_matched_candle"
34
+ };
35
+ export const DEEPBOOK_SOURCE_FIELD_VALUES = {
36
+ officialIndexer: "deepbook_v3_official_indexer",
37
+ sdkMainnetPackageId: "deepbook_v3_sdk_mainnet_package_id",
38
+ pinnedSdkWhenTargetAssetSelected: "pinned_deepbook_sdk_when_target_asset_selected"
39
+ };
40
+ export const DEEPBOOK_SDK_SIMULATION_SOURCE_BASE = {
41
+ sdk: "@mysten/deepbook-v3",
42
+ transport: "grpc",
43
+ simulation: "client.core.simulateTransaction"
44
+ };
45
+ export const DEEPBOOK_PINNED_SDK_METADATA_SOURCE = {
46
+ sdk: "@mysten/deepbook-v3",
47
+ registry: ["mainnetCoins", "mainnetPools"],
48
+ network: "mainnet",
49
+ unitSource: DEEPBOOK_SCALAR_UNIT_SOURCE
50
+ };
51
+ export const DEEPBOOK_OFFICIAL_INDEXER_SOURCE_BASE = {
52
+ kind: DEEPBOOK_SOURCE_FIELD_VALUES.officialIndexer,
53
+ chainRecomputedBySuiMcp: false
54
+ };
55
+ export const DEEPBOOK_OFFICIAL_INDEXER_USDC_REFERENCE = {
56
+ quoteAsset: "USDC",
57
+ priceConvention: DEEPBOOK_OFFICIAL_INDEXER_PRICE_CONVENTION,
58
+ usdcIsFiatUsd: false,
59
+ usdPegGuaranteeAvailable: false
60
+ };
61
+ export const DEEPBOOK_OFFICIAL_INDEXER_CANDLE_USE = {
62
+ allowedUse: DEEPBOOK_ANSWER_USE.officialUsdcCandleHistory,
63
+ source: DEEPBOOK_OFFICIAL_INDEXER_SOURCE_BASE.kind,
64
+ ...DEEPBOOK_OFFICIAL_INDEXER_USDC_REFERENCE,
65
+ chainRecomputedBySuiMcp: DEEPBOOK_OFFICIAL_INDEXER_SOURCE_BASE.chainRecomputedBySuiMcp
66
+ };
67
+ export const DEEPBOOK_SOURCE_OWNER_RUNTIME_WORDING = {
68
+ officialIndexerCandleData: "DeepBookV3 official Indexer candle data",
69
+ officialIndexerCandleReferences: "DeepBookV3 official Indexer candle references",
70
+ officialIndexerUsdcDenominatedCandles: "DeepBookV3 official Indexer USDC-denominated candles",
71
+ pinnedSdkSnapshots: "pinned-SDK snapshots",
72
+ usdcNotFiatUsdAndNotPeg: "not fiat USD and not a USDC/USD peg guarantee"
73
+ };
74
+ export const DEEPBOOK_OFFICIAL_INDEXER_RESPONSE_TEXT = {
75
+ sourceStatement: DEEPBOOK_OFFICIAL_INDEXER_SOURCE_STATEMENT,
76
+ usdcDisclaimer: `USDC is a token-denominated reference asset here, ${DEEPBOOK_SOURCE_OWNER_RUNTIME_WORDING.usdcNotFiatUsdAndNotPeg}.`
77
+ };
78
+ export const DEEPBOOK_READ_RESPONSE_UNSUPPORTED = {
79
+ orderbook: [
80
+ "live_orderbook_stream",
81
+ "global_market_price",
82
+ "indicative_quote_for_a_source_amount",
83
+ "payment_coverage_or_shortfall",
84
+ "liquidity_verdict",
85
+ "price_impact",
86
+ "venue_comparison",
87
+ "route_recommendation",
88
+ "transaction_building",
89
+ "signing_data_or_readiness",
90
+ "profit_or_pnl"
91
+ ],
92
+ midPrice: [
93
+ "global_market_price",
94
+ "fiat_usd_cash_out",
95
+ "external_market_price_conversion",
96
+ "usd_peg_assumption",
97
+ "payment_coverage_or_shortfall",
98
+ "price_impact",
99
+ "quote_slippage",
100
+ "venue_comparison",
101
+ "route_recommendation",
102
+ "transaction_building",
103
+ "signing_data_or_readiness",
104
+ "profit_or_pnl",
105
+ "cost_basis"
106
+ ],
107
+ officialUsdcCandles: [
108
+ "fiat_usd_cash_out",
109
+ "usd_peg_assumption",
110
+ "global_market_price",
111
+ "historical_mid_price",
112
+ "live_quote",
113
+ "route_recommendation",
114
+ "best_route",
115
+ "transaction_building",
116
+ "signing_data_or_readiness",
117
+ "profit_or_pnl",
118
+ "cost_basis"
119
+ ],
120
+ quote: [
121
+ "payment_coverage",
122
+ "payment_shortfall",
123
+ "funding_source",
124
+ "route_dependent_payment_support",
125
+ "final_min_out",
126
+ "liquidity_verdict",
127
+ "price_impact",
128
+ "quote_vs_mid_slippage",
129
+ "effective_price",
130
+ "venue_comparison",
131
+ "route_recommendation",
132
+ "fiat_usd_cash_out",
133
+ "external_market_price_conversion",
134
+ "usd_peg_assumption",
135
+ "transaction_building",
136
+ "signing_data_or_readiness",
137
+ "profit_or_pnl",
138
+ "cost_basis"
139
+ ],
140
+ accountInventory: [
141
+ "current_wallet_coin_balance",
142
+ "wallet_transaction_history",
143
+ "funding_source",
144
+ "route_liquidity",
145
+ "withdrawal_readiness",
146
+ "payment_coverage_or_shortfall",
147
+ "transaction_building",
148
+ "signing_data_or_readiness",
149
+ "profit_or_pnl",
150
+ "cost_basis"
151
+ ],
152
+ protocolMatches: [
153
+ "market_data",
154
+ "route_support",
155
+ "inventory_evidence",
156
+ "signing_readiness",
157
+ "official_indexer_replacement_evidence"
158
+ ]
159
+ };