@wowok/agent-mcp 2.7.1 → 2.7.3

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 (597) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/account-events.d.ts +32 -0
  4. package/dist/customer/account-events.js +1 -0
  5. package/dist/customer/customer-advice.d.ts +1 -0
  6. package/dist/customer/customer-advice.js +1 -130
  7. package/dist/customer/index.js +1 -11
  8. package/dist/customer/industry-risks.js +1 -438
  9. package/dist/customer/info-puzzle.js +1 -681
  10. package/dist/customer/order-monitor.js +1 -328
  11. package/dist/customer/order-strategy.d.ts +1 -1
  12. package/dist/customer/order-strategy.js +1 -373
  13. package/dist/customer/post-purchase.js +1 -351
  14. package/dist/customer/preorder-compare.js +1 -34
  15. package/dist/customer/reminder-system.d.ts +2 -0
  16. package/dist/customer/reminder-system.js +1 -316
  17. package/dist/customer/risk-assessment.d.ts +1 -0
  18. package/dist/customer/risk-assessment.js +1 -397
  19. package/dist/customer/types.d.ts +2 -0
  20. package/dist/customer/types.js +1 -13
  21. package/dist/customer/user-preferences.js +1 -460
  22. package/dist/evaluation/arbitration-game.d.ts +9 -2
  23. package/dist/evaluation/arbitration-game.js +1 -48
  24. package/dist/evaluation/builtins/arbitration-score.d.ts +41 -0
  25. package/dist/evaluation/builtins/arbitration-score.js +1 -0
  26. package/dist/evaluation/builtins/demand-match.js +1 -153
  27. package/dist/evaluation/builtins/index.d.ts +1 -0
  28. package/dist/evaluation/builtins/index.js +1 -10
  29. package/dist/evaluation/builtins/service-risk.js +1 -55
  30. package/dist/evaluation/capability.js +1 -13
  31. package/dist/evaluation/category-match-rules.d.ts +30 -0
  32. package/dist/evaluation/category-match-rules.js +1 -0
  33. package/dist/evaluation/composer.js +1 -40
  34. package/dist/evaluation/engine.js +1 -175
  35. package/dist/evaluation/extract.js +1 -115
  36. package/dist/evaluation/game-strategy.d.ts +27 -0
  37. package/dist/evaluation/game-strategy.js +1 -0
  38. package/dist/evaluation/gap.js +1 -100
  39. package/dist/evaluation/index.d.ts +2 -0
  40. package/dist/evaluation/index.js +1 -11
  41. package/dist/evaluation/location-match.d.ts +42 -0
  42. package/dist/evaluation/location-match.js +1 -0
  43. package/dist/evaluation/node-game.d.ts +31 -3
  44. package/dist/evaluation/node-game.js +1 -57
  45. package/dist/evaluation/path-reasoning.d.ts +35 -0
  46. package/dist/evaluation/path-reasoning.js +1 -0
  47. package/dist/evaluation/region.d.ts +6 -0
  48. package/dist/evaluation/region.js +1 -36
  49. package/dist/evaluation/types.d.ts +18 -0
  50. package/dist/evaluation/types.js +1 -1
  51. package/dist/evaluation/user-injection.js +1 -27
  52. package/dist/experience/experience-reuse.js +1 -103
  53. package/dist/experience/index.js +1 -5
  54. package/dist/experience/intent-distill.js +1 -83
  55. package/dist/experience/realtime-feedback.js +1 -94
  56. package/dist/experience/types.js +1 -1
  57. package/dist/experience/user-profile.d.ts +1 -1
  58. package/dist/experience/user-profile.js +1 -171
  59. package/dist/extensions/business-modules.js +1 -287
  60. package/dist/extensions/capability-manifest.js +1 -781
  61. package/dist/extensions/constraint-registry.js +1 -198
  62. package/dist/extensions/index.d.ts +6 -0
  63. package/dist/extensions/index.js +1 -6
  64. package/dist/extensions/industry-layers.d.ts +75 -0
  65. package/dist/extensions/industry-layers.js +1 -0
  66. package/dist/extensions/industry-pack.d.ts +105 -0
  67. package/dist/extensions/industry-pack.js +1 -0
  68. package/dist/extensions/metric-registry.js +1 -257
  69. package/dist/extensions/mode-evaluator.d.ts +1 -1
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.d.ts +1 -0
  73. package/dist/extensions/registry.js +1 -717
  74. package/dist/extensions/types.js +1 -1
  75. package/dist/graph/base.d.ts +8 -0
  76. package/dist/graph/base.js +1 -0
  77. package/dist/harness/auto-escalation.js +1 -68
  78. package/dist/harness/checkpoint.js +1 -129
  79. package/dist/harness/index.d.ts +1 -0
  80. package/dist/harness/index.js +1 -78
  81. package/dist/harness/plan.d.ts +2 -0
  82. package/dist/harness/plan.js +1 -315
  83. package/dist/harness/recover.d.ts +1 -1
  84. package/dist/harness/recover.js +1 -139
  85. package/dist/harness/types.d.ts +2 -3
  86. package/dist/harness/types.js +1 -1
  87. package/dist/harness/verify.js +1 -237
  88. package/dist/index.js +1 -273
  89. package/dist/intent/enrich.js +1 -67
  90. package/dist/intent/index.js +1 -60
  91. package/dist/intent/matcher.js +1 -81
  92. package/dist/intent/store.js +1 -55
  93. package/dist/intent/types.js +1 -10
  94. package/dist/knowledge/acquisition-flywheel.js +1 -192
  95. package/dist/knowledge/allocation-confirm.js +1 -534
  96. package/dist/knowledge/allocation-context.js +1 -249
  97. package/dist/knowledge/allocation-ledger.js +1 -463
  98. package/dist/knowledge/allocation-puzzle.js +1 -298
  99. package/dist/knowledge/allocation-risk.js +1 -568
  100. package/dist/knowledge/allocation-templates.js +1 -970
  101. package/dist/knowledge/allocation-translation.js +1 -585
  102. package/dist/knowledge/anti-cheat.d.ts +37 -0
  103. package/dist/knowledge/anti-cheat.js +1 -0
  104. package/dist/knowledge/arb-confirm.d.ts +28 -0
  105. package/dist/knowledge/arb-confirm.js +1 -0
  106. package/dist/knowledge/arb-risk.js +1 -210
  107. package/dist/knowledge/arb-translation.d.ts +48 -0
  108. package/dist/knowledge/arb-translation.js +1 -0
  109. package/dist/knowledge/arbitration-confirm.js +1 -559
  110. package/dist/knowledge/arbitration-context.js +1 -505
  111. package/dist/knowledge/arbitration-ledger.js +1 -521
  112. package/dist/knowledge/arbitration-puzzle.js +1 -304
  113. package/dist/knowledge/arbitration-risk.js +1 -423
  114. package/dist/knowledge/arbitration-templates.js +1 -276
  115. package/dist/knowledge/arbitration-translation.js +1 -487
  116. package/dist/knowledge/audit-rules.js +1 -141
  117. package/dist/knowledge/bridge-confirm.d.ts +26 -0
  118. package/dist/knowledge/bridge-confirm.js +1 -0
  119. package/dist/knowledge/bridge-risk.js +1 -263
  120. package/dist/knowledge/bridge-translation.d.ts +37 -0
  121. package/dist/knowledge/bridge-translation.js +1 -0
  122. package/dist/knowledge/contact-confirm.d.ts +27 -0
  123. package/dist/knowledge/contact-confirm.js +1 -0
  124. package/dist/knowledge/contact-risk.js +1 -200
  125. package/dist/knowledge/contact-templates.js +1 -60
  126. package/dist/knowledge/contact-translation.d.ts +39 -0
  127. package/dist/knowledge/contact-translation.js +1 -0
  128. package/dist/knowledge/demand-confirm.js +1 -206
  129. package/dist/knowledge/demand-context.d.ts +17 -0
  130. package/dist/knowledge/demand-context.js +1 -0
  131. package/dist/knowledge/demand-ledger.d.ts +26 -0
  132. package/dist/knowledge/demand-ledger.js +1 -0
  133. package/dist/knowledge/demand-matching.js +1 -132
  134. package/dist/knowledge/demand-puzzle.d.ts +29 -0
  135. package/dist/knowledge/demand-puzzle.js +1 -0
  136. package/dist/knowledge/demand-risk.js +1 -240
  137. package/dist/knowledge/demand-templates.d.ts +12 -0
  138. package/dist/knowledge/demand-templates.js +1 -0
  139. package/dist/knowledge/demand-translation.js +1 -354
  140. package/dist/knowledge/deployment-scanner.js +1 -823
  141. package/dist/knowledge/dynamic-pricing.js +1 -87
  142. package/dist/knowledge/evidence-review.d.ts +12 -0
  143. package/dist/knowledge/evidence-review.js +1 -0
  144. package/dist/knowledge/examples-scanner-cli.js +1 -26
  145. package/dist/knowledge/examples-scanner.js +1 -843
  146. package/dist/knowledge/flywheel-loop.d.ts +0 -1
  147. package/dist/knowledge/flywheel-loop.js +1 -404
  148. package/dist/knowledge/fund-layer.js +1 -973
  149. package/dist/knowledge/glossary.js +1 -211
  150. package/dist/knowledge/guard-confirm.js +1 -406
  151. package/dist/knowledge/guard-context.js +1 -287
  152. package/dist/knowledge/guard-design-patterns.js +1 -360
  153. package/dist/knowledge/guard-ledger.js +1 -260
  154. package/dist/knowledge/guard-lint.js +1 -670
  155. package/dist/knowledge/guard-migration.d.ts +1 -1
  156. package/dist/knowledge/guard-migration.js +1 -228
  157. package/dist/knowledge/guard-puzzle.js +1 -805
  158. package/dist/knowledge/guard-render.js +1 -700
  159. package/dist/knowledge/guard-risk.js +1 -1879
  160. package/dist/knowledge/guard-submission-prompt.js +1 -171
  161. package/dist/knowledge/guard-templates.js +1 -1105
  162. package/dist/knowledge/guard-translation.js +1 -1119
  163. package/dist/knowledge/index.d.ts +71 -3
  164. package/dist/knowledge/index.js +1 -436
  165. package/dist/knowledge/industry-evolution.js +1 -323
  166. package/dist/knowledge/industry-generalizer.js +1 -381
  167. package/dist/knowledge/industry-registry.js +1 -174
  168. package/dist/knowledge/intent-metrics.d.ts +4 -3
  169. package/dist/knowledge/intent-metrics.js +1 -566
  170. package/dist/knowledge/machine-confirm.js +1 -559
  171. package/dist/knowledge/machine-context.js +1 -833
  172. package/dist/knowledge/machine-ledger.js +1 -338
  173. package/dist/knowledge/machine-puzzle.js +1 -494
  174. package/dist/knowledge/machine-render.js +1 -565
  175. package/dist/knowledge/machine-risk.js +1 -669
  176. package/dist/knowledge/machine-templates.js +1 -1597
  177. package/dist/knowledge/machine-topology.js +1 -234
  178. package/dist/knowledge/machine-translation.js +1 -513
  179. package/dist/knowledge/market-metrics.d.ts +12 -0
  180. package/dist/knowledge/market-metrics.js +1 -0
  181. package/dist/knowledge/market-operations.d.ts +46 -0
  182. package/dist/knowledge/market-operations.js +1 -0
  183. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  184. package/dist/knowledge/mcp-schema-audit.d.ts +22 -22
  185. package/dist/knowledge/mcp-schema-audit.js +1 -777
  186. package/dist/knowledge/onchain-constants.js +1 -35
  187. package/dist/knowledge/order-confirm.js +1 -573
  188. package/dist/knowledge/order-context.js +1 -390
  189. package/dist/knowledge/order-ledger.js +1 -341
  190. package/dist/knowledge/order-puzzle.js +1 -255
  191. package/dist/knowledge/order-risk.js +1 -653
  192. package/dist/knowledge/order-templates.js +1 -368
  193. package/dist/knowledge/order-translation.js +1 -550
  194. package/dist/knowledge/overrides-loader.js +1 -65
  195. package/dist/knowledge/passport-confirm.js +1 -531
  196. package/dist/knowledge/passport-context.js +1 -306
  197. package/dist/knowledge/passport-ledger.js +1 -282
  198. package/dist/knowledge/passport-puzzle.js +1 -333
  199. package/dist/knowledge/passport-risk.js +1 -450
  200. package/dist/knowledge/passport-templates.js +1 -568
  201. package/dist/knowledge/passport-translation.js +1 -516
  202. package/dist/knowledge/payment-confirm.d.ts +26 -0
  203. package/dist/knowledge/payment-confirm.js +1 -0
  204. package/dist/knowledge/payment-risk.js +1 -249
  205. package/dist/knowledge/payment-translation.d.ts +37 -0
  206. package/dist/knowledge/payment-translation.js +1 -0
  207. package/dist/knowledge/permission-confirm.js +1 -426
  208. package/dist/knowledge/permission-context.js +1 -224
  209. package/dist/knowledge/permission-ledger.d.ts +11 -0
  210. package/dist/knowledge/permission-ledger.js +1 -403
  211. package/dist/knowledge/permission-puzzle.js +1 -173
  212. package/dist/knowledge/permission-risk.js +1 -411
  213. package/dist/knowledge/permission-templates.js +1 -234
  214. package/dist/knowledge/permission-translation.js +1 -350
  215. package/dist/knowledge/personal-confirm.d.ts +29 -0
  216. package/dist/knowledge/personal-confirm.js +1 -0
  217. package/dist/knowledge/personal-risk.js +1 -212
  218. package/dist/knowledge/personal-translation.d.ts +37 -0
  219. package/dist/knowledge/personal-translation.js +1 -0
  220. package/dist/knowledge/process-model.d.ts +1 -11
  221. package/dist/knowledge/process-model.js +1 -160
  222. package/dist/knowledge/progress-confirm.js +1 -456
  223. package/dist/knowledge/progress-context.js +1 -452
  224. package/dist/knowledge/progress-ledger.js +1 -330
  225. package/dist/knowledge/progress-puzzle.js +1 -219
  226. package/dist/knowledge/progress-risk.js +1 -461
  227. package/dist/knowledge/progress-templates.js +1 -228
  228. package/dist/knowledge/progress-translation.js +1 -405
  229. package/dist/knowledge/proof-confirm.js +1 -187
  230. package/dist/knowledge/proof-context.d.ts +17 -0
  231. package/dist/knowledge/proof-context.js +1 -0
  232. package/dist/knowledge/proof-ledger.d.ts +34 -0
  233. package/dist/knowledge/proof-ledger.js +1 -0
  234. package/dist/knowledge/proof-puzzle.d.ts +35 -0
  235. package/dist/knowledge/proof-puzzle.js +1 -0
  236. package/dist/knowledge/proof-risk.js +1 -207
  237. package/dist/knowledge/proof-templates.d.ts +22 -0
  238. package/dist/knowledge/proof-templates.js +1 -0
  239. package/dist/knowledge/proof-translation.js +1 -283
  240. package/dist/knowledge/registrar-confirm.d.ts +26 -0
  241. package/dist/knowledge/registrar-confirm.js +1 -0
  242. package/dist/knowledge/registrar-risk.js +1 -217
  243. package/dist/knowledge/registrar-translation.d.ts +37 -0
  244. package/dist/knowledge/registrar-translation.js +1 -0
  245. package/dist/knowledge/repository-confirm.js +1 -286
  246. package/dist/knowledge/repository-context.d.ts +12 -0
  247. package/dist/knowledge/repository-context.js +1 -0
  248. package/dist/knowledge/repository-ledger.d.ts +25 -0
  249. package/dist/knowledge/repository-ledger.js +1 -0
  250. package/dist/knowledge/repository-puzzle.d.ts +30 -0
  251. package/dist/knowledge/repository-puzzle.js +1 -0
  252. package/dist/knowledge/repository-risk.js +1 -373
  253. package/dist/knowledge/repository-templates.d.ts +14 -0
  254. package/dist/knowledge/repository-templates.js +1 -0
  255. package/dist/knowledge/repository-translation.js +1 -445
  256. package/dist/knowledge/reputation-rules.js +1 -99
  257. package/dist/knowledge/resource-confirm.d.ts +25 -0
  258. package/dist/knowledge/resource-confirm.js +1 -0
  259. package/dist/knowledge/resource-risk.js +1 -157
  260. package/dist/knowledge/resource-translation.d.ts +37 -0
  261. package/dist/knowledge/resource-translation.js +1 -0
  262. package/dist/knowledge/reward-confirm.js +1 -526
  263. package/dist/knowledge/reward-context.d.ts +2 -2
  264. package/dist/knowledge/reward-context.js +1 -504
  265. package/dist/knowledge/reward-ledger.js +1 -502
  266. package/dist/knowledge/reward-puzzle.js +1 -300
  267. package/dist/knowledge/reward-risk.js +1 -627
  268. package/dist/knowledge/reward-templates.js +1 -197
  269. package/dist/knowledge/reward-translation.js +1 -501
  270. package/dist/knowledge/safety-rules.d.ts +1 -0
  271. package/dist/knowledge/safety-rules.js +1 -404
  272. package/dist/knowledge/scenario-modes.js +1 -321
  273. package/dist/knowledge/service-confirm.js +1 -807
  274. package/dist/knowledge/service-context.js +1 -403
  275. package/dist/knowledge/service-ledger.js +1 -609
  276. package/dist/knowledge/service-puzzle.js +1 -236
  277. package/dist/knowledge/service-risk.d.ts +1 -1
  278. package/dist/knowledge/service-risk.js +1 -651
  279. package/dist/knowledge/service-templates.js +1 -456
  280. package/dist/knowledge/service-translation.js +1 -622
  281. package/dist/knowledge/template-registry.js +1 -353
  282. package/dist/knowledge/tool-constraints.js +1 -195
  283. package/dist/knowledge/tools-reference.js +1 -178
  284. package/dist/knowledge/treasury-confirm.js +1 -512
  285. package/dist/knowledge/treasury-context.js +1 -363
  286. package/dist/knowledge/treasury-ledger.js +1 -300
  287. package/dist/knowledge/treasury-puzzle.js +1 -216
  288. package/dist/knowledge/treasury-risk.js +1 -440
  289. package/dist/knowledge/treasury-templates.js +1 -358
  290. package/dist/knowledge/treasury-translation.js +1 -498
  291. package/dist/knowledge/trust-metrics.js +1 -198
  292. package/dist/knowledge/universal-template.d.ts +22 -0
  293. package/dist/knowledge/universal-template.js +1 -0
  294. package/dist/knowledge/util-confirm.d.ts +24 -0
  295. package/dist/knowledge/util-confirm.js +1 -0
  296. package/dist/knowledge/util-risk.js +1 -135
  297. package/dist/knowledge/util-translation.d.ts +38 -0
  298. package/dist/knowledge/util-translation.js +1 -0
  299. package/dist/knowledge/workflow-guidance.d.ts +116 -0
  300. package/dist/knowledge/workflow-guidance.js +1 -0
  301. package/dist/loop-engineering/aggregate.js +1 -132
  302. package/dist/loop-engineering/context-collect.js +1 -83
  303. package/dist/loop-engineering/diagnose.js +1 -273
  304. package/dist/loop-engineering/improve.js +1 -405
  305. package/dist/loop-engineering/index.js +1 -4
  306. package/dist/loop-engineering/pipeline.js +1 -56
  307. package/dist/mode-market/index.js +1 -3
  308. package/dist/mode-market/registry.js +1 -124
  309. package/dist/mode-market/review.js +1 -214
  310. package/dist/mode-market/submission.js +1 -85
  311. package/dist/participation/collaborator-interest.d.ts +23 -0
  312. package/dist/participation/collaborator-interest.js +1 -0
  313. package/dist/participation/customer-interest.d.ts +25 -0
  314. package/dist/participation/customer-interest.js +1 -0
  315. package/dist/participation/employee-kpi.d.ts +25 -0
  316. package/dist/participation/employee-kpi.js +1 -0
  317. package/dist/participation/employee-store.d.ts +16 -0
  318. package/dist/participation/employee-store.js +1 -0
  319. package/dist/participation/index.d.ts +2 -0
  320. package/dist/participation/index.js +1 -0
  321. package/dist/participation/merchant-interest.js +1 -100
  322. package/dist/participation/radar-core.d.ts +13 -3
  323. package/dist/participation/radar-core.js +1 -269
  324. package/dist/participation/supplier-interest.d.ts +25 -0
  325. package/dist/participation/supplier-interest.js +1 -0
  326. package/dist/persona/analyzer.js +1 -66
  327. package/dist/persona/bridge.js +1 -86
  328. package/dist/persona/defaults.js +1 -195
  329. package/dist/persona/experience-bridge.js +1 -23
  330. package/dist/persona/index.d.ts +9 -2
  331. package/dist/persona/index.js +1 -71
  332. package/dist/persona/local-region.d.ts +20 -0
  333. package/dist/persona/local-region.js +1 -0
  334. package/dist/persona/model.js +1 -111
  335. package/dist/persona/overrides.d.ts +10 -0
  336. package/dist/persona/overrides.js +1 -0
  337. package/dist/persona/pack-personae.d.ts +11 -0
  338. package/dist/persona/pack-personae.js +1 -0
  339. package/dist/persona/store.js +1 -62
  340. package/dist/persona/strategy-intent.d.ts +20 -0
  341. package/dist/persona/strategy-intent.js +1 -0
  342. package/dist/persona/types.d.ts +6 -2
  343. package/dist/persona/types.js +1 -5
  344. package/dist/project/business-puzzle.d.ts +1 -1
  345. package/dist/project/business-puzzle.js +1 -383
  346. package/dist/project/context-assembly.js +1 -254
  347. package/dist/project/deployment-bridge.js +1 -120
  348. package/dist/project/deployment-doc.js +1 -1126
  349. package/dist/project/edit-planner.js +1 -1342
  350. package/dist/project/evaluation.d.ts +37 -1
  351. package/dist/project/evaluation.js +1 -2011
  352. package/dist/project/game-theory.js +1 -177
  353. package/dist/project/graph-builder.js +1 -656
  354. package/dist/project/graph.d.ts +3 -6
  355. package/dist/project/graph.js +1 -340
  356. package/dist/project/handlers.d.ts +33 -2
  357. package/dist/project/handlers.js +1 -1784
  358. package/dist/project/index.d.ts +2 -0
  359. package/dist/project/index.js +1 -301
  360. package/dist/project/intent-analyzer.js +1 -149
  361. package/dist/project/machine-nodes.js +1 -36
  362. package/dist/project/merchant-guide.d.ts +19 -0
  363. package/dist/project/merchant-guide.js +1 -264
  364. package/dist/project/migration.js +1 -125
  365. package/dist/project/mode-actions.js +1 -309
  366. package/dist/project/namespace.js +1 -206
  367. package/dist/project/participation-radar.js +1 -428
  368. package/dist/project/pipeline-actions.js +1 -109
  369. package/dist/project/project-store.js +1 -422
  370. package/dist/project/query.js +1 -153
  371. package/dist/project/reverse-mapping.d.ts +34 -0
  372. package/dist/project/reverse-mapping.js +1 -0
  373. package/dist/project/risk-aggregator.js +1 -295
  374. package/dist/project/rollback-policy.js +1 -290
  375. package/dist/project/semantic-assembler.js +1 -345
  376. package/dist/project/semantic-graph.d.ts +3 -5
  377. package/dist/project/semantic-graph.js +1 -292
  378. package/dist/project/stage-gate.js +1 -369
  379. package/dist/project/substep-trace.js +1 -332
  380. package/dist/project/task-tracker.js +1 -78
  381. package/dist/project/workflow-design-assessment.d.ts +24 -0
  382. package/dist/project/workflow-design-assessment.js +1 -0
  383. package/dist/role/derivation.d.ts +18 -0
  384. package/dist/role/derivation.js +1 -0
  385. package/dist/role/index.d.ts +5 -0
  386. package/dist/role/index.js +1 -0
  387. package/dist/role/model.d.ts +8 -0
  388. package/dist/role/model.js +1 -0
  389. package/dist/role/resolution.d.ts +11 -0
  390. package/dist/role/resolution.js +1 -0
  391. package/dist/role/types.d.ts +11 -0
  392. package/dist/role/types.js +1 -0
  393. package/dist/rules.js +1 -52
  394. package/dist/safety/confirm-gate.d.ts +1 -1
  395. package/dist/safety/confirm-gate.js +1 -88
  396. package/dist/safety/index.js +1 -3
  397. package/dist/safety/preview.js +1 -52
  398. package/dist/schema/call/allocation.d.ts +186 -1385
  399. package/dist/schema/call/allocation.js +1 -34
  400. package/dist/schema/call/arbitration.d.ts +272 -1871
  401. package/dist/schema/call/arbitration.js +1 -113
  402. package/dist/schema/call/base.d.ts +1831 -9076
  403. package/dist/schema/call/base.js +1 -370
  404. package/dist/schema/call/bridge.d.ts +911 -3171
  405. package/dist/schema/call/bridge.js +1 -458
  406. package/dist/schema/call/contact.d.ts +135 -931
  407. package/dist/schema/call/contact.js +1 -37
  408. package/dist/schema/call/demand.d.ts +164 -1194
  409. package/dist/schema/call/demand.js +1 -47
  410. package/dist/schema/call/guard.d.ts +298 -1140
  411. package/dist/schema/call/guard.js +1 -161
  412. package/dist/schema/call/handler.js +1 -322
  413. package/dist/schema/call/index.js +1 -20
  414. package/dist/schema/call/machine.d.ts +459 -5403
  415. package/dist/schema/call/machine.js +1 -193
  416. package/dist/schema/call/order.d.ts +137 -844
  417. package/dist/schema/call/order.js +1 -35
  418. package/dist/schema/call/payment.d.ts +74 -561
  419. package/dist/schema/call/payment.js +1 -37
  420. package/dist/schema/call/permission-handler.js +1 -54
  421. package/dist/schema/call/permission.d.ts +335 -2791
  422. package/dist/schema/call/permission.js +1 -105
  423. package/dist/schema/call/personal.d.ts +227 -1814
  424. package/dist/schema/call/personal.js +1 -78
  425. package/dist/schema/call/progress.d.ts +140 -843
  426. package/dist/schema/call/progress.js +1 -47
  427. package/dist/schema/call/proof.d.ts +42 -258
  428. package/dist/schema/call/proof.js +1 -33
  429. package/dist/schema/call/repository.d.ts +324 -2222
  430. package/dist/schema/call/repository.js +1 -77
  431. package/dist/schema/call/reward.d.ts +153 -1183
  432. package/dist/schema/call/reward.js +1 -30
  433. package/dist/schema/call/semantic.js +1 -1679
  434. package/dist/schema/call/service.d.ts +376 -3431
  435. package/dist/schema/call/service.js +1 -184
  436. package/dist/schema/call/treasury.d.ts +252 -2158
  437. package/dist/schema/call/treasury.js +1 -71
  438. package/dist/schema/common/index.d.ts +222 -697
  439. package/dist/schema/common/index.js +1 -407
  440. package/dist/schema/config/index.d.ts +18 -161
  441. package/dist/schema/config/index.js +1 -68
  442. package/dist/schema/employee/index.d.ts +99 -0
  443. package/dist/schema/employee/index.js +1 -0
  444. package/dist/schema/evaluation/index.d.ts +1062 -3748
  445. package/dist/schema/evaluation/index.js +1 -356
  446. package/dist/schema/index.d.ts +3 -0
  447. package/dist/schema/index.js +1 -17
  448. package/dist/schema/industry-pack/index.d.ts +132 -0
  449. package/dist/schema/industry-pack/index.js +1 -0
  450. package/dist/schema/intent-radar/index.d.ts +92 -245
  451. package/dist/schema/intent-radar/index.js +1 -89
  452. package/dist/schema/local/index.d.ts +2045 -18080
  453. package/dist/schema/local/index.js +1 -927
  454. package/dist/schema/local/wip.d.ts +61 -651
  455. package/dist/schema/local/wip.js +1 -187
  456. package/dist/schema/messenger/index.d.ts +949 -5557
  457. package/dist/schema/messenger/index.js +1 -475
  458. package/dist/schema/operations.d.ts +2969 -26518
  459. package/dist/schema/operations.js +1 -520
  460. package/dist/schema/persona/index.d.ts +469 -1820
  461. package/dist/schema/persona/index.js +1 -148
  462. package/dist/schema/project/index.d.ts +1027 -8408
  463. package/dist/schema/project/index.js +1 -2057
  464. package/dist/schema/query/index.d.ts +12041 -75261
  465. package/dist/schema/query/index.js +1 -1646
  466. package/dist/schema/schema-query/index.d.ts +35 -98
  467. package/dist/schema/schema-query/index.js +1 -104
  468. package/dist/schema/schema-version.js +1 -76
  469. package/dist/schema/task-status.d.ts +26 -132
  470. package/dist/schema/task-status.js +1 -36
  471. package/dist/schema/trust/index.d.ts +194 -1290
  472. package/dist/schema/trust/index.js +1 -314
  473. package/dist/schema/utils/guard-parser.js +1 -419
  474. package/dist/schema/utils/guard-query-utils.js +1 -46
  475. package/dist/schema/utils/node-parser.js +1 -369
  476. package/dist/schema/utils/object-type-utils.js +1 -35
  477. package/dist/schema/utils/permission-index-utils.js +1 -7
  478. package/dist/schema/utils/permission-machine-check.js +1 -121
  479. package/dist/schema/utils/skills-recommendation.d.ts +1 -0
  480. package/dist/schema/utils/skills-recommendation.js +1 -77
  481. package/dist/schema/workspace/index.d.ts +69 -0
  482. package/dist/schema/workspace/index.js +1 -0
  483. package/dist/schema-query-impl/index.js +1 -0
  484. package/dist/schemas/account_operation.output.json +3147 -1652
  485. package/dist/schemas/account_operation.schema.json +225 -218
  486. package/dist/schemas/bridge_operation.output.json +1168 -650
  487. package/dist/schemas/bridge_operation.schema.json +736 -504
  488. package/dist/schemas/config_operation.output.json +185 -179
  489. package/dist/schemas/config_operation.schema.json +21 -26
  490. package/dist/schemas/employee_operation.output.json +207 -0
  491. package/dist/schemas/employee_operation.schema.json +176 -0
  492. package/dist/schemas/evaluation_operation.output.json +2329 -557
  493. package/dist/schemas/evaluation_operation.schema.json +2939 -720
  494. package/dist/schemas/guard2file.output.json +58 -64
  495. package/dist/schemas/guard2file.schema.json +79 -81
  496. package/dist/schemas/index.json +29 -11
  497. package/dist/schemas/industry_pack_operation.output.json +594 -0
  498. package/dist/schemas/industry_pack_operation.schema.json +55 -0
  499. package/dist/schemas/intent_radar.output.json +275 -200
  500. package/dist/schemas/intent_radar.schema.json +124 -123
  501. package/dist/schemas/local_info_operation.output.json +1174 -657
  502. package/dist/schemas/local_info_operation.schema.json +119 -125
  503. package/dist/schemas/local_mark_operation.output.json +1239 -689
  504. package/dist/schemas/local_mark_operation.schema.json +91 -96
  505. package/dist/schemas/machineNode2file.output.json +63 -69
  506. package/dist/schemas/machineNode2file.schema.json +79 -81
  507. package/dist/schemas/messenger_operation.output.json +2722 -1528
  508. package/dist/schemas/messenger_operation.schema.json +1482 -1264
  509. package/dist/schemas/onchain_events.output.json +2590 -975
  510. package/dist/schemas/onchain_events.schema.json +117 -99
  511. package/dist/schemas/onchain_operations.output.json +3957 -2309
  512. package/dist/schemas/onchain_operations.schema.json +20799 -9285
  513. package/dist/schemas/onchain_operations_allocation.schema.json +172 -108
  514. package/dist/schemas/onchain_operations_arbitration.schema.json +233 -146
  515. package/dist/schemas/onchain_operations_contact.schema.json +129 -90
  516. package/dist/schemas/onchain_operations_demand.schema.json +170 -112
  517. package/dist/schemas/onchain_operations_gen_passport.schema.json +61 -646
  518. package/dist/schemas/onchain_operations_gen_proof.schema.json +40 -172
  519. package/dist/schemas/onchain_operations_guard.schema.json +3765 -294
  520. package/dist/schemas/onchain_operations_machine.schema.json +537 -164
  521. package/dist/schemas/onchain_operations_order.schema.json +126 -96
  522. package/dist/schemas/onchain_operations_payment.schema.json +82 -67
  523. package/dist/schemas/onchain_operations_permission.schema.json +331 -93
  524. package/dist/schemas/onchain_operations_personal.schema.json +636 -96
  525. package/dist/schemas/onchain_operations_progress.schema.json +125 -92
  526. package/dist/schemas/onchain_operations_proof.schema.json +76 -69
  527. package/dist/schemas/onchain_operations_repository.schema.json +636 -249
  528. package/dist/schemas/onchain_operations_reward.schema.json +218 -108
  529. package/dist/schemas/onchain_operations_service.schema.json +679 -221
  530. package/dist/schemas/onchain_operations_treasury.schema.json +401 -135
  531. package/dist/schemas/onchain_table_data.output.json +6018 -2430
  532. package/dist/schemas/onchain_table_data.schema.json +544 -430
  533. package/dist/schemas/persona_operation.output.json +1568 -265
  534. package/dist/schemas/persona_operation.schema.json +346 -202
  535. package/dist/schemas/project_operation.output.json +6957 -5147
  536. package/dist/schemas/project_operation.schema.json +1050 -1020
  537. package/dist/schemas/query_task_status.output.json +195 -99
  538. package/dist/schemas/query_task_status.schema.json +12 -18
  539. package/dist/schemas/query_toolkit.output.json +18870 -14566
  540. package/dist/schemas/query_toolkit.schema.json +614 -522
  541. package/dist/schemas/schema_query.output.json +127 -129
  542. package/dist/schemas/schema_query.schema.json +64 -69
  543. package/dist/schemas/trust_score.output.json +678 -587
  544. package/dist/schemas/trust_score.schema.json +289 -277
  545. package/dist/schemas/wip_file.output.json +116 -124
  546. package/dist/schemas/wip_file.schema.json +142 -143
  547. package/dist/schemas/workspace_operation.output.json +277 -0
  548. package/dist/schemas/workspace_operation.schema.json +45 -0
  549. package/dist/schemas/wowok_buildin_info.output.json +1693 -723
  550. package/dist/schemas/wowok_buildin_info.schema.json +576 -512
  551. package/dist/telemetry/index.js +1 -112
  552. package/dist/telemetry/redact.js +1 -23
  553. package/dist/telemetry/storage.js +1 -80
  554. package/dist/tools/handlers/bridge.d.ts +8 -1
  555. package/dist/tools/handlers/bridge.js +1 -1
  556. package/dist/tools/handlers/config.js +1 -74
  557. package/dist/tools/handlers/employee.d.ts +2 -0
  558. package/dist/tools/handlers/employee.js +1 -0
  559. package/dist/tools/handlers/evaluation.js +1 -123
  560. package/dist/tools/handlers/file-export.js +1 -90
  561. package/dist/tools/handlers/industry-pack.d.ts +2 -0
  562. package/dist/tools/handlers/industry-pack.js +1 -0
  563. package/dist/tools/handlers/intent-radar.js +1 -76
  564. package/dist/tools/handlers/local.js +1 -53
  565. package/dist/tools/handlers/messenger.js +1 -188
  566. package/dist/tools/handlers/onchain.js +1 -1180
  567. package/dist/tools/handlers/persona.js +1 -89
  568. package/dist/tools/handlers/project.js +1 -211
  569. package/dist/tools/handlers/query.js +1 -434
  570. package/dist/tools/handlers/schema-query.js +1 -176
  571. package/dist/tools/handlers/task-status.js +1 -26
  572. package/dist/tools/handlers/trust.js +1 -380
  573. package/dist/tools/handlers/wip.js +1 -90
  574. package/dist/tools/handlers/workspace.d.ts +2 -0
  575. package/dist/tools/handlers/workspace.js +1 -0
  576. package/dist/tools/index.d.ts +2 -1
  577. package/dist/tools/index.js +1 -1382
  578. package/dist/tools/retry.js +1 -85
  579. package/dist/tools/rules-hook.d.ts +1 -1
  580. package/dist/tools/rules-hook.js +1 -23
  581. package/dist/tools/shared.d.ts +1 -1
  582. package/dist/tools/shared.js +1 -130
  583. package/dist/tools/types.d.ts +2 -1
  584. package/dist/tools/types.js +1 -1
  585. package/dist/tools/upgrade-check.d.ts +19 -0
  586. package/dist/tools/upgrade-check.js +1 -0
  587. package/dist/tools/wip-deploy-assist.js +1 -306
  588. package/dist/tools/wrap.js +1 -500
  589. package/package.json +7 -6
  590. package/dist/knowledge/arbitration-trust.d.ts +0 -24
  591. package/dist/knowledge/arbitration-trust.js +0 -117
  592. package/dist/schema/call/bridge-handler.d.ts +0 -8
  593. package/dist/schema/call/bridge-handler.js +0 -265
  594. package/dist/schema/sync-layer4.d.ts +0 -21
  595. package/dist/schema/sync-layer4.js +0 -286
  596. package/dist/schema-query/index.js +0 -810
  597. /package/dist/{schema-query → schema-query-impl}/index.d.ts +0 -0
