@wowok/agent-mcp 2.7.0 → 2.7.2

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 (427) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/customer-advice.js +1 -130
  4. package/dist/customer/index.js +1 -11
  5. package/dist/customer/industry-risks.js +1 -438
  6. package/dist/customer/info-puzzle.js +1 -681
  7. package/dist/customer/order-monitor.js +1 -328
  8. package/dist/customer/order-strategy.js +1 -373
  9. package/dist/customer/post-purchase.js +1 -351
  10. package/dist/customer/preorder-compare.js +1 -34
  11. package/dist/customer/reminder-system.js +1 -316
  12. package/dist/customer/risk-assessment.d.ts +5 -1
  13. package/dist/customer/risk-assessment.js +1 -397
  14. package/dist/customer/types.js +1 -13
  15. package/dist/customer/user-preferences.js +1 -460
  16. package/dist/evaluation/arbitration-game.d.ts +23 -0
  17. package/dist/evaluation/arbitration-game.js +1 -0
  18. package/dist/evaluation/builtins/demand-match.d.ts +15 -0
  19. package/dist/evaluation/builtins/demand-match.js +1 -0
  20. package/dist/evaluation/builtins/index.d.ts +3 -0
  21. package/dist/evaluation/builtins/index.js +1 -0
  22. package/dist/evaluation/builtins/service-risk.d.ts +6 -0
  23. package/dist/evaluation/builtins/service-risk.js +1 -0
  24. package/dist/evaluation/capability.d.ts +50 -0
  25. package/dist/evaluation/capability.js +1 -0
  26. package/dist/evaluation/composer.d.ts +13 -0
  27. package/dist/evaluation/composer.js +1 -0
  28. package/dist/evaluation/engine.d.ts +18 -0
  29. package/dist/evaluation/engine.js +1 -0
  30. package/dist/evaluation/extract.d.ts +30 -0
  31. package/dist/evaluation/extract.js +1 -0
  32. package/dist/evaluation/game-strategy.d.ts +27 -0
  33. package/dist/evaluation/game-strategy.js +1 -0
  34. package/dist/evaluation/gap.d.ts +2 -0
  35. package/dist/evaluation/gap.js +1 -0
  36. package/dist/evaluation/index.d.ts +12 -0
  37. package/dist/evaluation/index.js +1 -0
  38. package/dist/evaluation/node-game.d.ts +62 -0
  39. package/dist/evaluation/node-game.js +1 -0
  40. package/dist/evaluation/region.d.ts +10 -0
  41. package/dist/evaluation/region.js +1 -0
  42. package/dist/evaluation/types.d.ts +77 -0
  43. package/dist/evaluation/types.js +1 -0
  44. package/dist/evaluation/user-injection.d.ts +6 -0
  45. package/dist/evaluation/user-injection.js +1 -0
  46. package/dist/examples/education-contact-create.json +40 -0
  47. package/dist/examples/freelance-contact-create.json +40 -0
  48. package/dist/examples/insurance-machine-create.json +1 -1
  49. package/dist/examples/insurance-service-allocators.json +1 -1
  50. package/dist/examples/machine-publish.json +1 -1
  51. package/dist/examples/rental-ziroom-service-create.json +1 -1
  52. package/dist/examples/retail-adv-guard-messenger-proof-create.json +1 -1
  53. package/dist/examples/retail-myshop-service-create.json +1 -1
  54. package/dist/examples/retail-myshop-service-customer-required.json +1 -1
  55. package/dist/examples/subscription-contact-create.json +40 -0
  56. package/dist/examples/threebody-machine-create.json +1 -1
  57. package/dist/examples/travel-machine-create.json +1 -1
  58. package/dist/examples/travel-service-create.json +1 -1
  59. package/dist/experience/experience-reuse.js +1 -103
  60. package/dist/experience/index.js +1 -5
  61. package/dist/experience/intent-distill.js +1 -83
  62. package/dist/experience/realtime-feedback.js +1 -94
  63. package/dist/experience/types.js +1 -1
  64. package/dist/experience/user-profile.js +1 -171
  65. package/dist/extensions/business-modules.js +1 -287
  66. package/dist/extensions/capability-manifest.js +1 -781
  67. package/dist/extensions/constraint-registry.js +1 -198
  68. package/dist/extensions/index.js +1 -6
  69. package/dist/extensions/metric-registry.js +1 -257
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.js +1 -717
  73. package/dist/extensions/types.js +1 -1
  74. package/dist/harness/auto-escalation.js +1 -68
  75. package/dist/harness/checkpoint.js +1 -129
  76. package/dist/harness/index.js +1 -78
  77. package/dist/harness/plan.js +1 -276
  78. package/dist/harness/recover.js +1 -139
  79. package/dist/harness/types.js +1 -1
  80. package/dist/harness/verify.js +1 -237
  81. package/dist/index.js +1 -273
  82. package/dist/intent/enrich.d.ts +1 -0
  83. package/dist/intent/enrich.js +1 -0
  84. package/dist/intent/index.d.ts +23 -0
  85. package/dist/intent/index.js +1 -0
  86. package/dist/intent/matcher.d.ts +2 -0
  87. package/dist/intent/matcher.js +1 -0
  88. package/dist/intent/store.d.ts +19 -0
  89. package/dist/intent/store.js +1 -0
  90. package/dist/intent/types.d.ts +33 -0
  91. package/dist/intent/types.js +1 -0
  92. package/dist/knowledge/acquisition-flywheel.js +1 -192
  93. package/dist/knowledge/allocation-confirm.js +1 -534
  94. package/dist/knowledge/allocation-context.js +1 -249
  95. package/dist/knowledge/allocation-ledger.js +1 -463
  96. package/dist/knowledge/allocation-puzzle.js +1 -298
  97. package/dist/knowledge/allocation-risk.js +1 -568
  98. package/dist/knowledge/allocation-templates.js +1 -970
  99. package/dist/knowledge/allocation-translation.js +1 -585
  100. package/dist/knowledge/arb-risk.js +1 -210
  101. package/dist/knowledge/arbitration-confirm.js +1 -559
  102. package/dist/knowledge/arbitration-context.js +1 -505
  103. package/dist/knowledge/arbitration-ledger.js +1 -521
  104. package/dist/knowledge/arbitration-puzzle.js +1 -304
  105. package/dist/knowledge/arbitration-risk.js +1 -433
  106. package/dist/knowledge/arbitration-templates.js +1 -276
  107. package/dist/knowledge/arbitration-translation.js +1 -487
  108. package/dist/knowledge/arbitration-trust.js +1 -117
  109. package/dist/knowledge/audit-rules.js +1 -141
  110. package/dist/knowledge/bridge-risk.js +1 -263
  111. package/dist/knowledge/contact-risk.js +1 -200
  112. package/dist/knowledge/contact-templates.d.ts +27 -0
  113. package/dist/knowledge/contact-templates.js +1 -0
  114. package/dist/knowledge/demand-confirm.js +1 -206
  115. package/dist/knowledge/demand-matching.js +1 -132
  116. package/dist/knowledge/demand-risk.js +1 -240
  117. package/dist/knowledge/demand-translation.js +1 -354
  118. package/dist/knowledge/deployment-scanner.js +1 -823
  119. package/dist/knowledge/dynamic-pricing.js +1 -87
  120. package/dist/knowledge/examples-scanner-cli.js +1 -26
  121. package/dist/knowledge/examples-scanner.js +1 -825
  122. package/dist/knowledge/flywheel-loop.js +1 -404
  123. package/dist/knowledge/fund-layer.js +1 -973
  124. package/dist/knowledge/glossary.js +1 -211
  125. package/dist/knowledge/guard-confirm.js +1 -406
  126. package/dist/knowledge/guard-context.js +1 -287
  127. package/dist/knowledge/guard-design-patterns.js +1 -360
  128. package/dist/knowledge/guard-ledger.js +1 -260
  129. package/dist/knowledge/guard-lint.js +1 -670
  130. package/dist/knowledge/guard-migration.js +1 -228
  131. package/dist/knowledge/guard-puzzle.js +1 -805
  132. package/dist/knowledge/guard-render.js +1 -700
  133. package/dist/knowledge/guard-risk.js +1 -1879
  134. package/dist/knowledge/guard-submission-prompt.js +1 -171
  135. package/dist/knowledge/guard-templates.js +1 -1105
  136. package/dist/knowledge/guard-translation.js +1 -1119
  137. package/dist/knowledge/index.js +1 -436
  138. package/dist/knowledge/industry-evolution.js +1 -323
  139. package/dist/knowledge/industry-generalizer.js +1 -381
  140. package/dist/knowledge/industry-registry.js +1 -174
  141. package/dist/knowledge/intent-metrics.d.ts +4 -3
  142. package/dist/knowledge/intent-metrics.js +1 -566
  143. package/dist/knowledge/machine-confirm.js +1 -559
  144. package/dist/knowledge/machine-context.js +1 -833
  145. package/dist/knowledge/machine-ledger.js +1 -338
  146. package/dist/knowledge/machine-puzzle.js +1 -494
  147. package/dist/knowledge/machine-render.js +1 -565
  148. package/dist/knowledge/machine-risk.js +1 -670
  149. package/dist/knowledge/machine-templates.js +1 -1597
  150. package/dist/knowledge/machine-topology.js +1 -234
  151. package/dist/knowledge/machine-translation.js +1 -513
  152. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  153. package/dist/knowledge/mcp-schema-audit.d.ts +1 -1
  154. package/dist/knowledge/mcp-schema-audit.js +1 -773
  155. package/dist/knowledge/onchain-constants.js +1 -35
  156. package/dist/knowledge/order-confirm.js +1 -573
  157. package/dist/knowledge/order-context.js +1 -390
  158. package/dist/knowledge/order-ledger.js +1 -341
  159. package/dist/knowledge/order-puzzle.js +1 -255
  160. package/dist/knowledge/order-risk.js +1 -653
  161. package/dist/knowledge/order-templates.js +1 -368
  162. package/dist/knowledge/order-translation.js +1 -550
  163. package/dist/knowledge/overrides-loader.js +1 -65
  164. package/dist/knowledge/passport-confirm.js +1 -531
  165. package/dist/knowledge/passport-context.js +1 -306
  166. package/dist/knowledge/passport-ledger.js +1 -282
  167. package/dist/knowledge/passport-puzzle.js +1 -333
  168. package/dist/knowledge/passport-risk.js +1 -450
  169. package/dist/knowledge/passport-templates.js +1 -568
  170. package/dist/knowledge/passport-translation.js +1 -516
  171. package/dist/knowledge/payment-risk.js +1 -249
  172. package/dist/knowledge/permission-confirm.js +1 -426
  173. package/dist/knowledge/permission-context.js +1 -224
  174. package/dist/knowledge/permission-ledger.js +1 -403
  175. package/dist/knowledge/permission-puzzle.js +1 -173
  176. package/dist/knowledge/permission-risk.js +1 -411
  177. package/dist/knowledge/permission-templates.js +1 -234
  178. package/dist/knowledge/permission-translation.js +1 -350
  179. package/dist/knowledge/personal-risk.js +1 -212
  180. package/dist/knowledge/process-model.js +1 -160
  181. package/dist/knowledge/progress-confirm.js +1 -456
  182. package/dist/knowledge/progress-context.js +1 -452
  183. package/dist/knowledge/progress-ledger.js +1 -330
  184. package/dist/knowledge/progress-puzzle.js +1 -219
  185. package/dist/knowledge/progress-risk.js +1 -461
  186. package/dist/knowledge/progress-templates.js +1 -228
  187. package/dist/knowledge/progress-translation.js +1 -405
  188. package/dist/knowledge/proof-confirm.js +1 -187
  189. package/dist/knowledge/proof-risk.js +1 -207
  190. package/dist/knowledge/proof-translation.js +1 -283
  191. package/dist/knowledge/registrar-risk.js +1 -217
  192. package/dist/knowledge/repository-confirm.js +1 -286
  193. package/dist/knowledge/repository-risk.js +1 -373
  194. package/dist/knowledge/repository-translation.js +1 -445
  195. package/dist/knowledge/reputation-rules.js +1 -99
  196. package/dist/knowledge/resource-risk.js +1 -157
  197. package/dist/knowledge/reward-confirm.js +1 -526
  198. package/dist/knowledge/reward-context.js +1 -504
  199. package/dist/knowledge/reward-ledger.js +1 -502
  200. package/dist/knowledge/reward-puzzle.js +1 -300
  201. package/dist/knowledge/reward-risk.js +1 -627
  202. package/dist/knowledge/reward-templates.js +1 -197
  203. package/dist/knowledge/reward-translation.js +1 -501
  204. package/dist/knowledge/safety-rules.js +1 -404
  205. package/dist/knowledge/scenario-modes.js +1 -321
  206. package/dist/knowledge/service-confirm.js +1 -807
  207. package/dist/knowledge/service-context.js +1 -403
  208. package/dist/knowledge/service-ledger.js +1 -609
  209. package/dist/knowledge/service-puzzle.js +1 -236
  210. package/dist/knowledge/service-risk.js +1 -615
  211. package/dist/knowledge/service-templates.js +1 -456
  212. package/dist/knowledge/service-translation.js +1 -622
  213. package/dist/knowledge/template-registry.d.ts +1 -1
  214. package/dist/knowledge/template-registry.js +1 -341
  215. package/dist/knowledge/tool-constraints.js +1 -195
  216. package/dist/knowledge/tools-reference.js +1 -155
  217. package/dist/knowledge/treasury-confirm.js +1 -512
  218. package/dist/knowledge/treasury-context.js +1 -363
  219. package/dist/knowledge/treasury-ledger.js +1 -300
  220. package/dist/knowledge/treasury-puzzle.js +1 -216
  221. package/dist/knowledge/treasury-risk.js +1 -440
  222. package/dist/knowledge/treasury-templates.js +1 -358
  223. package/dist/knowledge/treasury-translation.js +1 -498
  224. package/dist/knowledge/trust-metrics.js +1 -198
  225. package/dist/knowledge/util-risk.js +1 -135
  226. package/dist/loop-engineering/aggregate.js +1 -132
  227. package/dist/loop-engineering/context-collect.js +1 -83
  228. package/dist/loop-engineering/diagnose.js +1 -273
  229. package/dist/loop-engineering/improve.js +1 -405
  230. package/dist/loop-engineering/index.js +1 -4
  231. package/dist/loop-engineering/pipeline.js +1 -56
  232. package/dist/mode-market/index.js +1 -3
  233. package/dist/mode-market/registry.js +1 -124
  234. package/dist/mode-market/review.js +1 -214
  235. package/dist/mode-market/submission.js +1 -85
  236. package/dist/participation/collaborator-interest.d.ts +23 -0
  237. package/dist/participation/collaborator-interest.js +1 -0
  238. package/dist/participation/customer-interest.d.ts +25 -0
  239. package/dist/participation/customer-interest.js +1 -0
  240. package/dist/participation/merchant-interest.js +1 -100
  241. package/dist/participation/radar-core.d.ts +13 -3
  242. package/dist/participation/radar-core.js +1 -269
  243. package/dist/participation/supplier-interest.d.ts +25 -0
  244. package/dist/participation/supplier-interest.js +1 -0
  245. package/dist/persona/analyzer.d.ts +16 -0
  246. package/dist/persona/analyzer.js +1 -0
  247. package/dist/persona/bridge.d.ts +5 -0
  248. package/dist/persona/bridge.js +1 -0
  249. package/dist/persona/defaults.d.ts +4 -0
  250. package/dist/persona/defaults.js +1 -0
  251. package/dist/persona/experience-bridge.d.ts +3 -0
  252. package/dist/persona/experience-bridge.js +1 -0
  253. package/dist/persona/index.d.ts +18 -0
  254. package/dist/persona/index.js +1 -0
  255. package/dist/persona/model.d.ts +7 -0
  256. package/dist/persona/model.js +1 -0
  257. package/dist/persona/store.d.ts +19 -0
  258. package/dist/persona/store.js +1 -0
  259. package/dist/persona/types.d.ts +45 -0
  260. package/dist/persona/types.js +1 -0
  261. package/dist/project/business-puzzle.js +1 -383
  262. package/dist/project/context-assembly.js +1 -254
  263. package/dist/project/deployment-bridge.js +1 -120
  264. package/dist/project/deployment-doc.js +1 -1126
  265. package/dist/project/edit-planner.js +1 -1342
  266. package/dist/project/evaluation.js +1 -2011
  267. package/dist/project/game-theory.js +1 -177
  268. package/dist/project/graph-builder.js +1 -656
  269. package/dist/project/graph.js +1 -340
  270. package/dist/project/handlers.d.ts +5 -0
  271. package/dist/project/handlers.js +1 -1762
  272. package/dist/project/index.d.ts +1 -0
  273. package/dist/project/index.js +1 -301
  274. package/dist/project/intent-analyzer.js +1 -149
  275. package/dist/project/machine-nodes.js +1 -36
  276. package/dist/project/merchant-guide.js +1 -264
  277. package/dist/project/migration.js +1 -125
  278. package/dist/project/mode-actions.js +1 -309
  279. package/dist/project/namespace.js +1 -206
  280. package/dist/project/participation-radar.js +1 -428
  281. package/dist/project/pipeline-actions.js +1 -109
  282. package/dist/project/project-store.js +1 -422
  283. package/dist/project/query.js +1 -153
  284. package/dist/project/reverse-mapping.d.ts +34 -0
  285. package/dist/project/reverse-mapping.js +1 -0
  286. package/dist/project/risk-aggregator.js +1 -295
  287. package/dist/project/rollback-policy.js +1 -290
  288. package/dist/project/semantic-assembler.js +1 -345
  289. package/dist/project/semantic-graph.js +1 -245
  290. package/dist/project/stage-gate.js +1 -369
  291. package/dist/project/substep-trace.js +1 -332
  292. package/dist/project/task-tracker.js +1 -78
  293. package/dist/role/derivation.d.ts +18 -0
  294. package/dist/role/derivation.js +1 -0
  295. package/dist/role/index.d.ts +5 -0
  296. package/dist/role/index.js +1 -0
  297. package/dist/role/model.d.ts +8 -0
  298. package/dist/role/model.js +1 -0
  299. package/dist/role/resolution.d.ts +11 -0
  300. package/dist/role/resolution.js +1 -0
  301. package/dist/role/types.d.ts +11 -0
  302. package/dist/role/types.js +1 -0
  303. package/dist/rules.d.ts +2 -0
  304. package/dist/rules.js +1 -9
  305. package/dist/safety/confirm-gate.js +1 -88
  306. package/dist/safety/index.js +1 -3
  307. package/dist/safety/preview.js +1 -52
  308. package/dist/schema/call/allocation.js +1 -34
  309. package/dist/schema/call/arbitration.js +1 -113
  310. package/dist/schema/call/base.d.ts +15 -15
  311. package/dist/schema/call/base.js +1 -370
  312. package/dist/schema/call/bridge-handler.js +1 -265
  313. package/dist/schema/call/bridge.d.ts +7 -7
  314. package/dist/schema/call/bridge.js +1 -458
  315. package/dist/schema/call/contact.js +1 -37
  316. package/dist/schema/call/demand.js +1 -47
  317. package/dist/schema/call/guard.js +1 -161
  318. package/dist/schema/call/handler.js +1 -322
  319. package/dist/schema/call/index.js +1 -20
  320. package/dist/schema/call/machine.js +1 -193
  321. package/dist/schema/call/order.js +1 -35
  322. package/dist/schema/call/payment.js +1 -37
  323. package/dist/schema/call/permission-handler.js +1 -54
  324. package/dist/schema/call/permission.js +1 -105
  325. package/dist/schema/call/personal.js +1 -78
  326. package/dist/schema/call/progress.js +1 -47
  327. package/dist/schema/call/proof.js +1 -33
  328. package/dist/schema/call/repository.js +1 -77
  329. package/dist/schema/call/reward.js +1 -30
  330. package/dist/schema/call/semantic.js +1 -1657
  331. package/dist/schema/call/service.js +1 -178
  332. package/dist/schema/call/treasury.js +1 -71
  333. package/dist/schema/common/index.js +1 -407
  334. package/dist/schema/config/index.js +1 -68
  335. package/dist/schema/evaluation/index.d.ts +4436 -0
  336. package/dist/schema/evaluation/index.js +1 -0
  337. package/dist/schema/index.d.ts +4 -0
  338. package/dist/schema/index.js +1 -13
  339. package/dist/schema/intent-radar/index.d.ts +284 -0
  340. package/dist/schema/intent-radar/index.js +1 -0
  341. package/dist/schema/local/index.d.ts +21 -21
  342. package/dist/schema/local/index.js +1 -927
  343. package/dist/schema/local/wip.js +1 -187
  344. package/dist/schema/messenger/index.d.ts +7 -7
  345. package/dist/schema/messenger/index.js +1 -475
  346. package/dist/schema/operations.d.ts +7 -7
  347. package/dist/schema/operations.js +1 -520
  348. package/dist/schema/persona/index.d.ts +1985 -0
  349. package/dist/schema/persona/index.js +1 -0
  350. package/dist/schema/project/index.d.ts +96 -50
  351. package/dist/schema/project/index.js +1 -2057
  352. package/dist/schema/query/index.d.ts +423 -7
  353. package/dist/schema/query/index.js +1 -1640
  354. package/dist/schema/schema-query/index.js +1 -104
  355. package/dist/schema/schema-version.js +1 -76
  356. package/dist/schema/sync-layer4.d.ts +1 -1
  357. package/dist/schema/sync-layer4.js +1 -282
  358. package/dist/schema/task-status.d.ts +168 -0
  359. package/dist/schema/task-status.js +1 -0
  360. package/dist/schema/trust/index.js +1 -314
  361. package/dist/schema/utils/guard-parser.js +1 -419
  362. package/dist/schema/utils/guard-query-utils.js +1 -46
  363. package/dist/schema/utils/node-parser.js +1 -369
  364. package/dist/schema/utils/object-type-utils.js +1 -35
  365. package/dist/schema/utils/permission-index-utils.js +1 -7
  366. package/dist/schema/utils/permission-machine-check.js +1 -121
  367. package/dist/schema/utils/skills-recommendation.js +1 -77
  368. package/dist/schema-query/index.js +1 -810
  369. package/dist/schemas/account_operation.output.json +5 -2
  370. package/dist/schemas/bridge_operation.output.json +5 -2
  371. package/dist/schemas/evaluation_operation.output.json +782 -0
  372. package/dist/schemas/evaluation_operation.schema.json +990 -0
  373. package/dist/schemas/index.json +25 -1
  374. package/dist/schemas/intent_radar.output.json +232 -0
  375. package/dist/schemas/intent_radar.schema.json +138 -0
  376. package/dist/schemas/local_info_operation.output.json +5 -2
  377. package/dist/schemas/local_mark_operation.output.json +5 -2
  378. package/dist/schemas/messenger_operation.output.json +5 -2
  379. package/dist/schemas/onchain_events.output.json +5 -2
  380. package/dist/schemas/onchain_operations.output.json +5 -2
  381. package/dist/schemas/onchain_operations.schema.json +6 -6
  382. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  383. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  384. package/dist/schemas/onchain_operations_service.schema.json +3 -3
  385. package/dist/schemas/onchain_table_data.output.json +6 -3
  386. package/dist/schemas/persona_operation.output.json +392 -0
  387. package/dist/schemas/persona_operation.schema.json +250 -0
  388. package/dist/schemas/project_operation.output.json +28 -8
  389. package/dist/schemas/query_task_status.output.json +115 -0
  390. package/dist/schemas/query_task_status.schema.json +24 -0
  391. package/dist/schemas/query_toolkit.output.json +9 -6
  392. package/dist/schemas/trust_score.schema.json +1 -1
  393. package/dist/schemas/wowok_buildin_info.output.json +132 -0
  394. package/dist/schemas/wowok_buildin_info.schema.json +14 -0
  395. package/dist/telemetry/index.js +1 -112
  396. package/dist/telemetry/redact.js +1 -23
  397. package/dist/telemetry/storage.js +1 -80
  398. package/dist/tools/handlers/bridge.js +1 -1
  399. package/dist/tools/handlers/config.js +1 -74
  400. package/dist/tools/handlers/evaluation.d.ts +2 -0
  401. package/dist/tools/handlers/evaluation.js +1 -0
  402. package/dist/tools/handlers/file-export.js +1 -90
  403. package/dist/tools/handlers/intent-radar.d.ts +2 -0
  404. package/dist/tools/handlers/intent-radar.js +1 -0
  405. package/dist/tools/handlers/local.js +1 -53
  406. package/dist/tools/handlers/messenger.js +1 -188
  407. package/dist/tools/handlers/onchain.js +1 -1082
  408. package/dist/tools/handlers/persona.d.ts +4 -0
  409. package/dist/tools/handlers/persona.js +1 -0
  410. package/dist/tools/handlers/project.js +1 -211
  411. package/dist/tools/handlers/query.js +1 -434
  412. package/dist/tools/handlers/schema-query.js +1 -176
  413. package/dist/tools/handlers/task-status.d.ts +0 -168
  414. package/dist/tools/handlers/task-status.js +1 -55
  415. package/dist/tools/handlers/trust.js +1 -380
  416. package/dist/tools/handlers/wip.js +1 -90
  417. package/dist/tools/index.js +1 -1306
  418. package/dist/tools/retry.js +1 -85
  419. package/dist/tools/rules-hook.js +1 -23
  420. package/dist/tools/shared.js +1 -130
  421. package/dist/tools/types.js +1 -1
  422. package/dist/tools/upgrade-check.d.ts +19 -0
  423. package/dist/tools/upgrade-check.js +1 -0
  424. package/dist/tools/wip-deploy-assist.d.ts +1 -1
  425. package/dist/tools/wip-deploy-assist.js +1 -278
  426. package/dist/tools/wrap.js +1 -500
  427. package/package.json +5 -3
@@ -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};}