@@ -1,973 +1 @@
1
- import { GasTokenType } from "@wowok/wowok";
2
- const GAS_TOKENS = [
3
- {
4
- type: "0x2::wow::WOW",
5
- symbol: "WOW",
6
- decimals: 9,
7
- name: "Wowok Token",
8
- description: "Default platform gas token for all WoWok operations. 1 WOW = 10^9 MIST. Available on testnet and mainnet.",
9
- },
10
- ];
11
- const TESTNET_TOKENS = [];
12
- function buildMainnetTokensFromSDK() {
13
- try {
14
- const { MAINNET_BRIDGE_CONFIG } = require("@wowok/wowok");
15
- if (!MAINNET_BRIDGE_CONFIG?.tokens)
16
- return [];
17
- const seen = new Set();
18
- return MAINNET_BRIDGE_CONFIG.tokens
19
- .filter((t) => {
20
- if (seen.has(t.wowTypeTag))
21
- return false;
22
- seen.add(t.wowTypeTag);
23
- return true;
24
- })
25
- .map((t) => ({
26
- type: t.wowTypeTag,
27
- symbol: t.symbol,
28
- decimals: t.wowDecimals,
29
- name: `${t.symbol} (Bridge)`,
30
- description: t.description ?? `Bridge token on WOW mainnet. ${t.wowDecimals} decimals.`,
31
- }));
32
- }
33
- catch {
34
- return [];
35
- }
36
- }
37
- export const OFFICIAL_TOKEN_REGISTRY = {
38
- gas: GAS_TOKENS,
39
- testnet: TESTNET_TOKENS,
40
- mainnet: buildMainnetTokensFromSDK(),
41
- };
42
- export function getRegistryForNetwork(network) {
43
- return [
44
- ...OFFICIAL_TOKEN_REGISTRY.gas,
45
- ...(network === "testnet" ? OFFICIAL_TOKEN_REGISTRY.testnet : []),
46
- ...(network === "mainnet" ? OFFICIAL_TOKEN_REGISTRY.mainnet : []),
47
- ];
48
- }
49
- export function findInRegistryByType(tokenType, network) {
50
- const gasMatch = OFFICIAL_TOKEN_REGISTRY.gas.find((t) => t.type === tokenType);
51
- if (gasMatch)
52
- return gasMatch;
53
- const netTokens = getRegistryForNetwork(network);
54
- return netTokens.find((t) => t.type === tokenType);
55
- }
56
- export function findInRegistryBySymbol(symbol, network) {
57
- const lower = symbol.toLowerCase();
58
- const gasMatches = OFFICIAL_TOKEN_REGISTRY.gas.filter((t) => t.symbol.toLowerCase() === lower);
59
- const netTokens = getRegistryForNetwork(network);
60
- const netMatches = netTokens.filter((t) => t.symbol.toLowerCase() === lower && !gasMatches.some((g) => g.type === t.type));
61
- return [...gasMatches, ...netMatches];
62
- }
63
- export async function resolveTokenByType(tokenType, network) {
64
- const registryEntry = findInRegistryByType(tokenType, network);
65
- if (registryEntry) {
66
- return {
67
- type: registryEntry.type,
68
- symbol: registryEntry.symbol,
69
- decimals: registryEntry.decimals,
70
- name: registryEntry.name,
71
- source: "registry",
72
- verified: true,
73
- };
74
- }
75
- const memKey = `${cacheNet(network)}::${tokenType}`;
76
- const memHit = RESOLUTION_CACHE.get(memKey);
77
- if (memHit)
78
- return memHit;
79
- try {
80
- const { TokenInfo } = await import("@wowok/wowok");
81
- const tokenInfo = TokenInfo.Instance();
82
- const fetched = await tokenInfo.fetch(tokenType, undefined, network);
83
- if (fetched) {
84
- const resolution = {
85
- type: fetched.type,
86
- symbol: fetched.symbol ?? "",
87
- decimals: fetched.decimals ?? 0,
88
- name: fetched.name ?? "",
89
- source: "cache",
90
- verified: false,
91
- };
92
- RESOLUTION_CACHE.set(memKey, resolution);
93
- return resolution;
94
- }
95
- }
96
- catch {
97
- }
98
- return undefined;
99
- }
100
- export async function resolveTokensBySymbol(symbol, network, preferredType) {
101
- const results = [];
102
- const registryMatches = findInRegistryBySymbol(symbol, network);
103
- for (const entry of registryMatches) {
104
- results.push({
105
- type: entry.type,
106
- symbol: entry.symbol,
107
- decimals: entry.decimals,
108
- name: entry.name,
109
- source: "registry",
110
- verified: true,
111
- });
112
- }
113
- try {
114
- const { query_local_token_list } = await import("@wowok/wowok");
115
- const cached = await query_local_token_list({ symbol });
116
- for (const token of cached) {
117
- if (results.some((r) => r.type === token.type))
118
- continue;
119
- results.push({
120
- type: token.type,
121
- symbol: token.symbol ?? "",
122
- decimals: token.decimals ?? 0,
123
- name: token.name ?? "",
124
- source: "cache",
125
- verified: false,
126
- });
127
- }
128
- }
129
- catch {
130
- }
131
- if (preferredType) {
132
- results.sort((a, b) => {
133
- if (a.type === preferredType)
134
- return -1;
135
- if (b.type === preferredType)
136
- return 1;
137
- if (a.verified && !b.verified)
138
- return -1;
139
- if (!a.verified && b.verified)
140
- return 1;
141
- return 0;
142
- });
143
- }
144
- return results;
145
- }
146
- const AMOUNT_WITH_SYMBOL = /^(\d+(?:\.\d+)?)\s*([A-Za-z][A-Za-z0-9]*)$/;
147
- export function isAmountWithSymbol(value) {
148
- if (typeof value !== "string")
149
- return false;
150
- const match = value.match(AMOUNT_WITH_SYMBOL);
151
- if (!match)
152
- return false;
153
- const symbol = match[2];
154
- return symbol.length >= 2 && symbol.length <= 10;
155
- }
156
- export async function parseAmount(amount, tokenType, network) {
157
- const originalInput = amount;
158
- const resolution = await resolveTokenByType(tokenType, network);
159
- const precisionKnown = resolution !== undefined;
160
- const decimals = resolution?.decimals ?? 9;
161
- const symbol = resolution?.symbol ?? "";
162
- const source = resolution?.source ?? "onchain";
163
- const verified = resolution?.verified ?? false;
164
- if (typeof amount === "string") {
165
- const match = amount.match(AMOUNT_WITH_SYMBOL);
166
- if (match) {
167
- if (!precisionKnown) {
168
- throw new Error(`TOKEN PRECISION UNKNOWN for ${tokenType} — REFUSING to convert "${amount}". ` +
169
- `The token's decimals could not be resolved from the official registry, local cache, ` +
170
- `or on-chain metadata, and guessing decimals would forge a wrong on-chain value. ` +
171
- `Retry (the on-chain lookup may have been transient), or pass a pure numeric value ` +
172
- `in smallest units only if you are certain of the raw u64 amount. ` +
173
- knownTokenSuggestions(network));
174
- }
175
- const numericPart = parseFloat(match[1]);
176
- const symbolPart = match[2];
177
- if (symbol && symbolPart.toLowerCase() !== symbol.toLowerCase()) {
178
- throw new Error(`Amount symbol "${symbolPart}" does not match the expected token symbol "${symbol}" ` +
179
- `(type: ${tokenType}). Either use the correct symbol or pass a pure numeric value ` +
180
- `in smallest units (e.g., ${(numericPart * Math.pow(10, decimals)).toFixed(0)}).`);
181
- }
182
- const smallestUnit = displayToSmallestUnit(numericPart, decimals);
183
- return {
184
- smallestUnit,
185
- displayAmount: `${numericPart} ${symbolPart}`,
186
- originalInput,
187
- tokenType,
188
- tokenSymbol: symbol || symbolPart,
189
- decimals,
190
- converted: true,
191
- source,
192
- verified,
193
- precision_known: true,
194
- };
195
- }
196
- }
197
- let smallestUnit;
198
- try {
199
- smallestUnit = BigInt(amount);
200
- }
201
- catch {
202
- throw new Error(`Invalid amount: "${amount}". Expected a number, a numeric string (smallest unit), ` +
203
- `or a display-format string like "2.5WOW" (matching the token's symbol).`);
204
- }
205
- const displayValue = precisionKnown
206
- ? smallestToDisplay(smallestUnit, decimals)
207
- : `${smallestUnit.toString()} raw smallest units (token precision unknown)`;
208
- return {
209
- smallestUnit,
210
- displayAmount: precisionKnown && symbol ? `${displayValue} ${symbol}` : displayValue,
211
- originalInput,
212
- tokenType,
213
- tokenSymbol: symbol,
214
- decimals,
215
- converted: false,
216
- source,
217
- verified,
218
- precision_known: precisionKnown,
219
- };
220
- }
221
- function displayToSmallestUnit(display, decimals) {
222
- const str = display.toString();
223
- const [wholePart, fracPart = ""] = str.split(".");
224
- const paddedFrac = fracPart.padEnd(decimals, "0").slice(0, decimals);
225
- const combined = wholePart + paddedFrac;
226
- return BigInt(combined || "0");
227
- }
228
- export function smallestToDisplay(value, decimals) {
229
- const sign = value < 0n ? "-" : "";
230
- const abs = value < 0n ? -value : value;
231
- const divisor = BigInt(10) ** BigInt(decimals);
232
- const whole = abs / divisor;
233
- const frac = abs % divisor;
234
- if (frac === 0n)
235
- return `${sign}${whole.toString()}`;
236
- const fracStr = frac.toString().padStart(decimals, "0").replace(/0+$/, "");
237
- return `${sign}${whole.toString()}.${fracStr}`;
238
- }
239
- export function displayStringToSmallest(display, decimals) {
240
- const trimmed = display.trim();
241
- if (!/^\d+(\.\d+)?$/.test(trimmed)) {
242
- throw new Error(`Invalid display amount: "${display}". Expected a non-negative decimal number like "2.5".`);
243
- }
244
- const [whole, frac = ""] = trimmed.split(".");
245
- if (frac.length > decimals) {
246
- throw new Error(`Too many decimal places: "${display}" has ${frac.length}, but this token supports at most ${decimals} (decimals: ${decimals}).`);
247
- }
248
- const paddedFrac = frac.padEnd(decimals, "0");
249
- return BigInt(whole + paddedFrac);
250
- }
251
- export function generateFundConfirmation(fields, ambiguities = []) {
252
- const hasAmbiguity = ambiguities.length > 0;
253
- const parts = [
254
- "MONEY TRANSACTION CONFIRMATION REQUIRED",
255
- "",
256
- ];
257
- for (const field of fields) {
258
- const verifiedTag = field.verified ? " [VERIFIED]" : " [UNVERIFIED]";
259
- const sourceTag = ` (source: ${field.source})`;
260
- parts.push(` • ${field.context}: ${field.displayAmount}${verifiedTag}${sourceTag}`);
261
- if (field.converted) {
262
- parts.push(` (converted from display format to smallest unit)`);
263
- }
264
- }
265
- if (hasAmbiguity) {
266
- parts.push("", "AMBIGUITY WARNING — multiple tokens share the same symbol:");
267
- for (const amb of ambiguities) {
268
- parts.push(` Symbol "${amb.symbol}" matches:`);
269
- for (const c of amb.candidates) {
270
- const vTag = c.verified ? " [VERIFIED]" : " [UNVERIFIED]";
271
- parts.push(` - type: ${c.type}, decimals: ${c.decimals}${vTag} (source: ${c.source})`);
272
- }
273
- parts.push(` → Specify the full type string in type_parameter to disambiguate.`);
274
- }
275
- }
276
- parts.push("", "This operation involves money. Please confirm before proceeding.");
277
- return {
278
- requiresConfirmation: true,
279
- reason: hasAmbiguity
280
- ? "Money transaction with ambiguous token symbol — user must specify full type"
281
- : "Money transaction requires user confirmation",
282
- fields,
283
- ambiguities,
284
- message: parts.join("\n"),
285
- };
286
- }
287
- function extractTokenType(data, operationType, objectTokenType) {
288
- if (data?.object && typeof data.object === "object" && data.object.type_parameter) {
289
- return data.object.type_parameter;
290
- }
291
- if (operationType === "payment" && data?.type_parameter) {
292
- return data.type_parameter;
293
- }
294
- if (objectTokenType) {
295
- return objectTokenType;
296
- }
297
- return GasTokenType;
298
- }
299
- const MONETARY_FIELDS = {
300
- service: [
301
- { path: "sales.sales", context: "Service sale price", isArray: true, amountField: "price" },
302
- { path: "compensation_fund_add.balance", context: "Service compensation fund deposit" },
303
- { path: "order_new.buy.total_pay.balance", context: "Order payment amount" },
304
- { path: "discount.discount_value", context: "Discount value" },
305
- ],
306
- arbitration: [
307
- { path: "dispute.fee.balance", context: "Arbitration dispute fee" },
308
- { path: "fee", context: "Arbitration fee" },
309
- ],
310
- reward: [
311
- { path: "coin_add.balance", context: "Reward coin add" },
312
- ],
313
- treasury: [
314
- { path: "deposit.coin.balance", context: "Treasury deposit amount" },
315
- { path: "withdraw.amount.fixed", context: "Treasury withdrawal amount" },
316
- ],
317
- payment: [
318
- { path: "revenue", context: "Payment amount", isArray: true, amountField: "amount.balance" },
319
- ],
320
- allocation: [
321
- { path: "coin.balance", context: "Allocation funding amount" },
322
- ],
323
- };
324
- function getNestedValue(obj, path) {
325
- const parts = path.split(".");
326
- let current = obj;
327
- for (const part of parts) {
328
- if (current == null)
329
- return undefined;
330
- current = current[part];
331
- }
332
- return current;
333
- }
334
- export async function processFundOperation(data, operationType, network, options) {
335
- const result = {
336
- convertedData: data,
337
- warnings: [],
338
- errors: [],
339
- confirmation: null,
340
- };
341
- const fields = MONETARY_FIELDS[operationType];
342
- if (!fields) {
343
- return result;
344
- }
345
- const tokenType = extractTokenType(data, operationType, options?.objectTokenType);
346
- const confirmationFields = [];
347
- const ambiguities = [];
348
- const seenSymbols = new Map();
349
- for (const fieldDesc of fields) {
350
- const isArr = fieldDesc.isArray === true;
351
- const amountField = fieldDesc.amountField;
352
- if (isArr && amountField) {
353
- const arr = getNestedValue(data, fieldDesc.path);
354
- if (Array.isArray(arr)) {
355
- for (let i = 0; i < arr.length; i++) {
356
- const item = arr[i];
357
- const parts = amountField.split(".");
358
- let parentObj = item;
359
- for (let j = 0; j < parts.length - 1; j++) {
360
- parentObj = parentObj?.[parts[j]];
361
- if (parentObj == null)
362
- break;
363
- }
364
- const finalKey = parts[parts.length - 1];
365
- if (parentObj && parentObj[finalKey] != null) {
366
- const path = `${fieldDesc.path}[${i}].${amountField}`;
367
- await processSingleField(parentObj, finalKey, path, fieldDesc.context, tokenType, network, result, confirmationFields, ambiguities, seenSymbols);
368
- }
369
- }
370
- }
371
- }
372
- else {
373
- const lastDot = fieldDesc.path.lastIndexOf(".");
374
- const parentPath = lastDot >= 0 ? fieldDesc.path.slice(0, lastDot) : "";
375
- const finalKey = lastDot >= 0 ? fieldDesc.path.slice(lastDot + 1) : fieldDesc.path;
376
- const parentObj = parentPath ? getNestedValue(data, parentPath) : data;
377
- if (parentObj && parentObj[finalKey] != null) {
378
- await processSingleField(parentObj, finalKey, fieldDesc.path, fieldDesc.context, tokenType, network, result, confirmationFields, ambiguities, seenSymbols);
379
- }
380
- }
381
- }
382
- if (confirmationFields.length > 0) {
383
- result.confirmation = generateFundConfirmation(confirmationFields, ambiguities);
384
- const totalAmounts = confirmationFields.length;
385
- const hasUnverified = confirmationFields.some((f) => !f.verified);
386
- const hasAmbiguity = ambiguities.length > 0;
387
- if (hasAmbiguity) {
388
- result.warnings.push(`AMBIGUOUS TOKEN: ${ambiguities.length} token symbol(s) have multiple candidates. ` +
389
- `User must specify full type string in type_parameter to disambiguate. ` +
390
- `See confirmation message for details.`);
391
- }
392
- if (hasUnverified) {
393
- result.warnings.push(`UNVERIFIED TOKEN: some monetary fields use tokens not in the official registry. ` +
394
- `Precision was resolved from cache/on-chain. Verify the token type before proceeding.`);
395
- }
396
- result.warnings.push(`MONEY CONFIRMATION: ${totalAmounts} monetary field(s) require user confirmation. ` +
397
- `Token type: ${tokenType}. Use env.confirmed=true after user consent.`);
398
- }
399
- return result;
400
- }
401
- async function processSingleField(parentObj, fieldKey, fieldPath, context, tokenType, network, result, confirmationFields, ambiguities, seenSymbols) {
402
- const value = parentObj[fieldKey];
403
- if (value == null)
404
- return;
405
- try {
406
- const parsed = await parseAmount(value, tokenType, network);
407
- if (!parsed.precision_known) {
408
- result.errors.push(`FUND INPUT BLOCKED at ${fieldPath}: token precision unavailable for ${tokenType}. ` +
409
- `The raw value ${JSON.stringify(value)} was NOT converted or confirmed. ` +
410
- `Retry after the token info resolves (registry → cache → on-chain), ` +
411
- `or use a known token. ${knownTokenSuggestions(network)}`);
412
- return;
413
- }
414
- if (parsed.converted) {
415
- parentObj[fieldKey] = parsed.smallestUnit.toString();
416
- }
417
- confirmationFields.push({
418
- path: fieldPath,
419
- displayAmount: parsed.displayAmount,
420
- tokenType: parsed.tokenType,
421
- tokenSymbol: parsed.tokenSymbol,
422
- verified: parsed.verified,
423
- source: parsed.source,
424
- converted: parsed.converted,
425
- context,
426
- });
427
- if (parsed.tokenSymbol && parsed.source !== "registry") {
428
- const symbolKey = parsed.tokenSymbol.toLowerCase();
429
- let candidates = seenSymbols.get(symbolKey);
430
- if (!candidates) {
431
- const allMatches = await resolveTokensBySymbol(parsed.tokenSymbol, network, tokenType);
432
- if (allMatches.length > 1) {
433
- candidates = allMatches;
434
- seenSymbols.set(symbolKey, candidates);
435
- ambiguities.push({
436
- symbol: parsed.tokenSymbol,
437
- candidates: candidates.map((c) => ({
438
- type: c.type,
439
- decimals: c.decimals,
440
- source: c.source,
441
- verified: c.verified,
442
- })),
443
- });
444
- }
445
- }
446
- }
447
- }
448
- catch (err) {
449
- result.errors.push(`FUND INPUT BLOCKED at ${fieldPath}: ${err.message}`);
450
- }
451
- }
452
- export function generateSkillsHint(confirmation) {
453
- if (!confirmation || !confirmation.requiresConfirmation)
454
- return null;
455
- const hasAmbiguity = confirmation.ambiguities.length > 0;
456
- if (hasAmbiguity) {
457
- return ("SKILLS HINT: This money transaction has ambiguous token symbols. " +
458
- "If the wowok-safety skill is installed, it can guide the user through " +
459
- "interactive disambiguation. Otherwise, the MCP fund layer has already " +
460
- "listed all candidates in the confirmation message — ask the user to " +
461
- "specify the full token type string in type_parameter.");
462
- }
463
- return ("SKILLS HINT: This money transaction requires user confirmation. " +
464
- "If the wowok-safety skill is installed, it provides R1-R10 confirmation " +
465
- "dialogue scripts. Otherwise, present the confirmation message to the user " +
466
- "and proceed only after explicit consent (env.confirmed=true).");
467
- }
468
- export async function formatChainValue(raw, tokenType, network) {
469
- let rawStr;
470
- try {
471
- rawStr = BigInt(raw).toString();
472
- }
473
- catch {
474
- rawStr = String(raw);
475
- }
476
- const resolution = await resolveTokenByType(tokenType, network);
477
- if (resolution && typeof resolution.decimals === "number") {
478
- let display = rawStr;
479
- try {
480
- display = smallestToDisplay(BigInt(rawStr), resolution.decimals);
481
- }
482
- catch {
483
- }
484
- const symbol = resolution.symbol || "";
485
- const text = symbol
486
- ? `${display} ${symbol} (decimals: ${resolution.decimals}; 1 ${symbol} = 10^${resolution.decimals} raw units; raw: ${rawStr})`
487
- : `${display} (decimals: ${resolution.decimals}; 1 unit = 10^${resolution.decimals} raw units; raw: ${rawStr})`;
488
- return {
489
- raw: rawStr,
490
- display,
491
- symbol: symbol || undefined,
492
- decimals: resolution.decimals,
493
- token_type: tokenType,
494
- precision_known: true,
495
- text,
496
- };
497
- }
498
- return {
499
- raw: rawStr,
500
- display: rawStr,
501
- token_type: tokenType,
502
- precision_known: false,
503
- text: `${rawStr} raw smallest units (token precision unavailable for ${tokenType} — ` +
504
- `cannot convert to unit value. Conversion rule once decimals N is known: ` +
505
- `unit = raw / 10^N. Re-run the query to retry the on-chain precision lookup.)`,
506
- };
507
- }
508
- export function registryDisplayHint(tokenType, network) {
509
- if (!tokenType)
510
- return undefined;
511
- const entry = findInRegistryByType(tokenType, network);
512
- if (!entry)
513
- return undefined;
514
- return { decimals: entry.decimals, symbol: entry.symbol };
515
- }
516
- const RESOLUTION_CACHE = new Map();
517
- const OBJECT_TYPE_CACHE = new Map();
518
- function cacheNet(network) {
519
- return network ?? "default";
520
- }
521
- function isCacheableObjectRef(ref) {
522
- return /^0x[0-9a-fA-F]{20,}$/.test(ref);
523
- }
524
- export function clearFundResolutionCaches() {
525
- RESOLUTION_CACHE.clear();
526
- OBJECT_TYPE_CACHE.clear();
527
- }
528
- export function knownTokenSuggestions(network) {
529
- const tokens = getRegistryForNetwork(network)
530
- .map(t => `${t.symbol} (${t.type}, ${t.decimals} decimals)`);
531
- return tokens.length > 0
532
- ? `Known tokens: ${tokens.join("; ")}.`
533
- : "No officially-known tokens on this network.";
534
- }
535
- export function formatAmountText(raw, decimals, symbol) {
536
- let rawStr;
537
- try {
538
- rawStr = BigInt(raw).toString();
539
- }
540
- catch {
541
- rawStr = String(raw);
542
- }
543
- if (decimals === undefined) {
544
- return `${rawStr} smallest units (token precision unknown)`;
545
- }
546
- let display = rawStr;
547
- try {
548
- display = smallestToDisplay(BigInt(rawStr), decimals);
549
- }
550
- catch {
551
- }
552
- return symbol
553
- ? `${display} ${symbol} (decimals: ${decimals}; raw: ${rawStr})`
554
- : `${display} (decimals: ${decimals}; raw: ${rawStr})`;
555
- }
556
- export async function convertTokenValue(tokenType, value, network) {
557
- const resolution = await resolveTokenByType(tokenType, network);
558
- const decimals = resolution?.decimals;
559
- const symbol = resolution?.symbol || undefined;
560
- const base = { token_type: tokenType, symbol, decimals };
561
- if (value.raw !== undefined) {
562
- let rawStr;
563
- try {
564
- rawStr = BigInt(value.raw).toString();
565
- }
566
- catch {
567
- return {
568
- ...base,
569
- precision_known: decimals !== undefined,
570
- direction: "raw_to_unit",
571
- input: String(value.raw),
572
- output: "",
573
- error: `Invalid raw value: "${String(value.raw)}" — expected a non-negative integer (u64 smallest units).`,
574
- text: `Cannot convert: invalid raw value "${String(value.raw)}".`,
575
- };
576
- }
577
- if (decimals === undefined) {
578
- return {
579
- ...base,
580
- precision_known: false,
581
- direction: "raw_to_unit",
582
- input: rawStr,
583
- output: rawStr,
584
- text: `${rawStr} raw smallest units (token precision unavailable for ${tokenType} — ` +
585
- `cannot convert to unit value. Rule once decimals N is known: unit = raw / 10^N.)`,
586
- };
587
- }
588
- let unit = rawStr;
589
- try {
590
- unit = smallestToDisplay(BigInt(rawStr), decimals);
591
- }
592
- catch { }
593
- return {
594
- ...base,
595
- precision_known: true,
596
- direction: "raw_to_unit",
597
- input: rawStr,
598
- output: unit,
599
- text: symbol
600
- ? `${rawStr} raw = ${unit} ${symbol} (decimals: ${decimals}; 1 ${symbol} = 10^${decimals} raw units)`
601
- : `${rawStr} raw = ${unit} (decimals: ${decimals}; 1 unit = 10^${decimals} raw units)`,
602
- };
603
- }
604
- const unitStr = String(value.unit ?? "").trim();
605
- if (decimals === undefined) {
606
- return {
607
- ...base,
608
- precision_known: false,
609
- direction: "unit_to_raw",
610
- input: unitStr,
611
- output: "",
612
- error: `Token precision unavailable for ${tokenType} — REFUSING to convert "${unitStr}" to raw units. ` +
613
- `Guessing decimals would forge a wrong on-chain value. Retry after the precision lookup succeeds, ` +
614
- `or check the token's coin metadata.`,
615
- text: `Cannot convert "${unitStr}" to raw units: token precision unknown for ${tokenType}.`,
616
- };
617
- }
618
- try {
619
- const raw = displayStringToSmallest(unitStr, decimals);
620
- return {
621
- ...base,
622
- precision_known: true,
623
- direction: "unit_to_raw",
624
- input: unitStr,
625
- output: raw.toString(),
626
- text: symbol
627
- ? `${unitStr} ${symbol} = ${raw.toString()} raw smallest units (decimals: ${decimals}; 1 ${symbol} = 10^${decimals} raw units)`
628
- : `${unitStr} = ${raw.toString()} raw smallest units (decimals: ${decimals}; 1 unit = 10^${decimals} raw units)`,
629
- };
630
- }
631
- catch (e) {
632
- const msg = e instanceof Error ? e.message : String(e);
633
- return {
634
- ...base,
635
- precision_known: true,
636
- direction: "unit_to_raw",
637
- input: unitStr,
638
- output: "",
639
- error: msg,
640
- text: `Cannot convert "${unitStr}" to raw units: ${msg}`,
641
- };
642
- }
643
- }
644
- export const TOKEN_GENERIC_OBJECT_TYPES = [
645
- "Treasury",
646
- "Allocation",
647
- "Arbitration",
648
- "Arb",
649
- "Payment",
650
- "Reward",
651
- "Service",
652
- ];
653
- export function extractGenericTokenType(typeRaw) {
654
- if (!typeRaw || typeof typeRaw !== "string")
655
- return undefined;
656
- const lt = typeRaw.indexOf("<");
657
- if (lt < 0)
658
- return undefined;
659
- let depth = 0;
660
- for (let i = lt; i < typeRaw.length; i++) {
661
- const ch = typeRaw[i];
662
- if (ch === "<")
663
- depth++;
664
- else if (ch === ">") {
665
- depth--;
666
- if (depth === 0) {
667
- return typeRaw.slice(lt + 1, i).trim() || undefined;
668
- }
669
- }
670
- }
671
- return undefined;
672
- }
673
- export async function resolveObjectTokenType(objectRef, network) {
674
- if (!objectRef || typeof objectRef !== "string")
675
- return undefined;
676
- const cacheable = isCacheableObjectRef(objectRef);
677
- const memKey = `${cacheNet(network)}::${objectRef}`;
678
- if (cacheable) {
679
- const memHit = OBJECT_TYPE_CACHE.get(memKey);
680
- if (memHit)
681
- return memHit;
682
- }
683
- try {
684
- const { query_objects } = await import("@wowok/wowok");
685
- const res = await query_objects({ objects: [objectRef], network });
686
- const obj = res?.objects?.[0];
687
- if (!obj)
688
- return undefined;
689
- const typeRaw = obj.type_raw ?? obj.content_raw?.type ?? undefined;
690
- const resolution = {
691
- tokenType: extractGenericTokenType(typeRaw),
692
- objectType: obj.type,
693
- typeRaw,
694
- };
695
- if (cacheable)
696
- OBJECT_TYPE_CACHE.set(memKey, resolution);
697
- return resolution;
698
- }
699
- catch {
700
- return undefined;
701
- }
702
- }
703
- export async function resolveOperationObjectTokenType(data, operationType, network) {
704
- if (!data)
705
- return undefined;
706
- if (data.object && typeof data.object === "object" && typeof data.object.type_parameter === "string") {
707
- return data.object.type_parameter;
708
- }
709
- if (operationType === "payment" && typeof data.type_parameter === "string") {
710
- return data.type_parameter;
711
- }
712
- if (typeof data.object === "string" && data.object.length > 0) {
713
- const resolved = await resolveObjectTokenType(data.object, network);
714
- return resolved?.tokenType;
715
- }
716
- return undefined;
717
- }
718
- const RECEIVE_TOKEN_FIELDS = {
719
- treasury: ["receive"],
720
- allocation: ["received_coins"],
721
- reward: ["receive"],
722
- service: ["compensation_fund_receive"],
723
- arbitration: ["receive"],
724
- };
725
- const COIN_PARAM_FIELDS = {
726
- treasury: ["deposit.coin"],
727
- allocation: ["coin"],
728
- reward: ["coin_add"],
729
- arbitration: ["dispute.fee"],
730
- service: ["compensation_fund_add", "order_new.buy.total_pay"],
731
- };
732
- export async function validateOperationTokenMatch(data, operationType, objectTokenType, network) {
733
- const result = { errors: [], warnings: [], objectTokenType };
734
- if (!data || !objectTokenType)
735
- return result;
736
- const objectLabel = typeof data.object === "string" ? data.object : "the target object";
737
- const mismatchMsg = (provided, context) => `TOKEN TYPE MISMATCH (${context}): ${objectLabel} only accepts ${objectTokenType} ` +
738
- `(its generic token type is fixed and immutable), but ${provided} was provided. ` +
739
- `Use ${objectTokenType} for this operation, or target a different object.`;
740
- for (const field of RECEIVE_TOKEN_FIELDS[operationType] ?? []) {
741
- const v = data[field];
742
- if (v && typeof v === "object" && typeof v.token_type === "string" && v.token_type !== objectTokenType) {
743
- result.errors.push(mismatchMsg(v.token_type, `field '${field}.token_type'`));
744
- }
745
- }
746
- for (const path of COIN_PARAM_FIELDS[operationType] ?? []) {
747
- const coinParam = getNestedValue(data, path);
748
- if (coinParam && typeof coinParam === "object" && typeof coinParam.coin === "string") {
749
- const coinRef = coinParam.coin;
750
- const resolved = await resolveObjectTokenType(coinRef, network);
751
- if (resolved?.tokenType) {
752
- if (resolved.tokenType !== objectTokenType) {
753
- result.errors.push(mismatchMsg(resolved.tokenType, `coin '${coinRef}' at '${path}'`));
754
- }
755
- }
756
- else if (resolved === undefined) {
757
- result.warnings.push(`Could not resolve coin object '${coinRef}' (${path}) to verify its token type ` +
758
- `matches ${objectTokenType}. The on-chain type check will reject a mismatch at execution.`);
759
- }
760
- }
761
- }
762
- return result;
763
- }
764
- const OBJECT_MONEY_FIELDS = {
765
- Treasury: ["balance", "inflow", "outflow"],
766
- Allocation: ["balance"],
767
- Arbitration: ["fee", "balance"],
768
- Reward: ["balance"],
769
- Service: ["compensation_fund"],
770
- Payment: ["amount"],
771
- Arb: ["fee"],
772
- };
773
- export async function annotateObjectMonetaryFields(obj, network) {
774
- if (!obj || typeof obj !== "object" || typeof obj.type !== "string")
775
- return;
776
- let tokenType = extractGenericTokenType(obj.type_raw);
777
- const displays = {};
778
- const annotate = async (path, raw, tt) => {
779
- if (raw === null || raw === undefined)
780
- return;
781
- if (typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "bigint")
782
- return;
783
- displays[path] = tt
784
- ? await formatChainValue(raw, tt, network)
785
- : {
786
- raw: String(raw),
787
- display: String(raw),
788
- token_type: "",
789
- precision_known: false,
790
- text: `${String(raw)} raw smallest units (token type could not be determined for this field — ` +
791
- `no conversion applied. Showing the true raw value; re-run the query to retry resolution.)`,
792
- };
793
- };
794
- if (!tokenType && (obj.type === "Order" || obj.type === "Discount") && typeof obj.service === "string") {
795
- try {
796
- const svc = await resolveObjectTokenType(obj.service, network);
797
- tokenType = svc?.tokenType;
798
- }
799
- catch {
800
- }
801
- }
802
- for (const field of OBJECT_MONEY_FIELDS[obj.type] ?? []) {
803
- await annotate(field, obj[field], tokenType);
804
- }
805
- switch (obj.type) {
806
- case "Service":
807
- if (Array.isArray(obj.sales)) {
808
- for (let i = 0; i < obj.sales.length; i++) {
809
- await annotate(`sales[${i}].price`, obj.sales[i]?.price, tokenType);
810
- }
811
- }
812
- break;
813
- case "Order":
814
- await annotate("amount", obj.amount, tokenType);
815
- if (Array.isArray(obj.items)) {
816
- for (let i = 0; i < obj.items.length; i++) {
817
- await annotate(`items[${i}].price`, obj.items[i]?.price, tokenType);
818
- }
819
- }
820
- break;
821
- case "Payment":
822
- if (Array.isArray(obj.record)) {
823
- for (let i = 0; i < obj.record.length; i++) {
824
- await annotate(`record[${i}].amount`, obj.record[i]?.amount, tokenType);
825
- }
826
- }
827
- break;
828
- case "Reward":
829
- if (Array.isArray(obj.guards)) {
830
- for (let i = 0; i < obj.guards.length; i++) {
831
- const amount = obj.guards[i]?.amount;
832
- if (amount && typeof amount === "object" && amount.type === 1) {
833
- await annotate(`guards[${i}].amount.value`, amount.value, tokenType);
834
- }
835
- }
836
- }
837
- break;
838
- case "Arb":
839
- await annotate("indemnity.amount", obj.indemnity?.amount, tokenType);
840
- break;
841
- case "Discount":
842
- await annotate("benchmark", obj.benchmark, tokenType);
843
- if (obj.discount_type === 1) {
844
- await annotate("off", obj.off, tokenType);
845
- }
846
- break;
847
- }
848
- if (Object.keys(displays).length > 0) {
849
- obj._money_display = displays;
850
- }
851
- }
852
- const TABLE_ITEM_MONEY_FIELDS = {
853
- TableItem_TreasuryHistory: ["amount"],
854
- TableItem_RewardRecord: ["total"],
855
- };
856
- export async function resolveParentObjectTokenType(parentRef, network) {
857
- const res = await resolveObjectTokenType(parentRef, network);
858
- if (!res)
859
- return undefined;
860
- if (res.objectType && TOKEN_GENERIC_OBJECT_TYPES.includes(res.objectType)) {
861
- return res.tokenType;
862
- }
863
- return undefined;
864
- }
865
- export async function annotateTableItemMonetaryFields(item, parentTokenType, network) {
866
- if (!item || typeof item !== "object" || typeof item.type !== "string")
867
- return;
868
- const displays = {};
869
- const annotate = async (path, raw) => {
870
- if (raw === null || raw === undefined)
871
- return;
872
- if (typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "bigint")
873
- return;
874
- displays[path] = parentTokenType
875
- ? await formatChainValue(raw, parentTokenType, network)
876
- : {
877
- raw: String(raw),
878
- display: String(raw),
879
- token_type: "",
880
- precision_known: false,
881
- text: `${String(raw)} raw smallest units (parent object token type could not ` +
882
- `be resolved — no conversion applied)`,
883
- };
884
- };
885
- for (const field of TABLE_ITEM_MONEY_FIELDS[item.type] ?? []) {
886
- await annotate(field, item[field]);
887
- }
888
- if (item.type === "TableItem_RewardRecord" && Array.isArray(item.record)) {
889
- for (let i = 0; i < item.record.length; i++) {
890
- await annotate(`record[${i}].amount`, item.record[i]?.amount);
891
- }
892
- }
893
- if (Object.keys(displays).length > 0) {
894
- item._money_display = displays;
895
- }
896
- }
897
- export async function annotateEventMonetaryFields(event, network) {
898
- if (!event || typeof event !== "object")
899
- return;
900
- const isNewOrder = event.type === "NewOrderEvent" ||
901
- (typeof event.type === "string" && event.type.includes("::order::NewOrderEvent"));
902
- if (!isNewOrder)
903
- return;
904
- const pj = event.parsedJson_raw ?? {};
905
- const raw = event.amount ?? pj.amount;
906
- if (raw === null || raw === undefined)
907
- return;
908
- if (typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "bigint")
909
- return;
910
- let tokenType;
911
- const service = event.service ?? pj.service;
912
- if (typeof service === "string" && service) {
913
- try {
914
- tokenType = (await resolveObjectTokenType(service, network))?.tokenType;
915
- }
916
- catch {
917
- }
918
- }
919
- event._money_display = {
920
- amount: tokenType
921
- ? await formatChainValue(raw, tokenType, network)
922
- : {
923
- raw: String(raw),
924
- display: String(raw),
925
- token_type: "",
926
- precision_known: false,
927
- text: `${String(raw)} raw smallest units (order's Service token type could not be ` +
928
- `resolved — showing the true raw value; re-run the query to retry.)`,
929
- },
930
- };
931
- }
932
- export async function annotateEventsMonetaryFields(events, network) {
933
- if (!Array.isArray(events))
934
- return;
935
- for (const ev of events) {
936
- try {
937
- await annotateEventMonetaryFields(ev, network);
938
- }
939
- catch {
940
- }
941
- }
942
- }
943
- export async function annotateBalanceChanges(changes, network) {
944
- if (!Array.isArray(changes))
945
- return;
946
- for (const change of changes) {
947
- try {
948
- const coinType = change?.coin_type;
949
- const raw = change?.amount;
950
- if (typeof coinType !== "string" || !coinType)
951
- continue;
952
- if (typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "bigint")
953
- continue;
954
- change._money_display = {
955
- amount: await formatChainValue(raw, coinType, network),
956
- };
957
- }
958
- catch {
959
- }
960
- }
961
- }
962
- export async function prepareFundOperation(data, operationType, network) {
963
- const objectTokenType = await resolveOperationObjectTokenType(data, operationType, network);
964
- const match = await validateOperationTokenMatch(data, operationType, objectTokenType, network);
965
- const processed = await processFundOperation(data, operationType, network, { objectTokenType });
966
- return {
967
- ...processed,
968
- warnings: [...match.warnings, ...processed.warnings],
969
- matchErrors: match.errors,
970
- blockingErrors: [...match.errors, ...processed.errors],
971
- objectTokenType,
972
- };
973
- }
1
+ import{GasTokenType}from'@wowok/wowok';const GAS_TOKENS=[{'type':'0x2::wow::WOW','symbol':'WOW','decimals':0x9,'name':'Wowok\x20Token','description':'Default\x20platform\x20gas\x20token\x20for\x20all\x20WoWok\x20operations.\x201\x20WOW\x20=\x2010^9\x20MIST.\x20Available\x20on\x20testnet\x20and\x20mainnet.'}],TESTNET_TOKENS=[];function buildMainnetTokensFromSDK(){try{const {MAINNET_BRIDGE_CONFIG:a}=require('@wowok/wowok');if(!a?.['tokens'])return[];const b=new Set();return a['tokens']['filter'](c=>{if(b['has'](c['wowTypeTag']))return![];return b['add'](c['wowTypeTag']),!![];})['map'](c=>({'type':c['wowTypeTag'],'symbol':c['symbol'],'decimals':c['wowDecimals'],'name':c['symbol']+'\x20(Bridge)','description':c['description']??'Bridge\x20token\x20on\x20WOW\x20mainnet.\x20'+c['wowDecimals']+'\x20decimals.'}));}catch{return[];}}export const OFFICIAL_TOKEN_REGISTRY={'gas':GAS_TOKENS,'testnet':TESTNET_TOKENS,'mainnet':buildMainnetTokensFromSDK()};export function getRegistryForNetwork(a){return[...OFFICIAL_TOKEN_REGISTRY['gas'],...a==='testnet'?OFFICIAL_TOKEN_REGISTRY['testnet']:[],...a==='mainnet'?OFFICIAL_TOKEN_REGISTRY['mainnet']:[]];}export function findInRegistryByType(a,b){const c=OFFICIAL_TOKEN_REGISTRY['gas']['find'](e=>e['type']===a);if(c)return c;const d=getRegistryForNetwork(b);return d['find'](e=>e['type']===a);}export function findInRegistryBySymbol(a,b){const c=a['toLowerCase'](),d=OFFICIAL_TOKEN_REGISTRY['gas']['filter'](g=>g['symbol']['toLowerCase']()===c),e=getRegistryForNetwork(b),f=e['filter'](g=>g['symbol']['toLowerCase']()===c&&!d['some'](h=>h['type']===g['type']));return[...d,...f];}export async function resolveTokenByType(a,b){const c=findInRegistryByType(a,b);if(c)return{'type':c['type'],'symbol':c['symbol'],'decimals':c['decimals'],'name':c['name'],'source':'registry','verified':!![]};const d=cacheNet(b)+'::'+a,e=RESOLUTION_CACHE['get'](d);if(e)return e;try{const {TokenInfo:f}=await import('@wowok/wowok'),g=f['Instance'](),h=await g['fetch'](a,undefined,b);if(h){const i={'type':h['type'],'symbol':h['symbol']??'','decimals':h['decimals']??0x0,'name':h['name']??'','source':'cache','verified':![]};return RESOLUTION_CACHE['set'](d,i),i;}}catch{}return undefined;}export async function resolveTokensBySymbol(a,b,c){const d=[],e=findInRegistryBySymbol(a,b);for(const f of e){d['push']({'type':f['type'],'symbol':f['symbol'],'decimals':f['decimals'],'name':f['name'],'source':'registry','verified':!![]});}try{const {query_local_token_list:g}=await import('@wowok/wowok'),h=await g({'symbol':a});for(const i of h){if(d['some'](j=>j['type']===i['type']))continue;d['push']({'type':i['type'],'symbol':i['symbol']??'','decimals':i['decimals']??0x0,'name':i['name']??'','source':'cache','verified':![]});}}catch{}return c&&d['sort']((j,k)=>{if(j['type']===c)return-0x1;if(k['type']===c)return 0x1;if(j['verified']&&!k['verified'])return-0x1;if(!j['verified']&&k['verified'])return 0x1;return 0x0;}),d;}const AMOUNT_WITH_SYMBOL=/^(\d+(?:\.\d+)?)\s*([A-Za-z][A-Za-z0-9]*)$/;export function isAmountWithSymbol(a){if(typeof a!=='string')return![];const b=a['match'](AMOUNT_WITH_SYMBOL);if(!b)return![];const c=b[0x2];return c['length']>=0x2&&c['length']<=0xa;}export async function parseAmount(a,b,c){const d=a,e=await resolveTokenByType(b,c),f=e!==undefined,g=e?.['decimals']??0x9,h=e?.['symbol']??'',i=e?.['source']??'onchain',j=e?.['verified']??![];if(typeof a==='string'){const m=a['match'](AMOUNT_WITH_SYMBOL);if(m){if(!f)throw new Error('TOKEN\x20PRECISION\x20UNKNOWN\x20for\x20'+b+'\x20—\x20REFUSING\x20to\x20convert\x20\x22'+a+'\x22.\x20'+'The\x20token\x27s\x20decimals\x20could\x20not\x20be\x20resolved\x20from\x20the\x20official\x20registry,\x20local\x20cache,\x20'+'or\x20on-chain\x20metadata,\x20and\x20guessing\x20decimals\x20would\x20forge\x20a\x20wrong\x20on-chain\x20value.\x20'+'Retry\x20(the\x20on-chain\x20lookup\x20may\x20have\x20been\x20transient),\x20or\x20pass\x20a\x20pure\x20numeric\x20value\x20'+'in\x20smallest\x20units\x20only\x20if\x20you\x20are\x20certain\x20of\x20the\x20raw\x20u64\x20amount.\x20'+knownTokenSuggestions(c));const n=parseFloat(m[0x1]),o=m[0x2];if(h&&o['toLowerCase']()!==h['toLowerCase']())throw new Error('Amount\x20symbol\x20\x22'+o+'\x22\x20does\x20not\x20match\x20the\x20expected\x20token\x20symbol\x20\x22'+h+'\x22\x20'+('(type:\x20'+b+').\x20Either\x20use\x20the\x20correct\x20symbol\x20or\x20pass\x20a\x20pure\x20numeric\x20value\x20')+('in\x20smallest\x20units\x20(e.g.,\x20'+(n*Math['pow'](0xa,g))['toFixed'](0x0)+').'));const p=displayToSmallestUnit(n,g);return{'smallestUnit':p,'displayAmount':n+'\x20'+o,'originalInput':d,'tokenType':b,'tokenSymbol':h||o,'decimals':g,'converted':!![],'source':i,'verified':j,'precision_known':!![]};}}let k;try{k=BigInt(a);}catch{throw new Error('Invalid\x20amount:\x20\x22'+a+'\x22.\x20Expected\x20a\x20number,\x20a\x20numeric\x20string\x20(smallest\x20unit),\x20'+'or\x20a\x20display-format\x20string\x20like\x20\x222.5WOW\x22\x20(matching\x20the\x20token\x27s\x20symbol).');}const l=f?smallestToDisplay(k,g):k['toString']()+'\x20raw\x20smallest\x20units\x20(token\x20precision\x20unknown)';return{'smallestUnit':k,'displayAmount':f&&h?l+'\x20'+h:l,'originalInput':d,'tokenType':b,'tokenSymbol':h,'decimals':g,'converted':![],'source':i,'verified':j,'precision_known':f};}function displayToSmallestUnit(a,b){const c=a['toString'](),[d,e='']=c['split']('.'),f=e['padEnd'](b,'0')['slice'](0x0,b),g=d+f;return BigInt(g||'0');}export function smallestToDisplay(a,b){const c=a<0x0n?'-':'',d=a<0x0n?-a:a,e=BigInt(0xa)**BigInt(b),f=d/e,g=d%e;if(g===0x0n)return''+c+f['toString']();const h=g['toString']()['padStart'](b,'0')['replace'](/0+$/,'');return''+c+f['toString']()+'.'+h;}export function displayStringToSmallest(a,b){const c=a['trim']();if(!/^\d+(\.\d+)?$/['test'](c))throw new Error('Invalid\x20display\x20amount:\x20\x22'+a+'\x22.\x20Expected\x20a\x20non-negative\x20decimal\x20number\x20like\x20\x222.5\x22.');const [d,e='']=c['split']('.');if(e['length']>b)throw new Error('Too\x20many\x20decimal\x20places:\x20\x22'+a+'\x22\x20has\x20'+e['length']+',\x20but\x20this\x20token\x20supports\x20at\x20most\x20'+b+'\x20(decimals:\x20'+b+').');const f=e['padEnd'](b,'0');return BigInt(d+f);}export function generateFundConfirmation(a,b=[]){const d=b['length']>0x0,e=['MONEY\x20TRANSACTION\x20CONFIRMATION\x20REQUIRED',''];for(const f of a){const g=f['verified']?'\x20[VERIFIED]':'\x20[UNVERIFIED]',h='\x20(source:\x20'+f['source']+')';e['push']('\x20\x20•\x20'+f['context']+':\x20'+f['displayAmount']+g+h),f['converted']&&e['push']('\x20\x20\x20\x20(converted\x20from\x20display\x20format\x20to\x20smallest\x20unit)');}if(d){e['push']('','AMBIGUITY\x20WARNING\x20—\x20multiple\x20tokens\x20share\x20the\x20same\x20symbol:');for(const i of b){e['push']('\x20\x20Symbol\x20\x22'+i['symbol']+'\x22\x20matches:');for(const j of i['candidates']){const k=j['verified']?'\x20[VERIFIED]':'\x20[UNVERIFIED]';e['push']('\x20\x20\x20\x20-\x20type:\x20'+j['type']+',\x20decimals:\x20'+j['decimals']+k+'\x20(source:\x20'+j['source']+')');}e['push']('\x20\x20\x20\x20→\x20Specify\x20the\x20full\x20type\x20string\x20in\x20type_parameter\x20to\x20disambiguate.');}}return e['push']('','This\x20operation\x20involves\x20money.\x20Please\x20confirm\x20before\x20proceeding.'),{'requiresConfirmation':!![],'reason':d?'Money\x20transaction\x20with\x20ambiguous\x20token\x20symbol\x20—\x20user\x20must\x20specify\x20full\x20type':'Money\x20transaction\x20requires\x20user\x20confirmation','fields':a,'ambiguities':b,'message':e['join']('\x0a')};}function extractTokenType(a,b,c){if(a?.['object']&&typeof a['object']==='object'&&a['object']['type_parameter'])return a['object']['type_parameter'];if(b==='payment'&&a?.['type_parameter'])return a['type_parameter'];if(c)return c;return GasTokenType;}const MONETARY_FIELDS={'service':[{'path':'sales.sales','context':'Service\x20sale\x20price','isArray':!![],'amountField':'price'},{'path':'compensation_fund_add.balance','context':'Service\x20compensation\x20fund\x20deposit'},{'path':'order_new.buy.total_pay.balance','context':'Order\x20payment\x20amount'},{'path':'discount.discount_value','context':'Discount\x20value'}],'arbitration':[{'path':'dispute.fee.balance','context':'Arbitration\x20dispute\x20fee'},{'path':'fee','context':'Arbitration\x20fee'}],'reward':[{'path':'coin_add.balance','context':'Reward\x20coin\x20add'}],'treasury':[{'path':'deposit.coin.balance','context':'Treasury\x20deposit\x20amount'},{'path':'withdraw.amount.fixed','context':'Treasury\x20withdrawal\x20amount'}],'payment':[{'path':'revenue','context':'Payment\x20amount','isArray':!![],'amountField':'amount.balance'}],'allocation':[{'path':'coin.balance','context':'Allocation\x20funding\x20amount'}]};function getNestedValue(a,b){const c=b['split']('.');let d=a;for(const e of c){if(d==null)return undefined;d=d[e];}return d;}export async function processFundOperation(a,b,c,d){const e={'convertedData':a,'warnings':[],'errors':[],'confirmation':null},f=MONETARY_FIELDS[b];if(!f)return e;const g=extractTokenType(a,b,d?.['objectTokenType']),h=[],k=[],l=new Map();for(const m of f){const n=m['isArray']===!![],o=m['amountField'];if(n&&o){const p=getNestedValue(a,m['path']);if(Array['isArray'](p))for(let q=0x0;q<p['length'];q++){const r=p[q],s=o['split']('.');let t=r;for(let v=0x0;v<s['length']-0x1;v++){t=t?.[s[v]];if(t==null)break;}const u=s[s['length']-0x1];if(t&&t[u]!=null){const w=m['path']+'['+q+'].'+o;await processSingleField(t,u,w,m['context'],g,c,e,h,k,l);}}}else{const x=m['path']['lastIndexOf']('.'),y=x>=0x0?m['path']['slice'](0x0,x):'',z=x>=0x0?m['path']['slice'](x+0x1):m['path'],A=y?getNestedValue(a,y):a;A&&A[z]!=null&&await processSingleField(A,z,m['path'],m['context'],g,c,e,h,k,l);}}if(h['length']>0x0){e['confirmation']=generateFundConfirmation(h,k);const B=h['length'],C=h['some'](E=>!E['verified']),D=k['length']>0x0;D&&e['warnings']['push']('AMBIGUOUS\x20TOKEN:\x20'+k['length']+'\x20token\x20symbol(s)\x20have\x20multiple\x20candidates.\x20'+'User\x20must\x20specify\x20full\x20type\x20string\x20in\x20type_parameter\x20to\x20disambiguate.\x20'+'See\x20confirmation\x20message\x20for\x20details.'),C&&e['warnings']['push']('UNVERIFIED\x20TOKEN:\x20some\x20monetary\x20fields\x20use\x20tokens\x20not\x20in\x20the\x20official\x20registry.\x20'+'Precision\x20was\x20resolved\x20from\x20cache/on-chain.\x20Verify\x20the\x20token\x20type\x20before\x20proceeding.'),e['warnings']['push']('MONEY\x20CONFIRMATION:\x20'+B+'\x20monetary\x20field(s)\x20require\x20user\x20confirmation.\x20'+('Token\x20type:\x20'+g+'.\x20Use\x20env.confirmed=true\x20after\x20user\x20consent.'));}return e;}async function processSingleField(a,b,c,d,e,f,g,h,i,j){const k=a[b];if(k==null)return;try{const l=await parseAmount(k,e,f);if(!l['precision_known']){g['errors']['push']('FUND\x20INPUT\x20BLOCKED\x20at\x20'+c+':\x20token\x20precision\x20unavailable\x20for\x20'+e+'.\x20'+('The\x20raw\x20value\x20'+JSON['stringify'](k)+'\x20was\x20NOT\x20converted\x20or\x20confirmed.\x20')+'Retry\x20after\x20the\x20token\x20info\x20resolves\x20(registry\x20→\x20cache\x20→\x20on-chain),\x20'+('or\x20use\x20a\x20known\x20token.\x20'+knownTokenSuggestions(f)));return;}l['converted']&&(a[b]=l['smallestUnit']['toString']());h['push']({'path':c,'displayAmount':l['displayAmount'],'tokenType':l['tokenType'],'tokenSymbol':l['tokenSymbol'],'verified':l['verified'],'source':l['source'],'converted':l['converted'],'context':d});if(l['tokenSymbol']&&l['source']!=='registry'){const m=l['tokenSymbol']['toLowerCase']();let n=j['get'](m);if(!n){const o=await resolveTokensBySymbol(l['tokenSymbol'],f,e);o['length']>0x1&&(n=o,j['set'](m,n),i['push']({'symbol':l['tokenSymbol'],'candidates':n['map'](p=>({'type':p['type'],'decimals':p['decimals'],'source':p['source'],'verified':p['verified']}))}));}}}catch(p){g['errors']['push']('FUND\x20INPUT\x20BLOCKED\x20at\x20'+c+':\x20'+p['message']);}}export function generateSkillsHint(a){if(!a||!a['requiresConfirmation'])return null;const b=a['ambiguities']['length']>0x0;if(b)return'SKILLS\x20HINT:\x20This\x20money\x20transaction\x20has\x20ambiguous\x20token\x20symbols.\x20'+'If\x20the\x20wowok-safety\x20skill\x20is\x20installed,\x20it\x20can\x20guide\x20the\x20user\x20through\x20'+'interactive\x20disambiguation.\x20Otherwise,\x20the\x20MCP\x20fund\x20layer\x20has\x20already\x20'+'listed\x20all\x20candidates\x20in\x20the\x20confirmation\x20message\x20—\x20ask\x20the\x20user\x20to\x20'+'specify\x20the\x20full\x20token\x20type\x20string\x20in\x20type_parameter.';return'SKILLS\x20HINT:\x20This\x20money\x20transaction\x20requires\x20user\x20confirmation.\x20'+'If\x20the\x20wowok-safety\x20skill\x20is\x20installed,\x20it\x20provides\x20R1-R10\x20confirmation\x20'+'dialogue\x20scripts.\x20Otherwise,\x20present\x20the\x20confirmation\x20message\x20to\x20the\x20user\x20'+'and\x20proceed\x20only\x20after\x20explicit\x20consent\x20(env.confirmed=true).';}export async function formatChainValue(a,b,c){let d;try{d=BigInt(a)['toString']();}catch{d=String(a);}const e=await resolveTokenByType(b,c);if(e&&typeof e['decimals']==='number'){let f=d;try{f=smallestToDisplay(BigInt(d),e['decimals']);}catch{}const g=e['symbol']||'',h=g?f+'\x20'+g+'\x20(decimals:\x20'+e['decimals']+';\x201\x20'+g+'\x20=\x2010^'+e['decimals']+'\x20raw\x20units;\x20raw:\x20'+d+')':f+'\x20(decimals:\x20'+e['decimals']+';\x201\x20unit\x20=\x2010^'+e['decimals']+'\x20raw\x20units;\x20raw:\x20'+d+')';return{'raw':d,'display':f,'symbol':g||undefined,'decimals':e['decimals'],'token_type':b,'precision_known':!![],'text':h};}return{'raw':d,'display':d,'token_type':b,'precision_known':![],'text':d+'\x20raw\x20smallest\x20units\x20(token\x20precision\x20unavailable\x20for\x20'+b+'\x20—\x20'+'cannot\x20convert\x20to\x20unit\x20value.\x20Conversion\x20rule\x20once\x20decimals\x20N\x20is\x20known:\x20'+'unit\x20=\x20raw\x20/\x2010^N.\x20Re-run\x20the\x20query\x20to\x20retry\x20the\x20on-chain\x20precision\x20lookup.)'};}export function registryDisplayHint(a,b){if(!a)return undefined;const c=findInRegistryByType(a,b);if(!c)return undefined;return{'decimals':c['decimals'],'symbol':c['symbol']};}const RESOLUTION_CACHE=new Map(),OBJECT_TYPE_CACHE=new Map();function cacheNet(a){return a??'default';}function isCacheableObjectRef(a){return/^0x[0-9a-fA-F]{20,}$/['test'](a);}export function clearFundResolutionCaches(){RESOLUTION_CACHE['clear'](),OBJECT_TYPE_CACHE['clear']();}export function knownTokenSuggestions(a){const b=getRegistryForNetwork(a)['map'](c=>c['symbol']+'\x20('+c['type']+',\x20'+c['decimals']+'\x20decimals)');return b['length']>0x0?'Known\x20tokens:\x20'+b['join'](';\x20')+'.':'No\x20officially-known\x20tokens\x20on\x20this\x20network.';}export function formatAmountText(a,b,c){let d;try{d=BigInt(a)['toString']();}catch{d=String(a);}if(b===undefined)return d+'\x20smallest\x20units\x20(token\x20precision\x20unknown)';let e=d;try{e=smallestToDisplay(BigInt(d),b);}catch{}return c?e+'\x20'+c+'\x20(decimals:\x20'+b+';\x20raw:\x20'+d+')':e+'\x20(decimals:\x20'+b+';\x20raw:\x20'+d+')';}export async function convertTokenValue(a,b,c){const d=await resolveTokenByType(a,c),f=d?.['decimals'],g=d?.['symbol']||undefined,h={'token_type':a,'symbol':g,'decimals':f};if(b['raw']!==undefined){let j;try{j=BigInt(b['raw'])['toString']();}catch{return{...h,'precision_known':f!==undefined,'direction':'raw_to_unit','input':String(b['raw']),'output':'','error':'Invalid\x20raw\x20value:\x20\x22'+String(b['raw'])+'\x22\x20—\x20expected\x20a\x20non-negative\x20integer\x20(u64\x20smallest\x20units).','text':'Cannot\x20convert:\x20invalid\x20raw\x20value\x20\x22'+String(b['raw'])+'\x22.'};}if(f===undefined)return{...h,'precision_known':![],'direction':'raw_to_unit','input':j,'output':j,'text':j+'\x20raw\x20smallest\x20units\x20(token\x20precision\x20unavailable\x20for\x20'+a+'\x20—\x20'+'cannot\x20convert\x20to\x20unit\x20value.\x20Rule\x20once\x20decimals\x20N\x20is\x20known:\x20unit\x20=\x20raw\x20/\x2010^N.)'};let k=j;try{k=smallestToDisplay(BigInt(j),f);}catch{}return{...h,'precision_known':!![],'direction':'raw_to_unit','input':j,'output':k,'text':g?j+'\x20raw\x20=\x20'+k+'\x20'+g+'\x20(decimals:\x20'+f+';\x201\x20'+g+'\x20=\x2010^'+f+'\x20raw\x20units)':j+'\x20raw\x20=\x20'+k+'\x20(decimals:\x20'+f+';\x201\x20unit\x20=\x2010^'+f+'\x20raw\x20units)'};}const i=String(b['unit']??'')['trim']();if(f===undefined)return{...h,'precision_known':![],'direction':'unit_to_raw','input':i,'output':'','error':'Token\x20precision\x20unavailable\x20for\x20'+a+'\x20—\x20REFUSING\x20to\x20convert\x20\x22'+i+'\x22\x20to\x20raw\x20units.\x20'+'Guessing\x20decimals\x20would\x20forge\x20a\x20wrong\x20on-chain\x20value.\x20Retry\x20after\x20the\x20precision\x20lookup\x20succeeds,\x20'+'or\x20check\x20the\x20token\x27s\x20coin\x20metadata.','text':'Cannot\x20convert\x20\x22'+i+'\x22\x20to\x20raw\x20units:\x20token\x20precision\x20unknown\x20for\x20'+a+'.'};try{const l=displayStringToSmallest(i,f);return{...h,'precision_known':!![],'direction':'unit_to_raw','input':i,'output':l['toString'](),'text':g?i+'\x20'+g+'\x20=\x20'+l['toString']()+'\x20raw\x20smallest\x20units\x20(decimals:\x20'+f+';\x201\x20'+g+'\x20=\x2010^'+f+'\x20raw\x20units)':i+'\x20=\x20'+l['toString']()+'\x20raw\x20smallest\x20units\x20(decimals:\x20'+f+';\x201\x20unit\x20=\x2010^'+f+'\x20raw\x20units)'};}catch(m){const n=m instanceof Error?m['message']:String(m);return{...h,'precision_known':!![],'direction':'unit_to_raw','input':i,'output':'','error':n,'text':'Cannot\x20convert\x20\x22'+i+'\x22\x20to\x20raw\x20units:\x20'+n};}}export const TOKEN_GENERIC_OBJECT_TYPES=['Treasury','Allocation','Arbitration','Arb','Payment','Reward','Service'];export function extractGenericTokenType(a){if(!a||typeof a!=='string')return undefined;const b=a['indexOf']('<');if(b<0x0)return undefined;let c=0x0;for(let d=b;d<a['length'];d++){const e=a[d];if(e==='<')c++;else{if(e==='>'){c--;if(c===0x0)return a['slice'](b+0x1,d)['trim']()||undefined;}}}return undefined;}export async function resolveObjectTokenType(a,b){if(!a||typeof a!=='string')return undefined;const c=isCacheableObjectRef(a),d=cacheNet(b)+'::'+a;if(c){const e=OBJECT_TYPE_CACHE['get'](d);if(e)return e;}try{const {query_objects:f}=await import('@wowok/wowok'),g=await f({'objects':[a],'network':b}),h=g?.['objects']?.[0x0];if(!h)return undefined;const i=h['type_raw']??h['content_raw']?.['type']??undefined,j={'tokenType':extractGenericTokenType(i),'objectType':h['type'],'typeRaw':i};if(c)OBJECT_TYPE_CACHE['set'](d,j);return j;}catch{return undefined;}}export async function resolveOperationObjectTokenType(a,b,c){if(!a)return undefined;if(a['object']&&typeof a['object']==='object'&&typeof a['object']['type_parameter']==='string')return a['object']['type_parameter'];if(b==='payment'&&typeof a['type_parameter']==='string')return a['type_parameter'];if(typeof a['object']==='string'&&a['object']['length']>0x0){const d=await resolveObjectTokenType(a['object'],c);return d?.['tokenType'];}return undefined;}const RECEIVE_TOKEN_FIELDS={'treasury':['receive'],'allocation':['received_coins'],'reward':['receive'],'service':['compensation_fund_receive'],'arbitration':['receive']},COIN_PARAM_FIELDS={'treasury':['deposit.coin'],'allocation':['coin'],'reward':['coin_add'],'arbitration':['dispute.fee'],'service':['compensation_fund_add','order_new.buy.total_pay']};export async function validateOperationTokenMatch(a,b,c,d){const e={'errors':[],'warnings':[],'objectTokenType':c};if(!a||!c)return e;const f=typeof a['object']==='string'?a['object']:'the\x20target\x20object',g=(h,i)=>'TOKEN\x20TYPE\x20MISMATCH\x20('+i+'):\x20'+f+'\x20only\x20accepts\x20'+c+'\x20'+('(its\x20generic\x20token\x20type\x20is\x20fixed\x20and\x20immutable),\x20but\x20'+h+'\x20was\x20provided.\x20')+('Use\x20'+c+'\x20for\x20this\x20operation,\x20or\x20target\x20a\x20different\x20object.');for(const h of RECEIVE_TOKEN_FIELDS[b]??[]){const i=a[h];i&&typeof i==='object'&&typeof i['token_type']==='string'&&i['token_type']!==c&&e['errors']['push'](g(i['token_type'],'field\x20\x27'+h+'.token_type\x27'));}for(const j of COIN_PARAM_FIELDS[b]??[]){const k=getNestedValue(a,j);if(k&&typeof k==='object'&&typeof k['coin']==='string'){const l=k['coin'],m=await resolveObjectTokenType(l,d);if(m?.['tokenType'])m['tokenType']!==c&&e['errors']['push'](g(m['tokenType'],'coin\x20\x27'+l+'\x27\x20at\x20\x27'+j+'\x27'));else m===undefined&&e['warnings']['push']('Could\x20not\x20resolve\x20coin\x20object\x20\x27'+l+'\x27\x20('+j+')\x20to\x20verify\x20its\x20token\x20type\x20'+('matches\x20'+c+'.\x20The\x20on-chain\x20type\x20check\x20will\x20reject\x20a\x20mismatch\x20at\x20execution.'));}}return e;}const OBJECT_MONEY_FIELDS={'Treasury':['balance','inflow','outflow'],'Allocation':['balance'],'Arbitration':['fee','balance'],'Reward':['balance'],'Service':['compensation_fund'],'Payment':['amount'],'Arb':['fee']};export async function annotateObjectMonetaryFields(a,b){if(!a||typeof a!=='object'||typeof a['type']!=='string')return;let c=extractGenericTokenType(a['type_raw']);const d={},e=async(f,g,h)=>{if(g===null||g===undefined)return;if(typeof g!=='string'&&typeof g!=='number'&&typeof g!=='bigint')return;d[f]=h?await formatChainValue(g,h,b):{'raw':String(g),'display':String(g),'token_type':'','precision_known':![],'text':String(g)+'\x20raw\x20smallest\x20units\x20(token\x20type\x20could\x20not\x20be\x20determined\x20for\x20this\x20field\x20—\x20'+'no\x20conversion\x20applied.\x20Showing\x20the\x20true\x20raw\x20value;\x20re-run\x20the\x20query\x20to\x20retry\x20resolution.)'};};if(!c&&(a['type']==='Order'||a['type']==='Discount')&&typeof a['service']==='string')try{const f=await resolveObjectTokenType(a['service'],b);c=f?.['tokenType'];}catch{}for(const g of OBJECT_MONEY_FIELDS[a['type']]??[]){await e(g,a[g],c);}switch(a['type']){case'Service':if(Array['isArray'](a['sales']))for(let h=0x0;h<a['sales']['length'];h++){await e('sales['+h+'].price',a['sales'][h]?.['price'],c);}break;case'Order':await e('amount',a['amount'],c);if(Array['isArray'](a['items']))for(let j=0x0;j<a['items']['length'];j++){await e('items['+j+'].price',a['items'][j]?.['price'],c);}break;case'Payment':if(Array['isArray'](a['record']))for(let k=0x0;k<a['record']['length'];k++){await e('record['+k+'].amount',a['record'][k]?.['amount'],c);}break;case'Reward':if(Array['isArray'](a['guards']))for(let l=0x0;l<a['guards']['length'];l++){const m=a['guards'][l]?.['amount'];m&&typeof m==='object'&&m['type']===0x1&&await e('guards['+l+'].amount.value',m['value'],c);}break;case'Arb':await e('indemnity.amount',a['indemnity']?.['amount'],c);break;case'Discount':await e('benchmark',a['benchmark'],c);a['discount_type']===0x1&&await e('off',a['off'],c);break;}Object['keys'](d)['length']>0x0&&(a['_money_display']=d);}const TABLE_ITEM_MONEY_FIELDS={'TableItem_TreasuryHistory':['amount'],'TableItem_RewardRecord':['total']};export async function resolveParentObjectTokenType(a,b){const c=await resolveObjectTokenType(a,b);if(!c)return undefined;if(c['objectType']&&TOKEN_GENERIC_OBJECT_TYPES['includes'](c['objectType']))return c['tokenType'];return undefined;}export async function annotateTableItemMonetaryFields(a,b,c){if(!a||typeof a!=='object'||typeof a['type']!=='string')return;const d={},e=async(f,g)=>{if(g===null||g===undefined)return;if(typeof g!=='string'&&typeof g!=='number'&&typeof g!=='bigint')return;d[f]=b?await formatChainValue(g,b,c):{'raw':String(g),'display':String(g),'token_type':'','precision_known':![],'text':String(g)+'\x20raw\x20smallest\x20units\x20(parent\x20object\x20token\x20type\x20could\x20not\x20'+'be\x20resolved\x20—\x20no\x20conversion\x20applied)'};};for(const f of TABLE_ITEM_MONEY_FIELDS[a['type']]??[]){await e(f,a[f]);}if(a['type']==='TableItem_RewardRecord'&&Array['isArray'](a['record']))for(let g=0x0;g<a['record']['length'];g++){await e('record['+g+'].amount',a['record'][g]?.['amount']);}Object['keys'](d)['length']>0x0&&(a['_money_display']=d);}export async function annotateEventMonetaryFields(a,b){if(!a||typeof a!=='object')return;const c=a['type']==='NewOrderEvent'||typeof a['type']==='string'&&a['type']['includes']('::order::NewOrderEvent');if(!c)return;const d=a['parsedJson_raw']??{},e=a['amount']??d['amount'];if(e===null||e===undefined)return;if(typeof e!=='string'&&typeof e!=='number'&&typeof e!=='bigint')return;let f;const g=a['service']??d['service'];if(typeof g==='string'&&g)try{f=(await resolveObjectTokenType(g,b))?.['tokenType'];}catch{}a['_money_display']={'amount':f?await formatChainValue(e,f,b):{'raw':String(e),'display':String(e),'token_type':'','precision_known':![],'text':String(e)+'\x20raw\x20smallest\x20units\x20(order\x27s\x20Service\x20token\x20type\x20could\x20not\x20be\x20'+'resolved\x20—\x20showing\x20the\x20true\x20raw\x20value;\x20re-run\x20the\x20query\x20to\x20retry.)'}};}export async function annotateEventsMonetaryFields(a,b){if(!Array['isArray'](a))return;for(const c of a){try{await annotateEventMonetaryFields(c,b);}catch{}}}export async function annotateBalanceChanges(a,b){if(!Array['isArray'](a))return;for(const c of a){try{const d=c?.['coin_type'],e=c?.['amount'];if(typeof d!=='string'||!d)continue;if(typeof e!=='string'&&typeof e!=='number'&&typeof e!=='bigint')continue;c['_money_display']={'amount':await formatChainValue(e,d,b)};}catch{}}}export async function prepareFundOperation(a,b,c){const d=await resolveOperationObjectTokenType(a,b,c),e=await validateOperationTokenMatch(a,b,d,c),f=await processFundOperation(a,b,c,{'objectTokenType':d});return{...f,'warnings':[...e['warnings'],...f['warnings']],'matchErrors':e['errors'],'blockingErrors':[...e['errors'],...f['errors']],'objectTokenType':d};}