@wowok/agent-mcp 3.1.7 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/dist/config/exposure.d.ts +10 -10
  2. package/dist/config/judgment.d.ts +25 -25
  3. package/dist/config/rule-engine.d.ts +25 -25
  4. package/dist/customer/user-preferences.d.ts +2 -2
  5. package/dist/evaluation/arbitration-game.js +1 -1
  6. package/dist/evaluation/capability.d.ts +1 -1
  7. package/dist/evaluation/extract.js +1 -1
  8. package/dist/evaluation/match-operation.js +1 -1
  9. package/dist/extensions/industry-pack.d.ts +3 -2
  10. package/dist/extensions/industry-pack.js +1 -1
  11. package/dist/extensions/modes.js +1 -1
  12. package/dist/extensions/registry.js +1 -1
  13. package/dist/extensions/types.d.ts +1 -0
  14. package/dist/graph/onchain/analyze.js +1 -1
  15. package/dist/graph/onchain/analyze.spec.js +1 -1
  16. package/dist/graph/onchain/edge-schema.js +1 -1
  17. package/dist/graph/onchain/extract.js +1 -1
  18. package/dist/graph/onchain/field-manifest.js +1 -1
  19. package/dist/graph/onchain/project-relationship.js +1 -1
  20. package/dist/graph/onchain/types.d.ts +1 -1
  21. package/dist/harness/recover.js +1 -1
  22. package/dist/keeper/KeeperScan.d.ts +2 -1
  23. package/dist/keeper/KeeperScan.js +1 -1
  24. package/dist/keeper/detectors.d.ts +9 -0
  25. package/dist/keeper/detectors.js +1 -1
  26. package/dist/keeper/keeper.spec.js +1 -1
  27. package/dist/keeper/types.d.ts +1 -1
  28. package/dist/keeper/types.js +1 -1
  29. package/dist/knowledge/allocation-ledger.d.ts +4 -1
  30. package/dist/knowledge/allocation-ledger.js +1 -1
  31. package/dist/knowledge/allocation-puzzle.d.ts +2 -0
  32. package/dist/knowledge/allocation-puzzle.js +1 -1
  33. package/dist/knowledge/allocation-risk.d.ts +1 -1
  34. package/dist/knowledge/allocation-risk.js +1 -1
  35. package/dist/knowledge/arb-risk.d.ts +3 -1
  36. package/dist/knowledge/arb-risk.js +1 -1
  37. package/dist/knowledge/arbitration-ledger.js +1 -1
  38. package/dist/knowledge/arbitration-risk.js +1 -1
  39. package/dist/knowledge/arbitration-templates.d.ts +1 -0
  40. package/dist/knowledge/arbitration-templates.js +1 -1
  41. package/dist/knowledge/audit-rules.d.ts +13 -2
  42. package/dist/knowledge/audit-rules.js +1 -1
  43. package/dist/knowledge/baselines/rules/allocation.json +50 -1
  44. package/dist/knowledge/baselines/rules/arb.json +20 -1
  45. package/dist/knowledge/baselines/rules/arbitration.json +27 -0
  46. package/dist/knowledge/baselines/rules/guard.json +75 -2
  47. package/dist/knowledge/baselines/rules/machine.json +38 -13
  48. package/dist/knowledge/baselines/rules/order.json +2 -2
  49. package/dist/knowledge/builtin-templates.d.ts +3 -1
  50. package/dist/knowledge/builtin-templates.js +1 -1
  51. package/dist/knowledge/event-semantics.js +1 -1
  52. package/dist/knowledge/fund-layer.js +1 -1
  53. package/dist/knowledge/getting-started.js +1 -1
  54. package/dist/knowledge/guard-anchor-reach.d.ts +19 -0
  55. package/dist/knowledge/guard-anchor-reach.js +1 -0
  56. package/dist/knowledge/guard-bindings.js +1 -1
  57. package/dist/knowledge/guard-design-patterns.d.ts +1 -1
  58. package/dist/knowledge/guard-design-patterns.js +1 -1
  59. package/dist/knowledge/guard-ledger.js +1 -1
  60. package/dist/knowledge/guard-lint.js +1 -1
  61. package/dist/knowledge/guard-render.d.ts +6 -0
  62. package/dist/knowledge/guard-render.js +1 -1
  63. package/dist/knowledge/guard-risk.js +1 -1
  64. package/dist/knowledge/guard-submission-prompt.d.ts +6 -0
  65. package/dist/knowledge/guard-submission-prompt.js +1 -1
  66. package/dist/knowledge/guard-templates.d.ts +1 -1
  67. package/dist/knowledge/guard-templates.js +1 -1
  68. package/dist/knowledge/index.d.ts +4 -4
  69. package/dist/knowledge/index.js +1 -1
  70. package/dist/knowledge/industry-generalizer.js +1 -1
  71. package/dist/knowledge/industry-registry.d.ts +1 -1
  72. package/dist/knowledge/industry-registry.js +1 -1
  73. package/dist/knowledge/jsonrpc-enum.js +1 -1
  74. package/dist/knowledge/machine-ledger.js +1 -1
  75. package/dist/knowledge/machine-risk.js +1 -1
  76. package/dist/knowledge/machine-templates.js +1 -1
  77. package/dist/knowledge/order-ledger.js +1 -1
  78. package/dist/knowledge/order-templates.js +1 -1
  79. package/dist/knowledge/permission-ledger.js +1 -1
  80. package/dist/knowledge/release-sentinel.d.ts +12 -0
  81. package/dist/knowledge/release-sentinel.js +1 -0
  82. package/dist/knowledge/repository-write-semantics.d.ts +27 -0
  83. package/dist/knowledge/repository-write-semantics.js +1 -0
  84. package/dist/knowledge/rule-node-analyzers.d.ts +6 -0
  85. package/dist/knowledge/rule-node-analyzers.js +1 -1
  86. package/dist/knowledge/safety-rules.d.ts +5 -1
  87. package/dist/knowledge/safety-rules.js +1 -1
  88. package/dist/knowledge/scenario-modes.d.ts +10 -1
  89. package/dist/knowledge/scenario-modes.js +1 -1
  90. package/dist/knowledge/service-allocation-semantics.d.ts +36 -0
  91. package/dist/knowledge/service-allocation-semantics.js +1 -0
  92. package/dist/knowledge/strategy-manuals.d.ts +3 -5
  93. package/dist/knowledge/strategy-manuals.js +1 -1
  94. package/dist/knowledge/template-loader.d.ts +28 -12
  95. package/dist/knowledge/template-loader.js +1 -1
  96. package/dist/knowledge/template-registry.js +1 -1
  97. package/dist/knowledge/template-scanner.js +1 -1
  98. package/dist/knowledge/tools-reference.js +1 -1
  99. package/dist/knowledge/workflow-guidance.d.ts +26 -0
  100. package/dist/knowledge/workflow-guidance.js +1 -1
  101. package/dist/monitor/MonitorLoop.js +1 -1
  102. package/dist/participation/allocation-advice.d.ts +38 -0
  103. package/dist/participation/allocation-advice.js +1 -0
  104. package/dist/participation/radar-core.d.ts +2 -0
  105. package/dist/persona/types.d.ts +3 -2
  106. package/dist/persona/types.js +1 -1
  107. package/dist/playbooks/service-build/business-puzzle.js +1 -1
  108. package/dist/playbooks/service-build/intent-analyzer.js +1 -1
  109. package/dist/playbooks/service-build/merchant-guide.d.ts +70 -63
  110. package/dist/playbooks/service-build/merchant-guide.js +1 -1
  111. package/dist/playbooks/service-build/migration-planner.js +1 -1
  112. package/dist/playbooks/service-build/mode-actions.d.ts +5 -0
  113. package/dist/playbooks/service-build/mode-actions.js +1 -1
  114. package/dist/playbooks/service-build/participation-radar.js +1 -1
  115. package/dist/playbooks/service-build/semantic-graph.d.ts +1 -0
  116. package/dist/playbooks/service-build/semantic-graph.js +1 -1
  117. package/dist/playbooks/service-build/service-quote.d.ts +2 -0
  118. package/dist/playbooks/service-build/service-quote.js +1 -0
  119. package/dist/relationship/derivation.d.ts +1 -1
  120. package/dist/safety/confirm-gate.js +1 -1
  121. package/dist/schema/benchmark-migration/index.d.ts +30 -8
  122. package/dist/schema/benchmark-migration/index.js +1 -1
  123. package/dist/schema/call/allocation.d.ts +6 -3
  124. package/dist/schema/call/arbitration.js +1 -1
  125. package/dist/schema/call/base.js +1 -1
  126. package/dist/schema/call/guard.d.ts +8 -8
  127. package/dist/schema/call/machine.d.ts +56 -0
  128. package/dist/schema/call/machine.js +1 -1
  129. package/dist/schema/call/order.js +1 -1
  130. package/dist/schema/call/payment.js +1 -1
  131. package/dist/schema/call/semantic.js +1 -1
  132. package/dist/schema/call/service.d.ts +84 -22
  133. package/dist/schema/call/service.js +1 -1
  134. package/dist/schema/common/index.js +1 -1
  135. package/dist/schema/common/tokentype-short-probe.spec.js +1 -0
  136. package/dist/schema/evaluation/index.d.ts +8 -80
  137. package/dist/schema/evaluation/index.js +1 -1
  138. package/dist/schema/goal/index.d.ts +9 -42
  139. package/dist/schema/goal/planning.d.ts +25 -60
  140. package/dist/schema/goal/planning.js +1 -1
  141. package/dist/schema/intent-radar/index.d.ts +2 -20
  142. package/dist/schema/intent-radar/index.js +1 -1
  143. package/dist/schema/interaction/index.d.ts +1 -1
  144. package/dist/schema/keeper/index.d.ts +3 -0
  145. package/dist/schema/keeper/index.js +1 -1
  146. package/dist/schema/local/index.js +1 -1
  147. package/dist/schema/operations.d.ts +74 -14
  148. package/dist/schema/persona/index.d.ts +279 -384
  149. package/dist/schema/persona/index.js +1 -1
  150. package/dist/schema/query/bi.d.ts +149 -10
  151. package/dist/schema/query/bi.js +1 -1
  152. package/dist/schema/query/index.d.ts +35 -16
  153. package/dist/schema/query/index.js +1 -1
  154. package/dist/schema/schema-query/index.d.ts +4 -4
  155. package/dist/schema/schema-version.js +1 -1
  156. package/dist/schema/watch/index.d.ts +2 -2
  157. package/dist/schema-query-impl/index.d.ts +1 -0
  158. package/dist/schema-query-impl/index.js +1 -1
  159. package/dist/schemas/account_operation.output.json +2 -2
  160. package/dist/schemas/benchmark_migration_operation.output.json +116 -2
  161. package/dist/schemas/benchmark_migration_operation.schema.json +2 -10
  162. package/dist/schemas/bridge_operation.output.json +2 -2
  163. package/dist/schemas/evaluation_operation.schema.json +7 -70
  164. package/dist/schemas/goal_operation.schema.json +6 -39
  165. package/dist/schemas/index.json +1 -1
  166. package/dist/schemas/intent_radar.output.json +4 -20
  167. package/dist/schemas/keeper_operation.output.json +2 -2
  168. package/dist/schemas/keeper_operation.schema.json +9 -4
  169. package/dist/schemas/local_history_operation.output.json +2 -2
  170. package/dist/schemas/local_info_operation.output.json +2 -2
  171. package/dist/schemas/local_mark_operation.output.json +2 -2
  172. package/dist/schemas/messenger_operation.output.json +2 -2
  173. package/dist/schemas/monitor_events.output.json +2 -2
  174. package/dist/schemas/monitor_subscription.output.json +2 -2
  175. package/dist/schemas/onchain_events.output.json +2 -2
  176. package/dist/schemas/onchain_operations.output.json +6 -6
  177. package/dist/schemas/onchain_operations.schema.json +227 -54
  178. package/dist/schemas/onchain_operations_allocation.schema.json +11 -10
  179. package/dist/schemas/onchain_operations_arbitration.schema.json +13 -13
  180. package/dist/schemas/onchain_operations_machine.schema.json +27 -5
  181. package/dist/schemas/onchain_operations_order.schema.json +1 -1
  182. package/dist/schemas/onchain_operations_payment.schema.json +2 -2
  183. package/dist/schemas/onchain_operations_reward.schema.json +1 -1
  184. package/dist/schemas/onchain_operations_service.schema.json +171 -21
  185. package/dist/schemas/onchain_operations_treasury.schema.json +1 -1
  186. package/dist/schemas/onchain_table_data.output.json +57 -4
  187. package/dist/schemas/persona_operation.output.json +11 -88
  188. package/dist/schemas/persona_operation.schema.json +4 -32
  189. package/dist/schemas/query_toolkit.output.json +320 -22
  190. package/dist/schemas/query_toolkit.schema.json +53 -0
  191. package/dist/tools/handlers/benchmark-migration.js +1 -1
  192. package/dist/tools/handlers/config.js +1 -1
  193. package/dist/tools/handlers/dispatch-expectations.spec.js +1 -1
  194. package/dist/tools/handlers/keeper.d.ts +1 -1
  195. package/dist/tools/handlers/onchain.js +1 -1
  196. package/dist/tools/handlers/query.js +1 -1
  197. package/dist/tools/handlers/schema-query.js +1 -1
  198. package/dist/tools/index.js +1 -1
  199. package/dist/tools/move-fn-index.gen.js +1 -1
  200. package/dist/tools/registry/business.js +1 -1
  201. package/dist/tools/wrap.js +1 -1
  202. package/package.json +2 -2
  203. package/dist/knowledge/alloc-audit-policy.spec.js +0 -1
  204. package/dist/knowledge/event-semantics.spec.d.ts +0 -1
  205. package/dist/knowledge/event-semantics.spec.js +0 -1
  206. package/dist/knowledge/facts-sync.spec.d.ts +0 -1
  207. package/dist/knowledge/facts-sync.spec.js +0 -1
  208. package/dist/knowledge/guard-design-patterns.spec.d.ts +0 -1
  209. package/dist/knowledge/guard-design-patterns.spec.js +0 -1
  210. package/dist/knowledge/guard-eval.spec.d.ts +0 -1
  211. package/dist/knowledge/guard-eval.spec.js +0 -1
  212. package/dist/knowledge/rule-node-analyzers.spec.d.ts +0 -1
  213. package/dist/knowledge/rule-node-analyzers.spec.js +0 -1
  214. package/dist/knowledge/safety-rules.extract-amount.spec.d.ts +0 -1
  215. package/dist/knowledge/safety-rules.extract-amount.spec.js +0 -1
  216. package/dist/knowledge/template-loader.spec.d.ts +0 -1
  217. package/dist/knowledge/template-loader.spec.js +0 -1
  218. package/dist/knowledge/template-scanner.spec.d.ts +0 -1
  219. package/dist/knowledge/template-scanner.spec.js +0 -1
  220. /package/dist/{knowledge/alloc-audit-policy.spec.d.ts → schema/common/tokentype-short-probe.spec.d.ts} +0 -0
@@ -1 +1 @@
1
- import{rootOf}from'./extract.js';const MAX_MANAGED_TOTAL=0x3c,MAX_ORDERS=0x28,MAX_DEMANDS=0x14,MAX_ALLOCATIONS=0x28,MAX_CONTACTS=0x14,MAX_MACHINES=0xa,MAX_ARB_SERVICES=0xf;function fld(a,b){if(!a?.['raw'])return undefined;const c=rootOf(a['raw']);return c[b];}function addrList(a,b){const c=fld(a,b);return(Array['isArray'](c)?c:[])['filter'](d=>typeof d==='string');}function outEdges(a,b,c){return(a['out']['get'](b['toLowerCase']())??[])['filter'](d=>d['schema']===c);}function rawOf(a,b){return b?a['nodes']['get'](b['toLowerCase']()):undefined;}function managedTargets(a,b){const c=new Set();for(const d of[...outEdges(a,b,'permission.core_binding'),...outEdges(a,b,'permission.tx_binding')]){c['add'](d['to']);}return[...c]['map'](f=>a['nodes']['get'](f))['filter'](f=>!!f&&f['kind']==='object');}function mapMode(a){if(a===0x1||a==='Rate')return'Rate';if(a===0x2||a==='Surplus')return'Surplus';return'Amount';}export function projectRelationshipFacts(b,c){const f=c['toLowerCase'](),g=outEdges(b,f,'eoa.permission'),h=[],i=new Map();for(const C of g){const D=b['nodes']['get'](C['to']);if(!D)continue;const E=outEdges(b,D['id'],'permission.entity')['map'](H=>({'address':H['to'],'perm_indices':H['payload']?.['permIndices']??[]})),F=managedTargets(b,D['id']),G=F['filter'](H=>!!H['objectType'])['map'](H=>({'object_type':H['objectType'],'address':H['id']}));for(const H of G){if(i['size']>=MAX_MANAGED_TOTAL)break;i['set'](H['address']['toLowerCase'](),H);}h['push']({'address':D['id'],'owner':fld(D,'owner')??'','admins':addrList(D,'admin'),'entities':E,'anchor_role_bits':C['payload']?.['roleBits'],'managed_objects':G});}const j=I=>[...i['values']()]['filter'](J=>J['object_type']===I)['map'](J=>J['address']),k=j('Service'),l=j('Machine')['slice'](0x0,MAX_MACHINES),n=j('Demand')['slice'](0x0,MAX_DEMANDS),p=j('Contact')['slice'](0x0,MAX_CONTACTS),q=j('Arbitration'),r=new Map();for(const I of outEdges(b,f,'eoa.order'))r['set'](I['to'],'buyer');for(const J of k){for(const K of outEdges(b,J,'service.order'))r['set'](K['to'],'merchant');}const t=[],u={};for(const L of[...r['keys']()]['slice'](0x0,MAX_ORDERS)){const M=rawOf(b,L);if(!M||M['objectType']!=='Order')continue;const N=fld(M,'service')??'';t['push']({'address':M['id'],'owner':fld(M,'owner')??fld(M,'builder')??'','agents':addrList(M,'agent'),'service':N,'amount':fld(M,'amount'),'allocation':fld(M,'allocation'),'dispute_arbitrations':addrList(M,'dispute'),'claimed_by':fld(M,'claimed_by')??null});if(N){const O=rawOf(b,N),P=outEdges(b,N,'service.permission')[0x0]?.['to'],Q=rawOf(b,P),R=fld(Q,'owner');if(R)u[O?.['id']??N['toLowerCase']()]=R;}}const v=n['map'](S=>{const T=rawOf(b,S),U=outEdges(b,S,'demand.permission')[0x0]?.['to'],V=fld(rawOf(b,U),'owner')??'',W=outEdges(b,S,'demand.presenter')['map'](Y=>({'address':Y['to'],'service':typeof Y['payload']?.['service']==='string'?Y['payload']['service']:undefined,'acceptance_score':typeof Y['payload']?.['score']==='number'?Y['payload']['score']:undefined})),X=(fld(T,'guards')??[])['map'](Y=>typeof Y==='string'?Y:Y?.['guard'])['filter'](Y=>typeof Y==='string');return{'address':T['id'],'owner':V,'presenters':W,'rewards':addrList(T,'rewards'),'guards':X};}),w=[...new Set(t['map'](S=>S['allocation'])['filter'](S=>!!S))]['slice'](0x0,MAX_ALLOCATIONS),x=w['map'](S=>{const T=rawOf(b,S),U=fld(T,'allocators')??rootOf(T['raw']),V=Array['isArray'](U)?U:Array['isArray'](U?.['allocators'])?U['allocators']:[],W=V['flatMap'](X=>(Array['isArray'](X?.['sharing'])?X['sharing']:[])['map'](Y=>({'who':Y?.['who']??Y,'mode':mapMode(Y?.['mode']),'sharing':Y?.['sharing']!=null?String(Y['sharing']):undefined,'guard':typeof X?.['guard']==='string'?X['guard']:undefined})));return{'address':T['id'],'owner':fld(T,'owner'),'sharing':W};}),y=p['map'](S=>{const T=rawOf(b,S),U=outEdges(b,S,'contact.permission')[0x0]?.['to'],V=fld(rawOf(b,U),'owner')??'',W=(fld(T,'ims')??[])['map'](X=>typeof X==='string'?X:X?.['at'])['filter'](X=>typeof X==='string');return{'address':T['id'],'ims':W,'owner':V};}),z=l['map'](S=>{const T=rawOf(b,S),U=outEdges(b,S,'machine.permission')[0x0]?.['to'],V=S['toLowerCase']()+'::node::',W=b['edges']['filter'](X=>X['schema']==='wf.transition'&&X['from']['startsWith'](V))['map'](X=>({'node':X['payload']?.['prevNode']??'','next_node':X['payload']?.['node']??'','forward_name':X['payload']?.['forward']??'','named_operator':X['payload']?.['namedOperator']??null,'permission_index':X['payload']?.['permissionIndex']??null,'guard':X['payload']?.['guard']??null}));return{'address':T['id'],'permission_address':U,'forwards':W};}),A=new Map();for(const S of t){const T=r['get'](S['address']['toLowerCase']())??'buyer';for(const U of S['dispute_arbitrations']??[])A['set'](U['toLowerCase'](),T);}const B=[];for(const [V,W]of A){const X=rawOf(b,V);if(!X)continue;const Y=(fld(X,'voted')??[])['map'](Z=>({'address':typeof Z?.['voter']==='string'?Z['voter']:'','weight':typeof Z?.['weight']==='number'?Z['weight']:undefined}))['filter'](Z=>Z['address']['length']>0x0);B['push']({'address':X['id'],'object_kind':'case','voters':Y,'order':fld(X,'order'),'arbitration':fld(X,'arbitration'),'anchor_side':W,'bound_services':[]});}for(const Z of q['slice'](0x0,MAX_ARB_SERVICES)){if(A['has'](Z['toLowerCase']()))continue;B['push']({'address':Z,'object_kind':'service','voters':[],'bound_services':[]});}return{'anchor':f,'permissions':h,'machines':z,'orders':t,'demands':v,'allocations':x,'contacts':y,'arbitrations':B,'service_owners':u};}
1
+ import{rootOf}from'./extract.js';const MAX_MANAGED_TOTAL=0x3c,MAX_ORDERS=0x28,MAX_DEMANDS=0x14,MAX_ALLOCATIONS=0x28,MAX_CONTACTS=0x14,MAX_MACHINES=0xa,MAX_ARB_SERVICES=0xf;function fld(a,b){if(!a?.['raw'])return undefined;const c=rootOf(a['raw']);return c[b];}function addrList(a,b){const c=fld(a,b);return(Array['isArray'](c)?c:[])['filter'](d=>typeof d==='string');}function outEdges(a,b,c){return(a['out']['get'](b['toLowerCase']())??[])['filter'](d=>d['schema']===c);}function rawOf(a,b){return b?a['nodes']['get'](b['toLowerCase']()):undefined;}function managedTargets(a,b){const c=new Set();for(const d of[...outEdges(a,b,'permission.core_binding'),...outEdges(a,b,'permission.tx_binding')]){c['add'](d['to']);}return[...c]['map'](f=>a['nodes']['get'](f))['filter'](f=>!!f&&f['kind']==='object');}function mapMode(a){if(a===0x1||a==='Rate')return'Rate';if(a===0x2||a==='Surplus')return'Surplus';if(a===0x3||a==='RateGross')return'RateGross';return'Amount';}export function projectRelationshipFacts(b,c){const f=c['toLowerCase'](),g=outEdges(b,f,'eoa.permission'),h=[],i=new Map();for(const C of g){const D=b['nodes']['get'](C['to']);if(!D)continue;const E=outEdges(b,D['id'],'permission.entity')['map'](H=>({'address':H['to'],'perm_indices':H['payload']?.['permIndices']??[]})),F=managedTargets(b,D['id']),G=F['filter'](H=>!!H['objectType'])['map'](H=>({'object_type':H['objectType'],'address':H['id']}));for(const H of G){if(i['size']>=MAX_MANAGED_TOTAL)break;i['set'](H['address']['toLowerCase'](),H);}h['push']({'address':D['id'],'owner':fld(D,'owner')??'','admins':addrList(D,'admin'),'entities':E,'anchor_role_bits':C['payload']?.['roleBits'],'managed_objects':G});}const j=I=>[...i['values']()]['filter'](J=>J['object_type']===I)['map'](J=>J['address']),k=j('Service'),l=j('Machine')['slice'](0x0,MAX_MACHINES),n=j('Demand')['slice'](0x0,MAX_DEMANDS),p=j('Contact')['slice'](0x0,MAX_CONTACTS),q=j('Arbitration'),r=new Map();for(const I of outEdges(b,f,'eoa.order'))r['set'](I['to'],'buyer');for(const J of k){for(const K of outEdges(b,J,'service.order'))r['set'](K['to'],'merchant');}const t=[],u={};for(const L of[...r['keys']()]['slice'](0x0,MAX_ORDERS)){const M=rawOf(b,L);if(!M||M['objectType']!=='Order')continue;const N=fld(M,'service')??'';t['push']({'address':M['id'],'owner':fld(M,'owner')??fld(M,'builder')??'','agents':addrList(M,'agent'),'service':N,'amount':fld(M,'amount'),'allocation':fld(M,'allocation'),'dispute_arbitrations':addrList(M,'dispute'),'claimed_by':fld(M,'claimed_by')??null});if(N){const O=rawOf(b,N),P=outEdges(b,N,'service.permission')[0x0]?.['to'],Q=rawOf(b,P),R=fld(Q,'owner');if(R)u[O?.['id']??N['toLowerCase']()]=R;}}const v=n['map'](S=>{const T=rawOf(b,S),U=outEdges(b,S,'demand.permission')[0x0]?.['to'],V=fld(rawOf(b,U),'owner')??'',W=outEdges(b,S,'demand.presenter')['map'](Y=>({'address':Y['to'],'service':typeof Y['payload']?.['service']==='string'?Y['payload']['service']:undefined,'acceptance_score':typeof Y['payload']?.['score']==='number'?Y['payload']['score']:undefined})),X=(fld(T,'guards')??[])['map'](Y=>typeof Y==='string'?Y:Y?.['guard'])['filter'](Y=>typeof Y==='string');return{'address':T['id'],'owner':V,'presenters':W,'rewards':addrList(T,'rewards'),'guards':X};}),w=[...new Set(t['map'](S=>S['allocation'])['filter'](S=>!!S))]['slice'](0x0,MAX_ALLOCATIONS),x=w['map'](S=>{const T=rawOf(b,S),U=fld(T,'allocators')??rootOf(T['raw']),V=Array['isArray'](U)?U:Array['isArray'](U?.['allocators'])?U['allocators']:[],W=V['flatMap'](X=>(Array['isArray'](X?.['sharing'])?X['sharing']:[])['map'](Y=>({'who':Y?.['who']??Y,'mode':mapMode(Y?.['mode']),'sharing':Y?.['sharing']!=null?String(Y['sharing']):undefined,'guard':typeof X?.['guard']==='string'?X['guard']:undefined})));return{'address':T['id'],'owner':fld(T,'owner'),'sharing':W};}),y=p['map'](S=>{const T=rawOf(b,S),U=outEdges(b,S,'contact.permission')[0x0]?.['to'],V=fld(rawOf(b,U),'owner')??'',W=(fld(T,'ims')??[])['map'](X=>typeof X==='string'?X:X?.['at'])['filter'](X=>typeof X==='string');return{'address':T['id'],'ims':W,'owner':V};}),z=l['map'](S=>{const T=rawOf(b,S),U=outEdges(b,S,'machine.permission')[0x0]?.['to'],V=S['toLowerCase']()+'::node::',W=b['edges']['filter'](X=>X['schema']==='wf.transition'&&X['from']['startsWith'](V))['map'](X=>({'node':X['payload']?.['prevNode']??'','next_node':X['payload']?.['node']??'','forward_name':X['payload']?.['forward']??'','named_operator':X['payload']?.['namedOperator']??null,'permission_index':X['payload']?.['permissionIndex']??null,'guard':X['payload']?.['guard']??null}));return{'address':T['id'],'permission_address':U,'forwards':W};}),A=new Map();for(const S of t){const T=r['get'](S['address']['toLowerCase']())??'buyer';for(const U of S['dispute_arbitrations']??[])A['set'](U['toLowerCase'](),T);}const B=[];for(const [V,W]of A){const X=rawOf(b,V);if(!X)continue;const Y=(fld(X,'voted')??[])['map'](Z=>({'address':typeof Z?.['voter']==='string'?Z['voter']:'','weight':typeof Z?.['weight']==='number'?Z['weight']:undefined}))['filter'](Z=>Z['address']['length']>0x0);B['push']({'address':X['id'],'object_kind':'case','voters':Y,'order':fld(X,'order'),'arbitration':fld(X,'arbitration'),'anchor_side':W,'bound_services':[]});}for(const Z of q['slice'](0x0,MAX_ARB_SERVICES)){if(A['has'](Z['toLowerCase']()))continue;B['push']({'address':Z,'object_kind':'service','voters':[],'bound_services':[]});}return{'anchor':f,'permissions':h,'machines':z,'orders':t,'demands':v,'allocations':x,'contacts':y,'arbitrations':B,'service_owners':u};}
@@ -40,7 +40,7 @@ export type Retention = "complete" | "bounded_exact" | "bounded_window" | "membe
40
40
  export interface TopoEdgePayload {
41
41
  amount?: string;
42
42
  coinType?: string;
43
- mode?: 0 | 1 | 2;
43
+ mode?: 0 | 1 | 2 | 3;
44
44
  guard?: string;
45
45
  roleBits?: number;
46
46
  node?: string;
@@ -1 +1 @@
1
- export const RECOVERY_RULES={'insufficient_balance':{'error_code':'insufficient_balance','strategy':'claim_faucet','max_attempts':0x3,'automation':'semi','detail':'1.\x20Testnet:\x20claim\x20WOW\x20from\x20the\x20faucet\x202.\x20Mainnet:\x20transfer\x20ETH/USDT/USDC/WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge\x20(query\x20active\x20EVM\x20account\x20→\x20top\x20up\x20from\x20external\x20wallet\x20→\x20confirm\x20→\x20cross-chain)\x203.\x20Point\x20the\x20user\x20to\x20the\x20live\x20airdrop\x20page\x20(https://wowok.net/airdrop.html)\x20for\x20the\x20current\x20round\x204.\x20Retry\x20original\x20operation','user_prompt':'Insufficient\x20balance\x20for\x20gas\x20or\x20operation.\x20How\x20to\x20obtain\x20WOW\x20tokens:\x20(1)\x20Testnet\x20—\x20claim\x20WOW\x20from\x20the\x20faucet\x20(https://faucet.testnet.wowok.net);\x20all\x20merchant\x20and\x20order\x20testing\x20can\x20use\x20WOW\x20as\x20the\x20payment\x20token.\x20(2)\x20Mainnet\x20—\x20transfer\x20ETH\x20/\x20USDT\x20/\x20USDC\x20/\x20WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge:\x20first\x20query\x20the\x20active\x20EVM\x20account\x20(bridge_operation\x20query_active_evm_account,\x20auto-generated\x20on\x20first\x20use),\x20then\x20transfer\x20from\x20an\x20external\x20wallet\x20(e.g.\x20MetaMask)\x20to\x20that\x20address,\x20confirm\x20the\x20balance\x20arrived,\x20and\x20cross-chain\x20to\x20WOW\x20mainnet\x20(bridge_operation\x20cross_chain_evm_to_wow).\x20(3)\x20WOW\x20airdrop:\x20current\x20round\x20status,\x20pool\x20and\x20eligibility\x20are\x20published\x20live\x20at\x20https://wowok.net/airdrop.html\x20(referral:\x20https://wowok.net/refer.html)\x20—\x20open\x20that\x20page\x20rather\x20than\x20assuming\x20a\x20round\x20is\x20live\x20or\x20closed.\x20Query\x20wowok_buildin_info\x20with\x20info=\x27funding\x20guidance\x27\x20for\x20the\x20canonical\x20funding\x20guidance.'},'stock_exhausted':{'error_code':'stock_exhausted','strategy':'adjust_params','max_attempts':0x1,'automation':'semi','detail':'Merchant-side\x20inventory\x20shortfall\x20(Move\x20service:16\x20E_STOCK_NOT_ENOUGH)\x20—\x20NOT\x20a\x20buyer\x20balance\x20problem,\x20so\x20a\x20faucet\x20claim\x20will\x20NOT\x20help.\x201.\x20Reduce\x20the\x20purchase\x20quantity\x20to\x20the\x20item\x27s\x20remaining\x20stock\x202.\x20Pick\x20another\x20sale\x20item\x203.\x20Ask\x20the\x20merchant\x20to\x20restock,\x20then\x20retry','user_prompt':'The\x20sale\x20item\x27s\x20stock\x20is\x20exhausted\x20for\x20the\x20requested\x20quantity.\x20Reduce\x20the\x20quantity,\x20choose\x20another\x20item,\x20or\x20ask\x20the\x20merchant\x20to\x20restock.'},'sale_suspended':{'error_code':'sale_suspended','strategy':'adjust_params','max_attempts':0x1,'automation':'semi','detail':'The\x20merchant\x20suspended\x20this\x20sale\x20item\x20(Move\x20service:34\x20E_SALE_SUSPENDED).\x201.\x20Pick\x20another\x20(non-suspended)\x20item\x202.\x20Contact\x20the\x20merchant\x20to\x20resume\x20the\x20sale,\x20then\x20retry','user_prompt':'The\x20sale\x20item\x20is\x20suspended\x20by\x20the\x20merchant.\x20Please\x20choose\x20another\x20item\x20or\x20contact\x20the\x20merchant.'},'discount_invalid':{'error_code':'discount_invalid','strategy':'adjust_params','max_attempts':0x1,'automation':'semi','detail':'The\x20discount\x20is\x20outside\x20its\x20[time_start,\x20time_end]\x20validity\x20window\x20(Move\x20service:35\x20E_DISCOUNT_TIME_INVALID).\x201.\x20Retry\x20without\x20the\x20discount\x202.\x20Ask\x20the\x20merchant\x20for\x20a\x20fresh\x20discount,\x20then\x20retry','user_prompt':'The\x20discount\x20is\x20not\x20valid\x20at\x20the\x20current\x20time\x20(outside\x20its\x20validity\x20window).\x20Buy\x20without\x20the\x20discount\x20or\x20ask\x20the\x20merchant\x20for\x20a\x20new\x20one.'},'rate_limit':{'error_code':'rate_limit','strategy':'retry','max_attempts':0x5,'automation':'full','detail':'Rate\x20limit\x20hit\x20(HTTP\x20429).\x20Exponential\x20backoff\x20retry:\x202s\x20/\x204s\x20/\x208s\x20/\x2016s\x20/\x2032s.\x20Avoid\x20parallel\x20calls\x20while\x20the\x20limit\x20window\x20is\x20active.'},'gas_exceeded':{'error_code':'gas_exceeded','strategy':'adjust_params','max_attempts':0x3,'automation':'semi','detail':'Gas\x20budget\x20exceeded.\x201.\x20Increase\x20the\x20gas_budget\x20parameter\x202.\x20Reduce\x20the\x20operation\x20size\x20(fewer\x20objects\x20per\x20transaction)\x203.\x20Retry\x20the\x20original\x20operation','user_prompt':'Gas\x20budget\x20exceeded.\x20Increase\x20the\x20gas\x20budget\x20or\x20reduce\x20the\x20operation\x20size,\x20then\x20retry.'},'bcs_error':{'error_code':'bcs_error','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'BCS\x20serialization/deserialization\x20error\x20—\x20a\x20parameter\x20does\x20not\x20match\x20the\x20expected\x20type/structure.\x201.\x20Query\x20the\x20operation\x20schema\x20(schema_query)\x202.\x20Fix\x20the\x20offending\x20parameter\x20type\x20(e.g.\x20BigInt\x20vs\x20number,\x20vector\x20element\x20type)\x203.\x20Retry','user_prompt':'A\x20parameter\x20failed\x20serialization.\x20Check\x20the\x20parameter\x20types\x20against\x20the\x20schema\x20and\x20retry.'},'signature_error':{'error_code':'signature_error','strategy':'switch_account','max_attempts':0x2,'automation':'semi','detail':'Signature\x20verification\x20failed.\x201.\x20Verify\x20the\x20account\x20is\x20not\x20suspended\x202.\x20Check\x20the\x20network\x20matches\x20the\x20account\x27s\x203.\x20Switch\x20to\x20a\x20healthy\x20account\x20and\x20retry','user_prompt':'Signature\x20verification\x20failed.\x20The\x20account\x20may\x20be\x20suspended\x20or\x20misconfigured.\x20Switch\x20accounts\x20or\x20check\x20the\x20configuration\x20and\x20retry.'},'config_error':{'error_code':'config_error','strategy':'escalate_human','max_attempts':0x1,'automation':'manual','detail':'Local\x20configuration\x20error\x20(network\x20not\x20specified,\x20persistent\x20storage\x20not\x20set).\x201.\x20Show\x20the\x20user\x20which\x20configuration\x20is\x20missing\x202.\x20Guide\x20the\x20user\x20through\x20the\x20account_operation/config\x20setup\x203.\x20Retry\x20after\x20the\x20user\x20fixes\x20it','user_prompt':'Local\x20configuration\x20is\x20incomplete.\x20Please\x20finish\x20the\x20account/network\x20setup\x20and\x20retry.'},'wip_verification_failed':{'error_code':'wip_verification_failed','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'WIP\x20file\x20not\x20publicly\x20reachable\x20/\x20hash\x20mismatch.\x201.\x20Upload\x20via\x20the\x20wip\x20storage\x20service\x20(wip_file\x20type=\x27upload\x27\x20—\x20official\x20free\x20store\x20or\x20storage=\x27custom\x27)\x202.\x20Or\x20deploy\x20to\x20a\x20public\x20URL\x20(GitHub\x20Pages\x20/\x20IPFS\x20/\x20own\x20site)\x203.\x20Update\x20the\x20sale\x27s\x20wip\x20URL\x204.\x20Re-run\x20the\x20operation','user_prompt':'The\x20WIP\x20file\x20could\x20not\x20be\x20verified\x20from\x20a\x20public\x20URL.\x20Upload\x20it\x20with\x20wip_file\x20type=\x27upload\x27\x20(official\x20free\x20store\x20or\x20your\x20own\x20service)\x20or\x20deploy\x20it\x20(GitHub\x20Pages\x20/\x20IPFS),\x20update\x20the\x20sale\x27s\x20WIP\x20URL,\x20and\x20retry.'},'wip_storage_unavailable':{'error_code':'wip_storage_unavailable','strategy':'retry','max_attempts':0x3,'automation':'full','detail':'Transient\x20wip\x20storage\x20transport\x20failure.\x201.\x20Retry\x20the\x20same\x20request\x20with\x20bounded\x20backoff\x202.\x20Large\x20WIP\x20files\x20are\x20network-sensitive:\x20compress\x20images\x20before\x20generate\x20(each\x20image\x20<=\x202MB,\x20total\x20<=\x2010MB)\x203.\x20Check\x20connectivity\x20to\x20the\x20storage\x20base\x20URL\x20if\x20retries\x20keep\x20failing','user_prompt':'The\x20wip\x20storage\x20request\x20failed\x20due\x20to\x20a\x20network\x20problem.\x20Retry\x20the\x20upload;\x20if\x20it\x20keeps\x20failing,\x20reduce\x20the\x20file\x20size\x20or\x20check\x20connectivity.'},'network_error':{'error_code':'network_error','strategy':'retry','max_attempts':0x5,'automation':'full','detail':'Exponential\x20backoff\x20retry:\x201s\x20/\x202s\x20/\x204s\x20/\x208s\x20/\x2016s.\x20Switch\x20RPC\x20node\x20if\x20available.'},'transaction_expired':{'error_code':'transaction_expired','strategy':'retry','max_attempts':0x3,'automation':'full','detail':'The\x20transaction\x20expired\x20before\x20execution\x20(epoch\x20boundary\x20or\x20validator/gateway\x20outage)\x20—\x20it\x20did\x20NOT\x20land\x20and\x20nothing\x20was\x20committed.\x20Bounded\x20backoff\x20retry:\x2010s\x20/\x2030s\x20/\x2060s,\x20resubmit\x20the\x20SAME\x20call\x20unchanged.\x20If\x20a\x20dry_run\x20passes\x20while\x20the\x20real\x20call\x20keeps\x20failing,\x20the\x20fault\x20is\x20chain-side\x20—\x20wait\x20it\x20out.\x20Verify\x20with\x20onchain_events\x20if\x20unsure.'},'guard_rejected':{'error_code':'guard_rejected','strategy':'fill_submission','max_attempts':0x2,'automation':'semi','detail':'1.\x20Parse\x20Guard\x20table\x20structure\x202.\x20If\x20the\x20Guard\x20defines\x20submission\x20items,\x20fill\x20them\x20and\x20resubmit\x20with\x20call_with_submission\x203.\x20If\x20it\x20defines\x20none,\x20the\x20rule\x20evaluated\x20false\x20—\x20adjust\x20the\x20call\x27s\x20parameters\x20(signer/query/state)\x20or\x20change\x20the\x20Guard\x20(docs#40)','user_prompt':'Guard\x20verification\x20rejected.\x20If\x20the\x20Guard\x20defines\x20submission\x20items,\x20fill\x20in\x20the\x20required\x20submission\x20data\x20and\x20resubmit;\x20if\x20it\x20defines\x20none,\x20the\x20Guard\x20rule\x20evaluated\x20false\x20—\x20adjust\x20this\x20call\x27s\x20parameters\x20or\x20change\x20the\x20Guard\x20rule.'},'time_lock_not_elapsed':{'error_code':'time_lock_not_elapsed','strategy':'wait_and_retry','max_attempts':0x1,'automation':'semi','detail':'1.\x20Verify\x20Service\x20is\x20paused\x20(bPaused=true).\x20If\x20not,\x20submit\x20pause=true\x20first.\x202.\x20Wait\x20until\x20paused_time\x20+\x20setting_lock_duration\x20<=\x20current\x20clock.\x203.\x20Retry\x20the\x20original\x20operation.\x20Do\x20NOT\x20recreate\x20the\x20object.','user_prompt':'Service\x20setting_lock_duration\x20has\x20not\x20elapsed\x20since\x20the\x20Service\x20was\x20paused.\x20Please\x20pause\x20the\x20Service\x20if\x20it\x20is\x20not\x20already\x20paused,\x20wait\x20for\x20the\x20lock\x20duration\x20to\x20elapse,\x20then\x20retry.'},'immutable_violation':{'error_code':'immutable_violation','strategy':'recreate','max_attempts':0x1,'automation':'semi','detail':'1.\x20Stop\x20modification\x20attempt\x202.\x20Evaluate\x20creating\x20a\x20new\x20object\x20as\x20replacement\x203.\x20Re-plan\x20affected\x20phases','user_prompt':'Cannot\x20modify\x20an\x20immutable\x20object.\x20A\x20new\x20object\x20must\x20be\x20created\x20as\x20a\x20replacement.\x20Confirm\x20to\x20proceed\x20with\x20recreation.'},'permission_denied':{'error_code':'permission_denied','strategy':'switch_account','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20object\x27s\x20permission_guard\x202.\x20List\x20accounts\x20with\x20permission\x203.\x20Switch\x20account\x20or\x20prompt\x20user\x20to\x20add\x20permission','user_prompt':'Current\x20account\x20lacks\x20permission\x20for\x20this\x20operation.\x20Switch\x20to\x20an\x20authorized\x20account\x20or\x20update\x20the\x20Permission\x20object.'},'object_not_found':{'error_code':'object_not_found','strategy':'query_and_retry','max_attempts':0x3,'automation':'semi','detail':'1.\x20Verify\x20the\x20referenced\x20name/ID\x20spelling\x20(local_mark_list)\x20and\x20that\x20the\x20object\x20exists\x20on\x20the\x20current\x20network\x202.\x20If\x20recently\x20created,\x20re-query\x20the\x20object\x20(may\x20be\x20sync\x20delay)\x203.\x20If\x20truly\x20absent,\x20search\x20for\x20similar\x20objects\x204.\x20Prompt\x20user\x20to\x20reselect','user_prompt':'Referenced\x20object\x20not\x20found.\x20First\x20verify\x20the\x20name/ID\x20spelling\x20and\x20that\x20the\x20object\x20exists\x20on\x20the\x20current\x20network;\x20if\x20it\x20was\x20created\x20recently,\x20this\x20may\x20be\x20a\x20synchronization\x20delay\x20—\x20retry.\x20If\x20the\x20issue\x20persists,\x20please\x20select\x20a\x20valid\x20object.'},'state_conflict':{'error_code':'state_conflict','strategy':'adjust_params','max_attempts':0x2,'automation':'full','detail':'1.\x20Query\x20object\x27s\x20current\x20true\x20state\x202.\x20Update\x20ODG\x20status\x20annotations\x203.\x20Adjust\x20subsequent\x20operations\x20(e.g.,\x20skip\x20completed\x20steps)'},'invalid_parameter':{'error_code':'invalid_parameter','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20the\x20relevant\x20schema\x202.\x20Auto-fix\x20obvious\x20errors\x20(e.g.,\x20BigInt\x20vs\x20string)\x203.\x20If\x20unfixable,\x20prompt\x20user','user_prompt':'Parameter\x20validation\x20failed.\x20Please\x20check\x20the\x20parameter\x20types\x20and\x20values\x20against\x20the\x20schema\x20and\x20retry.'},'unknown':{'error_code':'unknown','strategy':'escalate_human','max_attempts':0x1,'automation':'manual','detail':'1.\x20Report\x20full\x20error\x20context\x20to\x20the\x20user\x202.\x20Escalate\x20to\x20human\x20intervention\x203.\x20Flag\x20for\x20error-classification\x20rule\x20addition','user_prompt':'An\x20unclassified\x20error\x20occurred.\x20Please\x20review\x20the\x20error\x20details\x20and\x20contact\x20support\x20if\x20needed.'}};const operationAttempts=new Map();function getAttemptCount(a,b){const c=operationAttempts['get'](a);if(!c)return 0x0;return c['get'](b)??0x0;}function incrementAttempt(a,b){!operationAttempts['has'](a)&&operationAttempts['set'](a,new Map());const c=operationAttempts['get'](a),d=(c['get'](b)??0x0)+0x1;return c['set'](b,d),d;}function getTotalAttempts(a){const b=operationAttempts['get'](a);if(!b)return 0x0;let c=0x0;for(const d of b['values']())c+=d;return c;}export function resetAttempts(a){operationAttempts['delete'](a);}export function recover(a,b,c){const d=RECOVERY_RULES[a]??RECOVERY_RULES['unknown'],e=0x5,f=getTotalAttempts(b),g=getAttemptCount(b,a);if(f>=e)return{'strategy':'stop','should_retry':![],'max_attempts':e,'current_attempt':f,'detail':'Total\x20retry\x20limit\x20('+e+')\x20reached\x20for\x20operation\x20'+b+'.\x20Escalating\x20to\x20human\x20intervention.','user_prompt':'Maximum\x20retry\x20attempts\x20reached.\x20Manual\x20intervention\x20required.'};if(g>=d['max_attempts'])return{'strategy':'escalate_human','should_retry':![],'max_attempts':d['max_attempts'],'current_attempt':g,'detail':'Per-error-code\x20retry\x20limit\x20('+d['max_attempts']+')\x20reached\x20for\x20'+a+'.\x20Escalating\x20to\x20human.','user_prompt':'Recovery\x20attempts\x20for\x20'+a+'\x20exhausted.\x20Manual\x20intervention\x20required.'};const h=incrementAttempt(b,a);return{'strategy':d['strategy'],'should_retry':d['automation']==='full'||h<d['max_attempts'],'max_attempts':d['max_attempts'],'current_attempt':h,'adjusted_params':d['adjusted_params'],'user_prompt':d['user_prompt'],'detail':d['detail']};}export function getBackoffDelay(a){return Math['pow'](0x2,a-0x1)*0x3e8;}
1
+ export const RECOVERY_RULES={'insufficient_balance':{'error_code':'insufficient_balance','strategy':'claim_faucet','max_attempts':0x3,'automation':'semi','detail':'1.\x20Testnet:\x20claim\x20WOW\x20from\x20the\x20faucet\x202.\x20Mainnet:\x20transfer\x20ETH/USDT/USDC/WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge\x20(query\x20active\x20EVM\x20account\x20→\x20top\x20up\x20from\x20external\x20wallet\x20→\x20confirm\x20→\x20cross-chain)\x203.\x20Point\x20the\x20user\x20to\x20the\x20live\x20airdrop\x20page\x20(https://wowok.net/airdrop.html)\x20for\x20the\x20current\x20round\x204.\x20Retry\x20original\x20operation','user_prompt':'Insufficient\x20balance\x20for\x20gas\x20or\x20operation.\x20How\x20to\x20obtain\x20WOW\x20tokens:\x20(1)\x20Testnet\x20—\x20claim\x20WOW\x20from\x20the\x20faucet\x20(https://faucet.testnet.wowok.net);\x20all\x20merchant\x20and\x20order\x20testing\x20can\x20use\x20WOW\x20as\x20the\x20payment\x20token.\x20(2)\x20Mainnet\x20—\x20transfer\x20ETH\x20/\x20USDT\x20/\x20USDC\x20/\x20WBTC\x20via\x20the\x20ETH\x20mainnet\x20cross-chain\x20bridge:\x20first\x20query\x20the\x20active\x20EVM\x20account\x20(bridge_operation\x20query_active_evm_account,\x20auto-generated\x20on\x20first\x20use),\x20then\x20transfer\x20from\x20an\x20external\x20wallet\x20(e.g.\x20MetaMask)\x20to\x20that\x20address,\x20confirm\x20the\x20balance\x20arrived,\x20and\x20cross-chain\x20to\x20WOW\x20mainnet\x20(bridge_operation\x20cross_chain_evm_to_wow).\x20(3)\x20WOW\x20airdrop:\x20current\x20round\x20status,\x20pool\x20and\x20eligibility\x20are\x20published\x20live\x20at\x20https://wowok.net/airdrop.html\x20(referral:\x20https://wowok.net/refer.html)\x20—\x20open\x20that\x20page\x20rather\x20than\x20assuming\x20a\x20round\x20is\x20live\x20or\x20closed.\x20Query\x20wowok_buildin_info\x20with\x20info=\x27funding\x20guidance\x27\x20for\x20the\x20canonical\x20funding\x20guidance.'},'stock_exhausted':{'error_code':'stock_exhausted','strategy':'adjust_params','max_attempts':0x1,'automation':'semi','detail':'Merchant-side\x20inventory\x20shortfall\x20(Move\x20service:16\x20E_STOCK_NOT_ENOUGH)\x20—\x20NOT\x20a\x20buyer\x20balance\x20problem,\x20so\x20a\x20faucet\x20claim\x20will\x20NOT\x20help.\x201.\x20Reduce\x20the\x20purchase\x20quantity\x20to\x20the\x20item\x27s\x20remaining\x20stock\x202.\x20Pick\x20another\x20sale\x20item\x203.\x20Ask\x20the\x20merchant\x20to\x20restock,\x20then\x20retry','user_prompt':'The\x20sale\x20item\x27s\x20stock\x20is\x20exhausted\x20for\x20the\x20requested\x20quantity.\x20Reduce\x20the\x20quantity,\x20choose\x20another\x20item,\x20or\x20ask\x20the\x20merchant\x20to\x20restock.'},'sale_suspended':{'error_code':'sale_suspended','strategy':'adjust_params','max_attempts':0x1,'automation':'semi','detail':'The\x20merchant\x20suspended\x20this\x20sale\x20item\x20(Move\x20service:34\x20E_SALE_SUSPENDED).\x201.\x20Pick\x20another\x20(non-suspended)\x20item\x202.\x20Contact\x20the\x20merchant\x20to\x20resume\x20the\x20sale,\x20then\x20retry','user_prompt':'The\x20sale\x20item\x20is\x20suspended\x20by\x20the\x20merchant.\x20Please\x20choose\x20another\x20item\x20or\x20contact\x20the\x20merchant.'},'discount_invalid':{'error_code':'discount_invalid','strategy':'adjust_params','max_attempts':0x1,'automation':'semi','detail':'The\x20discount\x20is\x20outside\x20its\x20[time_start,\x20time_end]\x20validity\x20window\x20(Move\x20service:35\x20E_DISCOUNT_TIME_INVALID).\x201.\x20Retry\x20without\x20the\x20discount\x202.\x20Ask\x20the\x20merchant\x20for\x20a\x20fresh\x20discount,\x20then\x20retry','user_prompt':'The\x20discount\x20is\x20not\x20valid\x20at\x20the\x20current\x20time\x20(outside\x20its\x20validity\x20window).\x20Buy\x20without\x20the\x20discount\x20or\x20ask\x20the\x20merchant\x20for\x20a\x20new\x20one.'},'rate_limit':{'error_code':'rate_limit','strategy':'retry','max_attempts':0x5,'automation':'full','detail':'Rate\x20limit\x20hit\x20(HTTP\x20429).\x20Exponential\x20backoff\x20retry:\x202s\x20/\x204s\x20/\x208s\x20/\x2016s\x20/\x2032s.\x20Avoid\x20parallel\x20calls\x20while\x20the\x20limit\x20window\x20is\x20active.'},'gas_exceeded':{'error_code':'gas_exceeded','strategy':'adjust_params','max_attempts':0x3,'automation':'semi','detail':'Gas\x20budget\x20exceeded.\x201.\x20Increase\x20the\x20gas_budget\x20parameter\x202.\x20Reduce\x20the\x20operation\x20size\x20(fewer\x20objects\x20per\x20transaction)\x203.\x20Retry\x20the\x20original\x20operation','user_prompt':'Gas\x20budget\x20exceeded.\x20Increase\x20the\x20gas\x20budget\x20or\x20reduce\x20the\x20operation\x20size,\x20then\x20retry.'},'bcs_error':{'error_code':'bcs_error','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'BCS\x20serialization/deserialization\x20error\x20—\x20a\x20parameter\x20does\x20not\x20match\x20the\x20expected\x20type/structure.\x201.\x20Query\x20the\x20operation\x20schema\x20(schema_query)\x202.\x20Fix\x20the\x20offending\x20parameter\x20type\x20(e.g.\x20BigInt\x20vs\x20number,\x20vector\x20element\x20type)\x203.\x20Retry','user_prompt':'A\x20parameter\x20failed\x20serialization.\x20Check\x20the\x20parameter\x20types\x20against\x20the\x20schema\x20and\x20retry.'},'signature_error':{'error_code':'signature_error','strategy':'switch_account','max_attempts':0x2,'automation':'semi','detail':'Signature\x20verification\x20failed.\x201.\x20Verify\x20the\x20account\x20is\x20not\x20suspended\x202.\x20Check\x20the\x20network\x20matches\x20the\x20account\x27s\x203.\x20Switch\x20to\x20a\x20healthy\x20account\x20and\x20retry','user_prompt':'Signature\x20verification\x20failed.\x20The\x20account\x20may\x20be\x20suspended\x20or\x20misconfigured.\x20Switch\x20accounts\x20or\x20check\x20the\x20configuration\x20and\x20retry.'},'config_error':{'error_code':'config_error','strategy':'escalate_human','max_attempts':0x1,'automation':'manual','detail':'Local\x20configuration\x20error\x20(network\x20not\x20specified,\x20persistent\x20storage\x20not\x20set).\x201.\x20Show\x20the\x20user\x20which\x20configuration\x20is\x20missing\x202.\x20Guide\x20the\x20user\x20through\x20the\x20account_operation/config\x20setup\x203.\x20Retry\x20after\x20the\x20user\x20fixes\x20it','user_prompt':'Local\x20configuration\x20is\x20incomplete.\x20Please\x20finish\x20the\x20account/network\x20setup\x20and\x20retry.'},'wip_verification_failed':{'error_code':'wip_verification_failed','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'WIP\x20file\x20not\x20publicly\x20reachable\x20/\x20hash\x20mismatch.\x201.\x20Upload\x20via\x20the\x20wip\x20storage\x20service\x20(wip_file\x20type=\x27upload\x27\x20—\x20official\x20free\x20store\x20or\x20storage=\x27custom\x27)\x202.\x20Or\x20deploy\x20to\x20a\x20public\x20URL\x20(GitHub\x20Pages\x20/\x20IPFS\x20/\x20own\x20site)\x203.\x20Update\x20the\x20sale\x27s\x20wip\x20URL\x204.\x20Re-run\x20the\x20operation','user_prompt':'The\x20WIP\x20file\x20could\x20not\x20be\x20verified\x20from\x20a\x20public\x20URL.\x20Upload\x20it\x20with\x20wip_file\x20type=\x27upload\x27\x20(official\x20free\x20store\x20or\x20your\x20own\x20service)\x20or\x20deploy\x20it\x20(GitHub\x20Pages\x20/\x20IPFS),\x20update\x20the\x20sale\x27s\x20WIP\x20URL,\x20and\x20retry.'},'wip_storage_unavailable':{'error_code':'wip_storage_unavailable','strategy':'retry','max_attempts':0x3,'automation':'full','detail':'Transient\x20wip\x20storage\x20transport\x20failure.\x201.\x20Retry\x20the\x20same\x20request\x20with\x20bounded\x20backoff\x202.\x20Large\x20WIP\x20files\x20are\x20network-sensitive:\x20compress\x20images\x20before\x20generate\x20(each\x20image\x20<=\x202MB,\x20total\x20<=\x2010MB)\x203.\x20Check\x20connectivity\x20to\x20the\x20storage\x20base\x20URL\x20if\x20retries\x20keep\x20failing','user_prompt':'The\x20wip\x20storage\x20request\x20failed\x20due\x20to\x20a\x20network\x20problem.\x20Retry\x20the\x20upload;\x20if\x20it\x20keeps\x20failing,\x20reduce\x20the\x20file\x20size\x20or\x20check\x20connectivity.'},'network_error':{'error_code':'network_error','strategy':'retry','max_attempts':0x5,'automation':'full','detail':'Exponential\x20backoff\x20retry:\x201s\x20/\x202s\x20/\x204s\x20/\x208s\x20/\x2016s.\x20Switch\x20RPC\x20node\x20if\x20available.'},'transaction_expired':{'error_code':'transaction_expired','strategy':'retry','max_attempts':0x3,'automation':'full','detail':'The\x20transaction\x20expired\x20before\x20execution\x20(epoch\x20boundary\x20or\x20validator/gateway\x20outage)\x20—\x20it\x20did\x20NOT\x20land\x20and\x20nothing\x20was\x20committed.\x20Bounded\x20backoff\x20retry:\x2010s\x20/\x2030s\x20/\x2060s,\x20resubmit\x20the\x20SAME\x20call\x20unchanged.\x20If\x20a\x20dry_run\x20passes\x20while\x20the\x20real\x20call\x20keeps\x20failing,\x20the\x20fault\x20is\x20chain-side\x20—\x20wait\x20it\x20out.\x20Verify\x20with\x20onchain_events\x20if\x20unsure.'},'guard_rejected':{'error_code':'guard_rejected','strategy':'fill_submission','max_attempts':0x2,'automation':'semi','detail':'1.\x20Parse\x20Guard\x20table\x20structure\x202.\x20If\x20the\x20Guard\x20defines\x20submission\x20items,\x20fill\x20them\x20and\x20resubmit\x20with\x20call_with_submission\x203.\x20If\x20it\x20defines\x20none,\x20the\x20rule\x20evaluated\x20false\x20—\x20adjust\x20the\x20call\x27s\x20parameters\x20(signer/query/state)\x20or\x20change\x20the\x20Guard\x20(docs#40)\x204.\x20When\x20the\x20failure\x20is\x20passport\x20E_VERIFY_FAILED\x20and\x20a\x20submission\x20was\x20supplied,\x20the\x20response\x20appends\x20a\x20\x27Guard\x20diagnosis\x20(dry-run)\x27\x20line\x20naming\x20the\x20first\x20failing\x20impact\x20guard\x20—\x20fix\x20that\x20guard\x20first','user_prompt':'Guard\x20verification\x20rejected.\x20If\x20the\x20Guard\x20defines\x20submission\x20items,\x20fill\x20in\x20the\x20required\x20submission\x20data\x20and\x20resubmit;\x20if\x20it\x20defines\x20none,\x20the\x20Guard\x20rule\x20evaluated\x20false\x20—\x20adjust\x20this\x20call\x27s\x20parameters\x20or\x20change\x20the\x20Guard\x20rule.\x20When\x20the\x20response\x20includes\x20a\x20\x27Guard\x20diagnosis\x20(dry-run)\x27\x20line,\x20it\x20names\x20the\x20first\x20failing\x20impact\x20guard\x20—\x20address\x20that\x20guard\x20first.'},'time_lock_not_elapsed':{'error_code':'time_lock_not_elapsed','strategy':'wait_and_retry','max_attempts':0x1,'automation':'semi','detail':'1.\x20Verify\x20Service\x20is\x20paused\x20(bPaused=true).\x20If\x20not,\x20submit\x20pause=true\x20first.\x202.\x20Wait\x20until\x20paused_time\x20+\x20setting_lock_duration\x20<=\x20current\x20clock.\x203.\x20Retry\x20the\x20original\x20operation.\x20Do\x20NOT\x20recreate\x20the\x20object.','user_prompt':'Service\x20setting_lock_duration\x20has\x20not\x20elapsed\x20since\x20the\x20Service\x20was\x20paused.\x20Please\x20pause\x20the\x20Service\x20if\x20it\x20is\x20not\x20already\x20paused,\x20wait\x20for\x20the\x20lock\x20duration\x20to\x20elapse,\x20then\x20retry.'},'immutable_violation':{'error_code':'immutable_violation','strategy':'recreate','max_attempts':0x1,'automation':'semi','detail':'1.\x20Stop\x20modification\x20attempt\x202.\x20Evaluate\x20creating\x20a\x20new\x20object\x20as\x20replacement\x203.\x20Re-plan\x20affected\x20phases','user_prompt':'Cannot\x20modify\x20an\x20immutable\x20object.\x20A\x20new\x20object\x20must\x20be\x20created\x20as\x20a\x20replacement.\x20Confirm\x20to\x20proceed\x20with\x20recreation.'},'permission_denied':{'error_code':'permission_denied','strategy':'switch_account','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20object\x27s\x20permission_guard\x202.\x20List\x20accounts\x20with\x20permission\x203.\x20Switch\x20account\x20or\x20prompt\x20user\x20to\x20add\x20permission','user_prompt':'Current\x20account\x20lacks\x20permission\x20for\x20this\x20operation.\x20Switch\x20to\x20an\x20authorized\x20account\x20or\x20update\x20the\x20Permission\x20object.'},'object_not_found':{'error_code':'object_not_found','strategy':'query_and_retry','max_attempts':0x3,'automation':'semi','detail':'1.\x20Verify\x20the\x20referenced\x20name/ID\x20spelling\x20(local_mark_list)\x20and\x20that\x20the\x20object\x20exists\x20on\x20the\x20current\x20network\x202.\x20If\x20recently\x20created,\x20re-query\x20the\x20object\x20(may\x20be\x20sync\x20delay)\x203.\x20If\x20truly\x20absent,\x20search\x20for\x20similar\x20objects\x204.\x20Prompt\x20user\x20to\x20reselect','user_prompt':'Referenced\x20object\x20not\x20found.\x20First\x20verify\x20the\x20name/ID\x20spelling\x20and\x20that\x20the\x20object\x20exists\x20on\x20the\x20current\x20network;\x20if\x20it\x20was\x20created\x20recently,\x20this\x20may\x20be\x20a\x20synchronization\x20delay\x20—\x20retry.\x20If\x20the\x20issue\x20persists,\x20please\x20select\x20a\x20valid\x20object.'},'state_conflict':{'error_code':'state_conflict','strategy':'adjust_params','max_attempts':0x2,'automation':'full','detail':'1.\x20Query\x20object\x27s\x20current\x20true\x20state\x202.\x20Update\x20ODG\x20status\x20annotations\x203.\x20Adjust\x20subsequent\x20operations\x20(e.g.,\x20skip\x20completed\x20steps)'},'invalid_parameter':{'error_code':'invalid_parameter','strategy':'adjust_params','max_attempts':0x2,'automation':'semi','detail':'1.\x20Query\x20the\x20relevant\x20schema\x202.\x20Auto-fix\x20obvious\x20errors\x20(e.g.,\x20BigInt\x20vs\x20string)\x203.\x20If\x20unfixable,\x20prompt\x20user','user_prompt':'Parameter\x20validation\x20failed.\x20Please\x20check\x20the\x20parameter\x20types\x20and\x20values\x20against\x20the\x20schema\x20and\x20retry.'},'unknown':{'error_code':'unknown','strategy':'escalate_human','max_attempts':0x1,'automation':'manual','detail':'1.\x20Report\x20full\x20error\x20context\x20to\x20the\x20user\x202.\x20Escalate\x20to\x20human\x20intervention\x203.\x20Flag\x20for\x20error-classification\x20rule\x20addition','user_prompt':'An\x20unclassified\x20error\x20occurred.\x20Please\x20review\x20the\x20error\x20details\x20and\x20contact\x20support\x20if\x20needed.'}};const operationAttempts=new Map();function getAttemptCount(a,b){const c=operationAttempts['get'](a);if(!c)return 0x0;return c['get'](b)??0x0;}function incrementAttempt(a,b){!operationAttempts['has'](a)&&operationAttempts['set'](a,new Map());const c=operationAttempts['get'](a),d=(c['get'](b)??0x0)+0x1;return c['set'](b,d),d;}function getTotalAttempts(a){const b=operationAttempts['get'](a);if(!b)return 0x0;let c=0x0;for(const d of b['values']())c+=d;return c;}export function resetAttempts(a){operationAttempts['delete'](a);}export function recover(a,b,c){const d=RECOVERY_RULES[a]??RECOVERY_RULES['unknown'],e=0x5,f=getTotalAttempts(b),g=getAttemptCount(b,a);if(f>=e)return{'strategy':'stop','should_retry':![],'max_attempts':e,'current_attempt':f,'detail':'Total\x20retry\x20limit\x20('+e+')\x20reached\x20for\x20operation\x20'+b+'.\x20Escalating\x20to\x20human\x20intervention.','user_prompt':'Maximum\x20retry\x20attempts\x20reached.\x20Manual\x20intervention\x20required.'};if(g>=d['max_attempts'])return{'strategy':'escalate_human','should_retry':![],'max_attempts':d['max_attempts'],'current_attempt':g,'detail':'Per-error-code\x20retry\x20limit\x20('+d['max_attempts']+')\x20reached\x20for\x20'+a+'.\x20Escalating\x20to\x20human.','user_prompt':'Recovery\x20attempts\x20for\x20'+a+'\x20exhausted.\x20Manual\x20intervention\x20required.'};const h=incrementAttempt(b,a);return{'strategy':d['strategy'],'should_retry':d['automation']==='full'||h<d['max_attempts'],'max_attempts':d['max_attempts'],'current_attempt':h,'adjusted_params':d['adjusted_params'],'user_prompt':d['user_prompt'],'detail':d['detail']};}export function getBackoffDelay(a){return Math['pow'](0x2,a-0x1)*0x3e8;}
@@ -1,5 +1,5 @@
1
1
  import type { ScopeSnapshot } from "../monitor/types.js";
2
- import { type PaymentDetectorDeps, type ProgressDetectorDeps } from "./detectors.js";
2
+ import { type PaymentDetectorDeps, type ProgressDetectorDeps, type SettlementDetectorDeps } from "./detectors.js";
3
3
  import { type KeeperStore } from "./KeeperStore.js";
4
4
  import { type KeeperTask } from "./types.js";
5
5
  export interface KeeperExecutionOutcome {
@@ -11,6 +11,7 @@ export interface KeeperScanDeps {
11
11
  store: KeeperStore;
12
12
  payment: PaymentDetectorDeps;
13
13
  progress: ProgressDetectorDeps;
14
+ settlement: SettlementDetectorDeps;
14
15
  execute(input: {
15
16
  operation_type: string;
16
17
  data: Record<string, unknown>;
@@ -1 +1 @@
1
- import{handleOnchainOperations}from'../tools/handlers/onchain.js';import{detectPaymentUnclaimed,detectProgressActionable,realPaymentDetectorDeps,realProgressDetectorDeps}from'./detectors.js';import{keeperStore}from'./KeeperStore.js';import{AUTO_EXECUTABLE_DETECTORS}from'./types.js';async function defaultExecute(a){try{const b=await handleOnchainOperations({'operation_type':a['operation_type'],'data':a['data'],'env':{'account':a['account'],'network':a['network'],'confirmed':!![],'user_intent_phrases':['keeper\x20auto-execute\x20via\x20'+a['via']]}}),c=b?.['structuredContent']?.['result'];if(c?.['type']==='transaction'&&typeof c?.['digest']==='string')return{'ok':!![],'digest':c['digest']};const d=c?.['type']==='error'&&typeof c?.['error']==='string'?c['error']:typeof b?.['structuredContent']?.['message']==='string'?b['structuredContent']['message']:'execution\x20did\x20not\x20produce\x20a\x20transaction';return{'ok':![],'error':String(d)['slice'](0x0,0x1f4)};}catch(f){return{'ok':![],'error':String(f?.['message']??f)['slice'](0x0,0x1f4)};}}export function realKeeperScanDeps(){return{'store':keeperStore,'payment':realPaymentDetectorDeps(),'progress':realProgressDetectorDeps(),'execute':defaultExecute,'now':()=>Date['now'](),'logger':a=>console['error']('[keeper]\x20'+a)};}export async function runKeeperScan(a,b,c,d){const f=c['now'](),g={'scanned':![],'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0,'auto_executed':0x0,'auto_failed':0x0,'duration_ms':0x0};try{const h=await c['store']['getConfig'](a);if(!h['enabled'])return g['reason']='disabled',g;const i=await c['store']['getLastScanAt'](a);if(!d?.['force']&&c['now']()-i<h['scan_interval_ms'])return g['reason']='interval',g;await c['store']['setLastScanAt'](a,c['now']()),g['scanned']=!![];if(h['detectors']['payment_unclaimed'])try{const l=await detectPaymentUnclaimed((b['accounts']??[])['slice'](0x0,h['max_scan_objects']),a,c['payment']),m=await c['store']['upsertDesired'](a,'payment_unclaimed',l,c['now']());g['opened']+=m['opened'],g['refreshed']+=m['refreshed'],g['revived']+=m['revived'],g['superseded']+=m['superseded'];}catch(n){c['logger']('scan\x20'+a+':\x20payment_unclaimed\x20detector\x20failed:\x20'+String(n?.['message']??n));}if(h['detectors']['progress_actionable'])try{const o=await detectProgressActionable(b,a,c['progress'],h['max_scan_objects']),p=await c['store']['upsertDesired'](a,'progress_actionable',o,c['now']());g['opened']+=p['opened'],g['refreshed']+=p['refreshed'],g['revived']+=p['revived'],g['superseded']+=p['superseded'];}catch(q){c['logger']('scan\x20'+a+':\x20progress_actionable\x20detector\x20failed:\x20'+String(q?.['message']??q));}const j=await c['store']['listTasks'](a,{'status':'pending'});let k=h['max_auto_execute_per_scan'];for(const s of j){if(k<=0x0)break;if(!s['operation'])continue;if(!AUTO_EXECUTABLE_DETECTORS['includes'](s['detector']))continue;if(s['last_auto_attempt_at']&&c['now']()-s['last_auto_attempt_at']<h['auto_retry_cooldown_ms'])continue;const t=await c['store']['matchingAutoRules'](a,s['detector'],s['beneficiary']),u=t[0x0];if(!u)continue;k--,await c['store']['markAutoAttempt'](a,s['id'],c['now']());const v=await c['execute']({'operation_type':s['operation']['operation_type'],'data':s['operation']['data'],'account':s['beneficiary'],'network':a,'via':'rule\x20'+u['id']});v['ok']?(await c['store']['resolveTask'](a,s['id'],'auto_executed',c['now'](),v['digest']?'tx\x20'+v['digest']:'executed',u['id']),g['auto_executed']++,c['logger']('auto-executed\x20'+s['dedupe_key']+'\x20via\x20rule\x20'+u['id']+'\x20('+(v['digest']??'no\x20digest')+')')):(await c['store']['resolveTask'](a,s['id'],'execute_failed',c['now'](),v['error']??'unknown\x20execution\x20error',u['id']),g['auto_failed']++,c['logger']('auto-execute\x20failed\x20for\x20'+s['dedupe_key']+':\x20'+(v['error']??'unknown')));}return g;}catch(w){return c['logger']('scan\x20'+a+'\x20failed:\x20'+String(w?.['message']??w)),g['reason']='error',g;}finally{g['duration_ms']=c['now']()-f;}}export async function executeKeeperTask(a,b,c){if(!b['operation'])return{'ok':![],'error':'This\x20task\x20is\x20reminder-only\x20(no\x20keeper-executable\x20operation).\x20'+'Follow\x20its\x20detail\x20text\x20—\x20progress\x20forwards\x20are\x20advanced\x20via\x20workflow_operation.'};const d=await c['execute']({'operation_type':b['operation']['operation_type'],'data':b['operation']['data'],'account':b['beneficiary'],'network':a,'via':'manual'});return d['ok']?await c['store']['resolveTask'](a,b['id'],'manual_executed',c['now'](),d['digest']?'tx\x20'+d['digest']:'executed'):await c['store']['resolveTask'](a,b['id'],'execute_failed',c['now'](),d['error']),d;}
1
+ import{handleOnchainOperations}from'../tools/handlers/onchain.js';import{detectPaymentUnclaimed,detectProgressActionable,detectSettlementPending,realPaymentDetectorDeps,realProgressDetectorDeps,realSettlementDetectorDeps}from'./detectors.js';import{keeperStore}from'./KeeperStore.js';import{AUTO_EXECUTABLE_DETECTORS}from'./types.js';async function defaultExecute(a){try{const b=await handleOnchainOperations({'operation_type':a['operation_type'],'data':a['data'],'env':{'account':a['account'],'network':a['network'],'confirmed':!![],'user_intent_phrases':['keeper\x20auto-execute\x20via\x20'+a['via']]}}),c=b?.['structuredContent']?.['result'];if(c?.['type']==='transaction'&&typeof c?.['digest']==='string')return{'ok':!![],'digest':c['digest']};const d=c?.['type']==='error'&&typeof c?.['error']==='string'?c['error']:typeof b?.['structuredContent']?.['message']==='string'?b['structuredContent']['message']:'execution\x20did\x20not\x20produce\x20a\x20transaction';return{'ok':![],'error':String(d)['slice'](0x0,0x1f4)};}catch(f){return{'ok':![],'error':String(f?.['message']??f)['slice'](0x0,0x1f4)};}}export function realKeeperScanDeps(){return{'store':keeperStore,'payment':realPaymentDetectorDeps(),'progress':realProgressDetectorDeps(),'settlement':realSettlementDetectorDeps(),'execute':defaultExecute,'now':()=>Date['now'](),'logger':a=>console['error']('[keeper]\x20'+a)};}export async function runKeeperScan(a,b,c,d){const f=c['now'](),g={'scanned':![],'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0,'auto_executed':0x0,'auto_failed':0x0,'duration_ms':0x0};try{const h=await c['store']['getConfig'](a);if(!h['enabled'])return g['reason']='disabled',g;const i=await c['store']['getLastScanAt'](a);if(!d?.['force']&&c['now']()-i<h['scan_interval_ms'])return g['reason']='interval',g;await c['store']['setLastScanAt'](a,c['now']()),g['scanned']=!![];if(h['detectors']['payment_unclaimed'])try{const l=await detectPaymentUnclaimed((b['accounts']??[])['slice'](0x0,h['max_scan_objects']),a,c['payment']),m=await c['store']['upsertDesired'](a,'payment_unclaimed',l,c['now']());g['opened']+=m['opened'],g['refreshed']+=m['refreshed'],g['revived']+=m['revived'],g['superseded']+=m['superseded'];}catch(n){c['logger']('scan\x20'+a+':\x20payment_unclaimed\x20detector\x20failed:\x20'+String(n?.['message']??n));}if(h['detectors']['progress_actionable'])try{const o=await detectProgressActionable(b,a,c['progress'],h['max_scan_objects']),p=await c['store']['upsertDesired'](a,'progress_actionable',o,c['now']());g['opened']+=p['opened'],g['refreshed']+=p['refreshed'],g['revived']+=p['revived'],g['superseded']+=p['superseded'];}catch(q){c['logger']('scan\x20'+a+':\x20progress_actionable\x20detector\x20failed:\x20'+String(q?.['message']??q));}if(h['detectors']['settlement_pending'])try{const s=await detectSettlementPending(b,a,c['settlement'],h['max_scan_objects']),t=await c['store']['upsertDesired'](a,'settlement_pending',s,c['now']());g['opened']+=t['opened'],g['refreshed']+=t['refreshed'],g['revived']+=t['revived'],g['superseded']+=t['superseded'];}catch(u){c['logger']('scan\x20'+a+':\x20settlement_pending\x20detector\x20failed:\x20'+String(u?.['message']??u));}const j=await c['store']['listTasks'](a,{'status':'pending'});let k=h['max_auto_execute_per_scan'];for(const v of j){if(k<=0x0)break;if(!v['operation'])continue;if(!AUTO_EXECUTABLE_DETECTORS['includes'](v['detector']))continue;if(v['last_auto_attempt_at']&&c['now']()-v['last_auto_attempt_at']<h['auto_retry_cooldown_ms'])continue;const w=await c['store']['matchingAutoRules'](a,v['detector'],v['beneficiary']),x=w[0x0];if(!x)continue;k--,await c['store']['markAutoAttempt'](a,v['id'],c['now']());const y=await c['execute']({'operation_type':v['operation']['operation_type'],'data':v['operation']['data'],'account':v['beneficiary'],'network':a,'via':'rule\x20'+x['id']});y['ok']?(await c['store']['resolveTask'](a,v['id'],'auto_executed',c['now'](),y['digest']?'tx\x20'+y['digest']:'executed',x['id']),g['auto_executed']++,c['logger']('auto-executed\x20'+v['dedupe_key']+'\x20via\x20rule\x20'+x['id']+'\x20('+(y['digest']??'no\x20digest')+')')):(await c['store']['resolveTask'](a,v['id'],'execute_failed',c['now'](),y['error']??'unknown\x20execution\x20error',x['id']),g['auto_failed']++,c['logger']('auto-execute\x20failed\x20for\x20'+v['dedupe_key']+':\x20'+(y['error']??'unknown')));}return g;}catch(z){return c['logger']('scan\x20'+a+'\x20failed:\x20'+String(z?.['message']??z)),g['reason']='error',g;}finally{g['duration_ms']=c['now']()-f;}}export async function executeKeeperTask(a,b,c){if(!b['operation'])return{'ok':![],'error':'This\x20task\x20is\x20reminder-only\x20(no\x20keeper-executable\x20operation).\x20'+'Follow\x20its\x20detail\x20text\x20—\x20progress\x20forwards\x20are\x20advanced\x20via\x20workflow_operation.'};const d=await c['execute']({'operation_type':b['operation']['operation_type'],'data':b['operation']['data'],'account':b['beneficiary'],'network':a,'via':'manual'});return d['ok']?await c['store']['resolveTask'](a,b['id'],'manual_executed',c['now'](),d['digest']?'tx\x20'+d['digest']:'executed'):await c['store']['resolveTask'](a,b['id'],'execute_failed',c['now'](),d['error']),d;}
@@ -19,5 +19,14 @@ export interface ProgressDetectorDeps {
19
19
  fetchOrderContext(order: string, network: string): Promise<OrderContext | undefined>;
20
20
  }
21
21
  export declare function detectProgressActionable(scope: ScopeSnapshot, network: string, deps: ProgressDetectorDeps, maxObjects: number): Promise<KeeperDesiredItem[]>;
22
+ export interface SettlementDetectorDeps {
23
+ fetchOrderFields(addrs: string[], network: string): Promise<Map<string, any>>;
24
+ fetchAllocationFields(addrs: string[], network: string): Promise<Map<string, any>>;
25
+ fetchProgressFields(addrs: string[], network: string): Promise<Map<string, any>>;
26
+ fetchMachineNodes(machine: string, network: string): Promise<ParsedMachineNode[]>;
27
+ formatAmount?(balance: bigint, tokenType: string | undefined, network: string): Promise<string | undefined>;
28
+ }
29
+ export declare function detectSettlementPending(scope: ScopeSnapshot, network: string, deps: SettlementDetectorDeps, maxObjects: number): Promise<KeeperDesiredItem[]>;
22
30
  export declare function realPaymentDetectorDeps(): PaymentDetectorDeps;
23
31
  export declare function realProgressDetectorDeps(): ProgressDetectorDeps;
32
+ export declare function realSettlementDetectorDeps(): SettlementDetectorDeps;
@@ -1 +1 @@
1
- import{query_received,query_objects}from'@wowok/wowok';import{batchQueryObjectsByIds,fetchMachineNodes,fetchOrderContext,fetchPermissionContext}from'../graph/onchain/sdk-batch.js';import{enumerateActionableForwards}from'../knowledge/index.js';import{formatChainValue}from'../knowledge/fund-layer.js';import{formatShortAddress}from'../persona/address-format.js';export async function detectPaymentUnclaimed(a,b,c){const d=[];for(const e of a){const f=e['toLowerCase']();let g=null;try{g=await c['queryUnclaimed'](f,b);}catch{g=null;}if(!g||g['balance']<=0x0n||g['count']<=0x0)continue;let h;try{h=await c['formatAmount']?.(g['balance'],g['token_type'],b);}catch{h=undefined;}const i=h??g['balance']['toString']()+'\x20(smallest\x20unit)';d['push']({'dedupe_key':'payment_unclaimed:'+f,'detector':'payment_unclaimed','beneficiary':f,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+i+'\x20waiting\x20to\x20be\x20received','detail':g['count']+'\x20CoinWrapper\x20object(s)\x20hold\x20'+i+'\x20for\x20this\x20account.\x20'+'They\x20are\x20owned\x20but\x20NOT\x20spendable\x20until\x20unwrapped.\x20Execute\x20payment\x20{receive:true}\x20'+'as\x20this\x20account\x20to\x20unwrap\x20all\x20of\x20them\x20into\x20the\x20wallet\x20in\x20one\x20transaction\x20(keeper\x20can\x20'+'auto-execute\x20this\x20when\x20a\x20payment_unclaimed\x20auto-exec\x20rule\x20covers\x20the\x20account).','benefit':'Receive\x20'+i+'\x20into\x20your\x20wallet','state_fingerprint':g['count']+':'+g['balance']['toString']()});}return d;}export async function detectProgressActionable(a,b,c,d){const e=(a['order_children']??[])['filter'](n=>n['type']==='progress'&&typeof n['object']==='string')['map'](n=>n['object'])['filter'](n=>n['startsWith']('0x')),f=(a['focus']??[])['map'](n=>n['object'])['filter'](n=>typeof n==='string'&&n['startsWith']('0x')),g=[...new Set([...e,...f])]['slice'](0x0,Math['max'](0x1,d));if(g['length']===0x0||(a['accounts']??[])['length']===0x0)return[];let h;try{h=await c['fetchProgressFields'](g,b);}catch{return[];}const i=new Map(),j=new Map(),k=new Map(),l=a['accounts'],m=[];for(const [n,o]of h){const p=typeof o?.['machine']==='string'?o['machine']:undefined;if(!p)continue;const q=p['toLowerCase']();let r=i['get'](q);if(!r){try{r=await c['fetchMachineNodes'](p,b);}catch{r=[];}i['set'](q,r);}if(r['length']===0x0)continue;let s;if(!j['has'](q)){let z;try{z=await c['fetchMachinePermissionAddr'](p,b);}catch{z=undefined;}let A;if(z)try{A=await c['fetchPermissionContext'](z,b);}catch{A=undefined;}j['set'](q,A);}s=j['get'](q);const t=typeof o?.['task']==='string'?o['task']:undefined;let u;if(t){const B=t['toLowerCase']();if(!k['has'](B))try{k['set'](B,await c['fetchOrderContext'](t,b));}catch{k['set'](B,undefined);}u=k['get'](B);}const v=(Array['isArray'](o?.['namedOperator'])?o['namedOperator']:[])['map'](C=>({'name':String(C?.['name']??''),'operators':(Array['isArray'](C?.['operators'])?C['operators']:[])['map'](D=>String(D))})),w=enumerateActionableForwards(o,r,l,v,u,s),x=typeof o?.['current']==='string'?o['current']:'',y=t?'order\x20'+formatShortAddress(t):'no\x20bound\x20order';for(const C of w){for(const D of C['executable_accounts']){const E=C['threshold']>0x1?'\x20—\x20cooperation\x20threshold\x20'+C['threshold']+'\x20(weight\x20'+C['weight']+');\x20other\x20distinct\x20forwards\x20may\x20still\x20be\x20needed':'',F=C['guard']?'\x20—\x20guard\x20'+formatShortAddress(C['guard'])+'\x20must\x20be\x20satisfied\x20(submissions\x20may\x20be\x20required)':'',G=u&&D===u['builder']['toLowerCase']()?'You\x20are\x20the\x20order\x20owner':C['operator_kind']==='named_operator'?'You\x20hold\x20the\x20named-operator\x20role\x20\x27'+C['named_operator']+'\x27':'You\x20hold\x20the\x20required\x20permission\x20index';m['push']({'dedupe_key':'progress_actionable:'+n+':'+D+':'+C['next_node']+'|'+C['forward'],'detector':'progress_actionable','beneficiary':D,'object':n,'title':'Workflow\x20action\x20available:\x20\x27'+C['forward']+'\x27\x20→\x20'+C['next_node'],'detail':'Progress\x20'+formatShortAddress(n)+'\x20('+y+')\x20sits\x20at\x20node\x20\x27'+x+'\x27.\x20'+(G+'\x20—\x20you\x20can\x20execute\x20forward\x20\x27'+C['forward']+'\x27\x20into\x20\x27'+C['next_node']+'\x27')+(''+E+F+'.\x20Advance\x20it\x20via\x20workflow_operation\x20')+'(action=\x27list\x27\x20to\x20review,\x20action=\x27operate\x27\x20to\x20execute).\x20'+'Who\x20benefits,\x20who\x20pushes:\x20waiting\x20does\x20not\x20move\x20the\x20order\x20—\x20the\x20party\x20that\x20'+'gains\x20from\x20the\x20next\x20step\x20sends\x20the\x20transaction.','benefit':benefitOfNode(C['next_node']),'state_fingerprint':C['weight']+':'+C['threshold']+':'+(C['guard']??'')+':'+C['operator_kind']});}}}return m;}function benefitOfNode(a){if(/(^|_)(completed?|done|finished|received|delivered|accepted|confirmed|finalized|success|approved)(_|$)/i['test'](a))return'Completing\x20this\x20step\x20settles\x20the\x20order\x20—\x20funds\x20are\x20released\x20to\x20the\x20provider';if(/(^|_)(cancel(led)?|refund(ed)?|return(ed|_approved)?)(_|$)/i['test'](a))return'This\x20step\x20routes\x20to\x20cancellation/refund\x20—\x20funds\x20return\x20to\x20the\x20buyer';if(/(^|_)(interrupt(ed)?|exception|dispute(d)?|fail(ed)?|abort(ed)?|reject(ed)?)(_|$)/i['test'](a))return'This\x20step\x20opens\x20the\x20exception\x20path\x20—\x20review\x20before\x20advancing';return'Advancing\x20keeps\x20the\x20order\x20moving\x20toward\x20settlement';}export function realPaymentDetectorDeps(){return{'queryUnclaimed':async(a,b)=>{const c=await query_received({'name_or_address':{'name_or_address':a},'type':'CoinWrapper','network':b});if(!c||typeof c!=='object'||!Array['isArray'](c['received']))return null;const d=typeof c['balance']==='bigint'?c['balance']:BigInt(c['balance']??0x0);return{'balance':d,'count':c['received']['length'],'token_type':typeof c['token_type']==='string'&&c['token_type']?c['token_type']:undefined};},'formatAmount':async(a,b,c)=>{if(!b)return undefined;const e=await formatChainValue(a,b,c),f=e['symbol']?'\x20'+e['symbol']:'';return e['precision_known']?''+e['display']+f:''+e['raw']+f;}};}export function realProgressDetectorDeps(){return{'fetchProgressFields':async(a,b)=>{const c=await batchQueryObjectsByIds(a,b,![]),e=new Map();for(const f of c??[]){const g=f?.['data']??f;if(f?.['type']!=='Progress')continue;const h=String(f?.['query_name']??f?.['object']??'')['toLowerCase']();if(h)e['set'](h,g);}return e;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'fetchMachinePermissionAddr':async(a,b)=>{const c=await query_objects({'objects':[a],'network':b}),d=c?.['objects']?.[0x0],e=(d?.['data']??d)?.['permission'];return typeof e==='string'&&e?e:undefined;},'fetchPermissionContext':(a,b)=>fetchPermissionContext(a,b,![]),'fetchOrderContext':(a,b)=>fetchOrderContext(a,b,![])};}
1
+ import{query_received,query_objects}from'@wowok/wowok';import{batchQueryObjectsByIds,fetchMachineNodes,fetchOrderContext,fetchPermissionContext}from'../graph/onchain/sdk-batch.js';import{extractCoinType}from'../graph/onchain/extract.js';import{enumerateActionableForwards}from'../knowledge/index.js';import{formatChainValue}from'../knowledge/fund-layer.js';import{formatShortAddress}from'../persona/address-format.js';export async function detectPaymentUnclaimed(a,b,c){const d=[];for(const e of a){const f=e['toLowerCase']();let g=null;try{g=await c['queryUnclaimed'](f,b);}catch{g=null;}if(!g||g['balance']<=0x0n||g['count']<=0x0)continue;let h;try{h=await c['formatAmount']?.(g['balance'],g['token_type'],b);}catch{h=undefined;}const i=h??g['balance']['toString']()+'\x20(smallest\x20unit)';d['push']({'dedupe_key':'payment_unclaimed:'+f,'detector':'payment_unclaimed','beneficiary':f,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+i+'\x20waiting\x20to\x20be\x20received','detail':g['count']+'\x20CoinWrapper\x20object(s)\x20hold\x20'+i+'\x20for\x20this\x20account.\x20'+'They\x20are\x20owned\x20but\x20NOT\x20spendable\x20until\x20unwrapped.\x20Execute\x20payment\x20{receive:true}\x20'+'as\x20this\x20account\x20to\x20unwrap\x20all\x20of\x20them\x20into\x20the\x20wallet\x20in\x20one\x20transaction\x20(keeper\x20can\x20'+'auto-execute\x20this\x20when\x20a\x20payment_unclaimed\x20auto-exec\x20rule\x20covers\x20the\x20account).','benefit':'Receive\x20'+i+'\x20into\x20your\x20wallet','state_fingerprint':g['count']+':'+g['balance']['toString']()});}return d;}export async function detectProgressActionable(a,b,c,d){const e=(a['order_children']??[])['filter'](n=>n['type']==='progress'&&typeof n['object']==='string')['map'](n=>n['object'])['filter'](n=>n['startsWith']('0x')),f=(a['focus']??[])['map'](n=>n['object'])['filter'](n=>typeof n==='string'&&n['startsWith']('0x')),g=[...new Set([...e,...f])]['slice'](0x0,Math['max'](0x1,d));if(g['length']===0x0||(a['accounts']??[])['length']===0x0)return[];let h;try{h=await c['fetchProgressFields'](g,b);}catch{return[];}const i=new Map(),j=new Map(),k=new Map(),l=a['accounts'],m=[];for(const [n,o]of h){const p=typeof o?.['machine']==='string'?o['machine']:undefined;if(!p)continue;const q=p['toLowerCase']();let r=i['get'](q);if(!r){try{r=await c['fetchMachineNodes'](p,b);}catch{r=[];}i['set'](q,r);}if(r['length']===0x0)continue;let s;if(!j['has'](q)){let z;try{z=await c['fetchMachinePermissionAddr'](p,b);}catch{z=undefined;}let A;if(z)try{A=await c['fetchPermissionContext'](z,b);}catch{A=undefined;}j['set'](q,A);}s=j['get'](q);const t=typeof o?.['task']==='string'?o['task']:undefined;let u;if(t){const B=t['toLowerCase']();if(!k['has'](B))try{k['set'](B,await c['fetchOrderContext'](t,b));}catch{k['set'](B,undefined);}u=k['get'](B);}const v=(Array['isArray'](o?.['namedOperator'])?o['namedOperator']:[])['map'](C=>({'name':String(C?.['name']??''),'operators':(Array['isArray'](C?.['operators'])?C['operators']:[])['map'](D=>String(D))})),w=enumerateActionableForwards(o,r,l,v,u,s),x=typeof o?.['current']==='string'?o['current']:'',y=t?'order\x20'+formatShortAddress(t):'no\x20bound\x20order';for(const C of w){for(const D of C['executable_accounts']){const E=C['threshold']>0x1?'\x20—\x20cooperation\x20threshold\x20'+C['threshold']+'\x20(weight\x20'+C['weight']+');\x20other\x20distinct\x20forwards\x20may\x20still\x20be\x20needed':'',F=C['guard']?'\x20—\x20guard\x20'+formatShortAddress(C['guard'])+'\x20must\x20be\x20satisfied\x20(submissions\x20may\x20be\x20required)':'',G=u&&D===u['builder']['toLowerCase']()?'You\x20are\x20the\x20order\x20owner':C['operator_kind']==='named_operator'?'You\x20hold\x20the\x20named-operator\x20role\x20\x27'+C['named_operator']+'\x27':'You\x20hold\x20the\x20required\x20permission\x20index';m['push']({'dedupe_key':'progress_actionable:'+n+':'+D+':'+C['next_node']+'|'+C['forward'],'detector':'progress_actionable','beneficiary':D,'object':n,'title':'Workflow\x20action\x20available:\x20\x27'+C['forward']+'\x27\x20→\x20'+C['next_node'],'detail':'Progress\x20'+formatShortAddress(n)+'\x20('+y+')\x20sits\x20at\x20node\x20\x27'+x+'\x27.\x20'+(G+'\x20—\x20you\x20can\x20execute\x20forward\x20\x27'+C['forward']+'\x27\x20into\x20\x27'+C['next_node']+'\x27')+(''+E+F+'.\x20Advance\x20it\x20via\x20workflow_operation\x20')+'(action=\x27list\x27\x20to\x20review,\x20action=\x27operate\x27\x20to\x20execute).\x20'+'Who\x20benefits,\x20who\x20pushes:\x20waiting\x20does\x20not\x20move\x20the\x20order\x20—\x20the\x20party\x20that\x20'+'gains\x20from\x20the\x20next\x20step\x20sends\x20the\x20transaction.','benefit':benefitOfNode(C['next_node']),'state_fingerprint':C['weight']+':'+C['threshold']+':'+(C['guard']??'')+':'+C['operator_kind']});}}}return m;}function benefitOfNode(a){if(/(^|_)(completed?|done|finished|received|delivered|accepted|confirmed|finalized|success|approved)(_|$)/i['test'](a))return'Completing\x20this\x20step\x20settles\x20the\x20order\x20—\x20funds\x20are\x20released\x20to\x20the\x20provider';if(/(^|_)(cancel(led)?|refund(ed)?|return(ed|_approved)?)(_|$)/i['test'](a))return'This\x20step\x20routes\x20to\x20cancellation/refund\x20—\x20funds\x20return\x20to\x20the\x20buyer';if(/(^|_)(interrupt(ed)?|exception|dispute(d)?|fail(ed)?|abort(ed)?|reject(ed)?)(_|$)/i['test'](a))return'This\x20step\x20opens\x20the\x20exception\x20path\x20—\x20review\x20before\x20advancing';return'Advancing\x20keeps\x20the\x20order\x20moving\x20toward\x20settlement';}const REFUND_FLAVOR_RE=/(^|_)(cancel(led)?|refund(ed)?|return(ed|_approved)?|expired)(_|$)/i;export async function detectSettlementPending(a,b,c,e){const f=(a['accounts']??[])['map'](s=>s['toLowerCase']());if(f['length']===0x0)return[];const g=(a['orders']??[])['slice'](0x0,Math['max'](0x1,e));if(g['length']===0x0)return[];const h=g['map'](s=>s['order'])['filter'](s=>typeof s==='string'&&s['startsWith']('0x'));let i;try{i=await c['fetchOrderFields'](h,b);}catch{return[];}const j=[],k=[];for(const s of i['values']()){const t=s?.['data']??s;if(typeof t?.['allocation']==='string'&&t['allocation']['startsWith']('0x'))j['push'](t['allocation']);if(typeof t?.['progress']==='string'&&t['progress']['startsWith']('0x'))k['push'](t['progress']);}let l=new Map(),m=new Map();try{l=await c['fetchAllocationFields']([...new Set(j)],b);}catch{return[];}try{m=await c['fetchProgressFields']([...new Set(k)],b);}catch{m=new Map();}const o=new Set((a['services']??[])['map'](u=>u['toLowerCase']())),q=new Map(),r=[];for(const [u,v]of i){const w=v?.['data']??v,x=typeof w?.['allocation']==='string'?w['allocation']:undefined;if(!x)continue;const y=l['get'](x['toLowerCase']());if(!y)continue;const z=y?.['data']??y,A=typeof z['balance']==='bigint'?z['balance']:BigInt(z['balance']??0x0);if(A<=0x0n)continue;const B=Array['isArray'](z['payment'])?z['payment']:[];if(B['length']>0x0)continue;const C=typeof w?.['progress']==='string'?w['progress']:undefined,D=C?m['get'](C['toLowerCase']()):undefined,E=typeof D?.['current']==='string'?D['current']:'',F=typeof D?.['machine']==='string'?D['machine']:typeof w?.['machine']==='string'?w['machine']:undefined;if(!E||!F)continue;let G=q['get'](F['toLowerCase']());if(!G){try{G=await c['fetchMachineNodes'](F,b);}catch{G=[];}q['set'](F['toLowerCase'](),G);}if(G['length']===0x0)continue;const H=new Set();for(const P of G){for(const Q of P['pairs']){if((Q['forwards']??[])['length']>0x0)H['add'](P['name']);}}if(H['has'](E))continue;const I=REFUND_FLAVOR_RE['test'](E),J=[];if(I){const R=typeof w?.['builder']==='string'?w['builder']['toLowerCase']():'';if(R&&f['includes'](R))J['push'](R);}else{const S=typeof w?.['service']==='string'?w['service']['toLowerCase']():'';if(S&&o['has'](S))J['push'](...f);}if(J['length']===0x0)continue;const K=(Array['isArray'](z['allocators']?.['allocators'])?z['allocators']['allocators']:[])['map'](T=>String(T?.['guard']??''))['filter'](T=>T),L=K['length']>0x0?'Candidate\x20settle\x20guards\x20on\x20this\x20pool:\x20'+K['map'](T=>formatShortAddress(T))['join'](',\x20')+'.':'This\x20pool\x20exposes\x20no\x20readable\x20allocator\x20guards\x20—\x20inspect\x20it\x20before\x20acting.';let M;try{M=await c['formatAmount']?.(A,extractCoinType(y?.['type_raw']),b);}catch{M=undefined;}const N=M??A['toString']()+'\x20(smallest\x20unit)',O=I?'refund/cancel':'completion';for(const T of J){r['push']({'dedupe_key':'settlement_pending:'+u+':'+x,'detector':'settlement_pending','beneficiary':T,'object':x,'title':'Unsettled\x20escrow\x20—\x20'+N+'\x20on\x20a\x20'+O+'\x20terminal','detail':'Order\x20'+formatShortAddress(u)+'\x20sits\x20on\x20terminal\x20node\x20\x27'+E+'\x27\x20but\x20its\x20Allocation\x20'+(formatShortAddress(x)+'\x20still\x20holds\x20'+N+'\x20and\x20has\x20emitted\x20no\x20Payment.\x20The\x20chain\x20never\x20')+('auto-settles:\x20someone\x20must\x20trigger\x20the\x20matching\x20guard.\x20'+L+'\x20Execute\x20via\x20allocation_operation\x20')+'(operation_type=\x27allocation\x27,\x20alloc_by_guard=<guard>)\x20as\x20an\x20account\x20that\x20can\x20satisfy\x20the\x20guard,\x20then\x20'+'recipients\x20claim\x20their\x20CoinWrappers\x20(payment\x20receive).\x20Trigger\x20ONCE\x20and\x20verify\x20the\x20pool\x20drained\x20—\x20a\x20'+'fully-drained\x20pool\x20aborts\x20on\x20re-trigger,\x20but\x20a\x20max-capped\x20pool\x20re-splits\x20the\x20remainder.\x20'+'Who\x20benefits,\x20who\x20pushes:\x20waiting\x20keeps\x20the\x20funds\x20frozen\x20and\x20leaves\x20the\x20dispute\x20window\x20open.','benefit':'Release\x20'+N+'\x20from\x20escrow\x20to\x20its\x20rightful\x20recipients','state_fingerprint':A['toString']()+':'+B['length']+':'+E});}}return r;}export function realPaymentDetectorDeps(){return{'queryUnclaimed':async(a,b)=>{const c=await query_received({'name_or_address':{'name_or_address':a},'type':'CoinWrapper','network':b});if(!c||typeof c!=='object'||!Array['isArray'](c['received']))return null;const d=typeof c['balance']==='bigint'?c['balance']:BigInt(c['balance']??0x0);return{'balance':d,'count':c['received']['length'],'token_type':typeof c['token_type']==='string'&&c['token_type']?c['token_type']:undefined};},'formatAmount':async(a,b,c)=>{if(!b)return undefined;const e=await formatChainValue(a,b,c),f=e['symbol']?'\x20'+e['symbol']:'';return e['precision_known']?''+e['display']+f:''+e['raw']+f;}};}export function realProgressDetectorDeps(){return{'fetchProgressFields':async(a,b)=>{const c=await batchQueryObjectsByIds(a,b,![]),e=new Map();for(const f of c??[]){const g=f?.['data']??f;if(f?.['type']!=='Progress')continue;const h=String(f?.['query_name']??f?.['object']??'')['toLowerCase']();if(h)e['set'](h,g);}return e;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'fetchMachinePermissionAddr':async(a,b)=>{const c=await query_objects({'objects':[a],'network':b}),d=c?.['objects']?.[0x0],e=(d?.['data']??d)?.['permission'];return typeof e==='string'&&e?e:undefined;},'fetchPermissionContext':(a,b)=>fetchPermissionContext(a,b,![]),'fetchOrderContext':(a,b)=>fetchOrderContext(a,b,![])};}async function fieldsByType(a,b,c){const d=await batchQueryObjectsByIds(a,b,![]),e=new Map();for(const f of d??[]){if(f?.['type']!==c)continue;const g=String(f?.['query_name']??f?.['object']??'')['toLowerCase']();if(g)e['set'](g,f);}return e;}export function realSettlementDetectorDeps(){return{'fetchOrderFields':(a,b)=>fieldsByType(a,b,'Order'),'fetchAllocationFields':(a,b)=>fieldsByType(a,b,'Allocation'),'fetchProgressFields':async(a,b)=>{const c=await fieldsByType(a,b,'Progress'),d=new Map();for(const [e,f]of c)d['set'](e,f?.['data']??f);return d;},'fetchMachineNodes':(a,b)=>fetchMachineNodes(a,b,![]),'formatAmount':async(a,b,c)=>{if(!b)return undefined;const e=await formatChainValue(a,b,c),f=e['symbol']?'\x20'+e['symbol']:'';return e['precision_known']?''+e['display']+f:''+e['raw']+f;}};}
@@ -1 +1 @@
1
- import{describe,expect,it}from'vitest';import{KeeperStore}from'./KeeperStore.js';import{detectPaymentUnclaimed,detectProgressActionable}from'./detectors.js';import{executeKeeperTask,runKeeperScan}from'./KeeperScan.js';import{clampKeeperConfig,defaultKeeperConfig,KEEPER_MIN}from'./types.js';const NET='testnet',ACCT='0xaaa111',OTHER='0xbbb222';function memStorage(){const a=new Map();return{'get':async b=>a['get'](b),'put':async(b,c)=>void a['set'](b,c)};}function makeStore(){return new KeeperStore(memStorage());}function paymentItem(a,b,c=0x1){return{'dedupe_key':'payment_unclaimed:'+a,'detector':'payment_unclaimed','beneficiary':a,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+b+'\x20waiting','state_fingerprint':c+':'+b['toString']()};}function makeScope(a){return{'version':0x1,'resolved_at':0x0,'accounts':[ACCT],'permissions':[],'managed_objects':[],'services':[],'orders':[],'order_children':[],'focus':[],'index':{},...a};}describe('keeper\x20config',()=>{it('returns\x20safe\x20defaults:\x20reminders\x20ON,\x20auto\x20rules\x20none',async()=>{const a=makeStore(),b=await a['getConfig'](NET);expect(b['enabled'])['toBe'](!![]),expect(b['detectors']['payment_unclaimed'])['toBe'](!![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]),expect(await a['listRules'](NET))['toEqual']([]);}),it('config_set\x20patch\x20merges\x20detectors\x20individually',async()=>{const a=makeStore(),b=await a['saveConfig'](NET,{'detectors':{'payment_unclaimed':![]}});expect(b['detectors']['payment_unclaimed'])['toBe'](![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]);const c=await a['getConfig'](NET);expect(c['detectors']['payment_unclaimed'])['toBe'](![]),expect(c['detectors']['progress_actionable'])['toBe'](!![]);}),it('clamps\x20numeric\x20bounds\x20(cost/gas\x20guards)',()=>{const a=clampKeeperConfig({...defaultKeeperConfig(),'scan_interval_ms':0x1,'max_scan_objects':0x0,'max_auto_execute_per_scan':0x0,'auto_retry_cooldown_ms':0x0});expect(a['scan_interval_ms'])['toBe'](KEEPER_MIN['scan_interval_ms']),expect(a['max_scan_objects'])['toBe'](KEEPER_MIN['max_scan_objects']),expect(a['max_auto_execute_per_scan'])['toBe'](KEEPER_MIN['max_auto_execute_per_scan']),expect(a['auto_retry_cooldown_ms'])['toBe'](KEEPER_MIN['auto_retry_cooldown_ms']);});}),describe('keeper\x20rules',()=>{const a=b=>({'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0,...b});it('matchingAutoRules\x20honors\x20enabled\x20/\x20auto_execute\x20/\x20account\x20coverage',async()=>{const b=makeStore();await b['upsertRule'](NET,a()),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'progress_actionable',ACCT))['toHaveLength'](0x0),await b['upsertRule'](NET,a({'id':'krule_2','accounts':[OTHER['toUpperCase']()]})),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER))['toHaveLength'](0x2),await b['upsertRule'](NET,a({'id':'krule_3','enabled':![]})),await b['upsertRule'](NET,a({'id':'krule_4','auto_execute':![]}));const c=await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER);expect(c['map'](d=>d['id'])['sort']())['toEqual'](['krule_1','krule_2']);});}),describe('KeeperStore.upsertDesired',()=>{it('opens\x20new\x20tasks,\x20refreshes\x20on\x20fingerprint\x20change,\x20no\x20churn\x20when\x20identical',async()=>{const a=makeStore();let b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);expect(b)['toEqual']({'opened':0x1,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0),expect(b)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0xfan)],0xbb8),expect(b)['toEqual']({'opened':0x0,'refreshed':0x1,'revived':0x0,'superseded':0x0});const c=(await a['listTasks'](NET))[0x0];expect(c['title'])['toContain']('250'),expect(c['updated_at'])['toBe'](0xbb8);}),it('dismissed\x20stays\x20dismissed\x20for\x20identical\x20state,\x20revives\x20on\x20material\x20change',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'dismissed',0x5dc,'not\x20now');let c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0);expect(c['revived'])['toBe'](0x0),expect((await a['getTask'](NET,b['id']))['status'])['toBe']('dismissed'),c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x190n,0x2)],0xbb8),expect(c['revived'])['toBe'](0x1);const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('pending'),expect(d['resolution'])['toBeUndefined'](),expect(d['resolved_at'])['toBeUndefined']();}),it('executed\x20tasks\x20are\x20terminal\x20—\x20same\x20dedupe_key\x20never\x20re-opens\x20them',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'auto_executed',0x5dc,'tx\x20ABC','krule_1');const c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x1f4n)],0x7d0);expect(c)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0});const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('executed'),expect(d['rule_id'])['toBe']('krule_1');}),it('supersedes\x20pending\x20tasks\x20of\x20THIS\x20detector\x20only',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8),await a['upsertDesired'](NET,'progress_actionable',[{'dedupe_key':'progress_actionable:0xp1:0xaaa111:shipped|deliver','detector':'progress_actionable','beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator'}],0x3e8);const b=await a['upsertDesired'](NET,'payment_unclaimed',[],0x7d0);expect(b['superseded'])['toBe'](0x1);const c=await a['listTasks'](NET),d=c['find'](f=>f['detector']==='payment_unclaimed'),e=c['find'](f=>f['detector']==='progress_actionable');expect(d['status'])['toBe']('superseded'),expect(d['resolution'])['toBe']('superseded'),expect(e['status'])['toBe']('pending');}),it('execute_failed\x20keeps\x20the\x20task\x20pending\x20with\x20failure\x20bookkeeping',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'execute_failed',0x1388,'insufficient\x20gas','krule_1');const c=await a['getTask'](NET,b['id']);expect(c['status'])['toBe']('pending'),expect(c['last_auto_attempt_at'])['toBe'](0x1388),expect(c['auto_attempts'])['toBe'](0x1),expect(c['resolution_note'])['toBe']('insufficient\x20gas');});}),describe('detectPaymentUnclaimed',()=>{it('emits\x20a\x20claim-to-self\x20task\x20for\x20accounts\x20with\x20unclaimed\x20wrappers',async()=>{const a=await detectPaymentUnclaimed([ACCT['toUpperCase'](),OTHER,'0xccc333'],NET,{'queryUnclaimed':async c=>{if(c===ACCT)return{'balance':0x64n,'count':0x2,'token_type':'0x2::wow::WOW'};if(c===OTHER)return{'balance':0x0n,'count':0x0};throw new Error('rpc\x20down');},'formatAmount':async()=>'0.0000001\x20WOW'});expect(a)['toHaveLength'](0x1);const b=a[0x0];expect(b['dedupe_key'])['toBe']('payment_unclaimed:'+ACCT),expect(b['beneficiary'])['toBe'](ACCT),expect(b['operation'])['toEqual']({'operation_type':'payment','data':{'receive':!![]}}),expect(b['state_fingerprint'])['toBe']('2:100'),expect(b['title'])['toContain']('0.0000001\x20WOW');}),it('falls\x20back\x20to\x20raw\x20units\x20when\x20formatting\x20fails',async()=>{const a=await detectPaymentUnclaimed([ACCT],NET,{'queryUnclaimed':async()=>({'balance':0x2an,'count':0x1}),'formatAmount':async()=>{throw new Error('no\x20metadata');}});expect(a[0x0]['title'])['toContain']('42\x20(smallest\x20unit)');});}),describe('detectProgressActionable',()=>{const a='0xprog1',b='0xmachine1',c=[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],d=(g=[])=>({'machine':b,'current':'start','session':g,'namedOperator':[{'name':'courier','operators':[ACCT]}]}),e=g=>({'fetchProgressFields':async()=>new Map([[a,g]]),'fetchMachineNodes':async()=>c,'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}),f=makeScope({'order_children':[{'type':'progress','object':a}]});it('routes\x20an\x20actionable\x20forward\x20to\x20its\x20named\x20operator',async()=>{const g=await detectProgressActionable(f,NET,e(d()),0x14);expect(g)['toHaveLength'](0x1),expect(g[0x0]['dedupe_key'])['toBe']('progress_actionable:'+a+':'+ACCT+':shipped|deliver'),expect(g[0x0]['beneficiary'])['toBe'](ACCT),expect(g[0x0]['operation'])['toBeUndefined'](),expect(g[0x0]['detail'])['toContain']('workflow_operation');}),it('omits\x20accomplished\x20forwards\x20(single-operator\x20lock)',async()=>{const g=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':ACCT,'accomplished':!![]}]}],h=await detectProgressActionable(f,NET,e(d(g)),0x14);expect(h)['toHaveLength'](0x0);}),it('restricts\x20a\x20held\x20forward\x20to\x20its\x20holder',async()=>{const g=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':OTHER,'accomplished':![]}]}],h=await detectProgressActionable(f,NET,e(d(g)),0x14);expect(h)['toHaveLength'](0x0);}),it('returns\x20nothing\x20when\x20the\x20batch\x20read\x20fails\x20(fail-safe)',async()=>{const g=await detectProgressActionable(f,NET,{...e(d()),'fetchProgressFields':async()=>{throw new Error('rpc\x20down');}},0x14);expect(g)['toEqual']([]);});});function scanDepsFor(a,b){let c=0x2710;const d=[],e={'store':a,'payment':{'queryUnclaimed':async()=>({'balance':0x64n,'count':0x1})},'progress':{'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined},'execute':async f=>{return d['push']({'operation_type':f['operation_type'],'account':f['account'],'via':f['via']}),{'ok':!![],'digest':'DIGEST1'};},'now':()=>c,'logger':()=>{},...b};return{'deps':e,'executed':d,'advance':f=>{c+=f;},'setClock':f=>{c=f;}};}describe('runKeeperScan',()=>{it('skips\x20when\x20disabled\x20and\x20when\x20inside\x20the\x20cadence\x20interval',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a);await a['saveConfig'](NET,{'enabled':![]});let c=await runKeeperScan(NET,makeScope(),b);expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('disabled'),await a['saveConfig'](NET,{'enabled':!![]}),await a['setLastScanAt'](NET,0x2710),c=await runKeeperScan(NET,makeScope(),b),expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('interval');}),it('auto-executes\x20a\x20payment\x20task\x20ONLY\x20with\x20a\x20covering\x20enabled\x20rule',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);let d=await runKeeperScan(NET,makeScope(),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0}),d=await runKeeperScan(NET,makeScope(),b,{'force':!![]}),expect(d['auto_executed'])['toBe'](0x1),expect(c[0x0])['toEqual']({'operation_type':'payment','account':ACCT,'via':'rule\x20krule_1'});const e=(await a['listTasks'](NET))[0x0];expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('auto_executed'),expect(e['rule_id'])['toBe']('krule_1'),expect(e['resolution_note'])['toContain']('DIGEST1');}),it('never\x20auto-executes\x20progress\x20tasks\x20(reminder-only\x20boundary)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a,{'payment':{'queryUnclaimed':async()=>null},'progress':{'fetchProgressFields':async()=>new Map([['0xprog1',{'machine':'0xm1','current':'start','session':[],'namedOperator':[{'name':'courier','operators':[ACCT]}]}]]),'fetchMachineNodes':async()=>[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}});await a['upsertRule'](NET,{'id':'krule_p','enabled':!![],'detector':'progress_actionable','accounts':[],'auto_execute':!![],'created_at':0x0});const d=await runKeeperScan(NET,makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),expect((await a['listTasks'](NET))[0x0]['status'])['toBe']('pending');}),it('backs\x20off\x20after\x20a\x20failed\x20auto-exec\x20until\x20the\x20cooldown\x20passes',async()=>{const a=makeStore(),b=scanDepsFor(a,{'execute':async()=>({'ok':![],'error':'insufficient\x20gas'})});await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});let c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]});expect(c['auto_failed'])['toBe'](0x1);const d=(await a['listTasks'](NET))[0x0];expect(d['status'])['toBe']('pending'),expect(d['resolution_note'])['toBe']('insufficient\x20gas'),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x0),expect(c['auto_executed'])['toBe'](0x0),b['advance'](0x1f*0xea60),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x1);}),it('caps\x20auto-executions\x20per\x20scan\x20(gas\x20guard)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);await a['saveConfig'](NET,{'max_auto_execute_per_scan':0x1}),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});const d=makeScope({'accounts':[ACCT,OTHER]}),e=await runKeeperScan(NET,d,b,{'force':!![]});expect(e['opened'])['toBe'](0x2),expect(e['auto_executed'])['toBe'](0x1),expect(c)['toHaveLength'](0x1),expect(await a['listTasks'](NET,{'status':'pending'}))['toHaveLength'](0x1);});}),describe('executeKeeperTask\x20(manual)',()=>{it('resolves\x20a\x20payment\x20task\x20as\x20manual_executed',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0],{deps:c}=scanDepsFor(a),d=await executeKeeperTask(NET,b,c);expect(d['ok'])['toBe'](!![]);const e=await a['getTask'](NET,b['id']);expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('manual_executed');}),it('refuses\x20reminder-only\x20tasks\x20(progress)\x20with\x20guidance',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a),c={'id':'ktask_x','dedupe_key':'progress_actionable:0xp:0xaaa111:shipped|deliver','detector':'progress_actionable','network':NET,'beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator','status':'pending','created_at':0x0,'updated_at':0x0},d=await executeKeeperTask(NET,c,b);expect(d['ok'])['toBe'](![]),expect(d['error'])['toContain']('reminder-only');});});
1
+ import{describe,expect,it}from'vitest';import{KeeperStore}from'./KeeperStore.js';import{detectPaymentUnclaimed,detectProgressActionable,detectSettlementPending}from'./detectors.js';import{executeKeeperTask,runKeeperScan}from'./KeeperScan.js';import{clampKeeperConfig,defaultKeeperConfig,KEEPER_MIN}from'./types.js';const NET='testnet',ACCT='0xaaa111',OTHER='0xbbb222';function memStorage(){const a=new Map();return{'get':async b=>a['get'](b),'put':async(b,c)=>void a['set'](b,c)};}function makeStore(){return new KeeperStore(memStorage());}function paymentItem(a,b,c=0x1){return{'dedupe_key':'payment_unclaimed:'+a,'detector':'payment_unclaimed','beneficiary':a,'operation':{'operation_type':'payment','data':{'receive':!![]}},'title':'Unclaimed\x20funds\x20—\x20'+b+'\x20waiting','state_fingerprint':c+':'+b['toString']()};}function makeScope(a){return{'version':0x1,'resolved_at':0x0,'accounts':[ACCT],'permissions':[],'managed_objects':[],'services':[],'orders':[],'order_children':[],'focus':[],'index':{},...a};}describe('keeper\x20config',()=>{it('returns\x20safe\x20defaults:\x20reminders\x20ON,\x20auto\x20rules\x20none',async()=>{const a=makeStore(),b=await a['getConfig'](NET);expect(b['enabled'])['toBe'](!![]),expect(b['detectors']['payment_unclaimed'])['toBe'](!![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]),expect(await a['listRules'](NET))['toEqual']([]);}),it('config_set\x20patch\x20merges\x20detectors\x20individually',async()=>{const a=makeStore(),b=await a['saveConfig'](NET,{'detectors':{'payment_unclaimed':![]}});expect(b['detectors']['payment_unclaimed'])['toBe'](![]),expect(b['detectors']['progress_actionable'])['toBe'](!![]);const c=await a['getConfig'](NET);expect(c['detectors']['payment_unclaimed'])['toBe'](![]),expect(c['detectors']['progress_actionable'])['toBe'](!![]);}),it('clamps\x20numeric\x20bounds\x20(cost/gas\x20guards)',()=>{const a=clampKeeperConfig({...defaultKeeperConfig(),'scan_interval_ms':0x1,'max_scan_objects':0x0,'max_auto_execute_per_scan':0x0,'auto_retry_cooldown_ms':0x0});expect(a['scan_interval_ms'])['toBe'](KEEPER_MIN['scan_interval_ms']),expect(a['max_scan_objects'])['toBe'](KEEPER_MIN['max_scan_objects']),expect(a['max_auto_execute_per_scan'])['toBe'](KEEPER_MIN['max_auto_execute_per_scan']),expect(a['auto_retry_cooldown_ms'])['toBe'](KEEPER_MIN['auto_retry_cooldown_ms']);});}),describe('keeper\x20rules',()=>{const a=b=>({'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0,...b});it('matchingAutoRules\x20honors\x20enabled\x20/\x20auto_execute\x20/\x20account\x20coverage',async()=>{const b=makeStore();await b['upsertRule'](NET,a()),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'progress_actionable',ACCT))['toHaveLength'](0x0),await b['upsertRule'](NET,a({'id':'krule_2','accounts':[OTHER['toUpperCase']()]})),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',ACCT))['toHaveLength'](0x1),expect(await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER))['toHaveLength'](0x2),await b['upsertRule'](NET,a({'id':'krule_3','enabled':![]})),await b['upsertRule'](NET,a({'id':'krule_4','auto_execute':![]}));const c=await b['matchingAutoRules'](NET,'payment_unclaimed',OTHER);expect(c['map'](d=>d['id'])['sort']())['toEqual'](['krule_1','krule_2']);});}),describe('KeeperStore.upsertDesired',()=>{it('opens\x20new\x20tasks,\x20refreshes\x20on\x20fingerprint\x20change,\x20no\x20churn\x20when\x20identical',async()=>{const a=makeStore();let b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);expect(b)['toEqual']({'opened':0x1,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0),expect(b)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0}),b=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0xfan)],0xbb8),expect(b)['toEqual']({'opened':0x0,'refreshed':0x1,'revived':0x0,'superseded':0x0});const c=(await a['listTasks'](NET))[0x0];expect(c['title'])['toContain']('250'),expect(c['updated_at'])['toBe'](0xbb8);}),it('dismissed\x20stays\x20dismissed\x20for\x20identical\x20state,\x20revives\x20on\x20material\x20change',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'dismissed',0x5dc,'not\x20now');let c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x7d0);expect(c['revived'])['toBe'](0x0),expect((await a['getTask'](NET,b['id']))['status'])['toBe']('dismissed'),c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x190n,0x2)],0xbb8),expect(c['revived'])['toBe'](0x1);const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('pending'),expect(d['resolution'])['toBeUndefined'](),expect(d['resolved_at'])['toBeUndefined']();}),it('executed\x20tasks\x20are\x20terminal\x20—\x20same\x20dedupe_key\x20never\x20re-opens\x20them',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'auto_executed',0x5dc,'tx\x20ABC','krule_1');const c=await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x1f4n)],0x7d0);expect(c)['toEqual']({'opened':0x0,'refreshed':0x0,'revived':0x0,'superseded':0x0});const d=await a['getTask'](NET,b['id']);expect(d['status'])['toBe']('executed'),expect(d['rule_id'])['toBe']('krule_1');}),it('supersedes\x20pending\x20tasks\x20of\x20THIS\x20detector\x20only',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8),await a['upsertDesired'](NET,'progress_actionable',[{'dedupe_key':'progress_actionable:0xp1:0xaaa111:shipped|deliver','detector':'progress_actionable','beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator'}],0x3e8);const b=await a['upsertDesired'](NET,'payment_unclaimed',[],0x7d0);expect(b['superseded'])['toBe'](0x1);const c=await a['listTasks'](NET),d=c['find'](f=>f['detector']==='payment_unclaimed'),e=c['find'](f=>f['detector']==='progress_actionable');expect(d['status'])['toBe']('superseded'),expect(d['resolution'])['toBe']('superseded'),expect(e['status'])['toBe']('pending');}),it('execute_failed\x20keeps\x20the\x20task\x20pending\x20with\x20failure\x20bookkeeping',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0];await a['resolveTask'](NET,b['id'],'execute_failed',0x1388,'insufficient\x20gas','krule_1');const c=await a['getTask'](NET,b['id']);expect(c['status'])['toBe']('pending'),expect(c['last_auto_attempt_at'])['toBe'](0x1388),expect(c['auto_attempts'])['toBe'](0x1),expect(c['resolution_note'])['toBe']('insufficient\x20gas');});}),describe('detectPaymentUnclaimed',()=>{it('emits\x20a\x20claim-to-self\x20task\x20for\x20accounts\x20with\x20unclaimed\x20wrappers',async()=>{const a=await detectPaymentUnclaimed([ACCT['toUpperCase'](),OTHER,'0xccc333'],NET,{'queryUnclaimed':async c=>{if(c===ACCT)return{'balance':0x64n,'count':0x2,'token_type':'0x2::wow::WOW'};if(c===OTHER)return{'balance':0x0n,'count':0x0};throw new Error('rpc\x20down');},'formatAmount':async()=>'0.0000001\x20WOW'});expect(a)['toHaveLength'](0x1);const b=a[0x0];expect(b['dedupe_key'])['toBe']('payment_unclaimed:'+ACCT),expect(b['beneficiary'])['toBe'](ACCT),expect(b['operation'])['toEqual']({'operation_type':'payment','data':{'receive':!![]}}),expect(b['state_fingerprint'])['toBe']('2:100'),expect(b['title'])['toContain']('0.0000001\x20WOW');}),it('falls\x20back\x20to\x20raw\x20units\x20when\x20formatting\x20fails',async()=>{const a=await detectPaymentUnclaimed([ACCT],NET,{'queryUnclaimed':async()=>({'balance':0x2an,'count':0x1}),'formatAmount':async()=>{throw new Error('no\x20metadata');}});expect(a[0x0]['title'])['toContain']('42\x20(smallest\x20unit)');});}),describe('detectProgressActionable',()=>{const a='0xprog1',b='0xmachine1',c=[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],d=(g=[])=>({'machine':b,'current':'start','session':g,'namedOperator':[{'name':'courier','operators':[ACCT]}]}),e=g=>({'fetchProgressFields':async()=>new Map([[a,g]]),'fetchMachineNodes':async()=>c,'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}),f=makeScope({'order_children':[{'type':'progress','object':a}]});it('routes\x20an\x20actionable\x20forward\x20to\x20its\x20named\x20operator',async()=>{const g=await detectProgressActionable(f,NET,e(d()),0x14);expect(g)['toHaveLength'](0x1),expect(g[0x0]['dedupe_key'])['toBe']('progress_actionable:'+a+':'+ACCT+':shipped|deliver'),expect(g[0x0]['beneficiary'])['toBe'](ACCT),expect(g[0x0]['operation'])['toBeUndefined'](),expect(g[0x0]['detail'])['toContain']('workflow_operation');}),it('omits\x20accomplished\x20forwards\x20(single-operator\x20lock)',async()=>{const g=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':ACCT,'accomplished':!![]}]}],h=await detectProgressActionable(f,NET,e(d(g)),0x14);expect(h)['toHaveLength'](0x0);}),it('restricts\x20a\x20held\x20forward\x20to\x20its\x20holder',async()=>{const g=[{'next_node':'shipped','forwards':[{'forward':'deliver','who':OTHER,'accomplished':![]}]}],h=await detectProgressActionable(f,NET,e(d(g)),0x14);expect(h)['toHaveLength'](0x0);}),it('returns\x20nothing\x20when\x20the\x20batch\x20read\x20fails\x20(fail-safe)',async()=>{const g=await detectProgressActionable(f,NET,{...e(d()),'fetchProgressFields':async()=>{throw new Error('rpc\x20down');}},0x14);expect(g)['toEqual']([]);});}),describe('detectSettlementPending',()=>{const a='0xorder1',b='0xpool1',c='0xprog1',d='0xmachine1',e='0xsvc1',f=i=>[{'name':'paid','pairs':[{'prev_node':'','threshold':0x1,'forwards':[{'name':'settle','weight':0x1}]}]},{'name':i,'pairs':[{'prev_node':'paid','threshold':0x1,'forwards':[]}]}];function g(i,j,k,l){return{'fetchOrderFields':async()=>new Map([[a,{'type':'Order','object':a,'data':i}]]),'fetchAllocationFields':async()=>new Map([[b,{'type':'Allocation','object':b,'type_raw':'0x2::allocation::Allocation<0x2::coin::COIN>','data':j}]]),'fetchProgressFields':async()=>new Map([[c,k]]),'fetchMachineNodes':async()=>l};}const h={'allocation':b,'progress':c,'machine':d,'service':e,'builder':ACCT};it('routes\x20a\x20completion\x20terminal\x20with\x20an\x20unsettled\x20pool\x20to\x20the\x20merchant\x20account',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[{'guard':'0xgsettle'}]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x1),expect(j[0x0]['beneficiary'])['toBe'](ACCT),expect(j[0x0]['detector'])['toBe']('settlement_pending'),expect(j[0x0]['title'])['toContain']('completion'),expect(j[0x0]['detail'])['toContain']('alloc_by_guard');}),it('routes\x20a\x20refund\x20terminal\x20to\x20the\x20buyer\x20(order\x20builder)\x20account',async()=>{const i=makeScope({'orders':[{'order':a,'role':'buyer'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[{'guard':'0xgrefund'}]}},{'current':'refunded','machine':d},f('refunded')),0x14);expect(j)['toHaveLength'](0x1),expect(j[0x0]['beneficiary'])['toBe'](ACCT),expect(j[0x0]['title'])['toContain']('refund/cancel');}),it('skips\x20a\x20pool\x20already\x20drained\x20(balance\x200)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'0','payment':[],'allocators':{'allocators':[]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('skips\x20a\x20pool\x20that\x20already\x20emitted\x20a\x20Payment',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':['0xpay1'],'allocators':{'allocators':[]}},{'current':'completed','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('skips\x20a\x20non-terminal\x20node\x20(still\x20has\x20outgoing\x20forwards)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,g(h,{'balance':'5000','payment':[],'allocators':{'allocators':[]}},{'current':'paid','machine':d},f('completed')),0x14);expect(j)['toHaveLength'](0x0);}),it('returns\x20nothing\x20when\x20the\x20order\x20batch\x20read\x20fails\x20(fail-safe)',async()=>{const i=makeScope({'services':[e],'orders':[{'order':a,'role':'merchant'}]}),j=await detectSettlementPending(i,NET,{...g(h,{'balance':'5000','payment':[]},{'current':'completed','machine':d},f('completed')),'fetchOrderFields':async()=>{throw new Error('rpc\x20down');}},0x14);expect(j)['toEqual']([]);});});function scanDepsFor(a,b){let c=0x2710;const d=[],e={'store':a,'payment':{'queryUnclaimed':async()=>({'balance':0x64n,'count':0x1})},'progress':{'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined},'settlement':{'fetchOrderFields':async()=>new Map(),'fetchAllocationFields':async()=>new Map(),'fetchProgressFields':async()=>new Map(),'fetchMachineNodes':async()=>[]},'execute':async f=>{return d['push']({'operation_type':f['operation_type'],'account':f['account'],'via':f['via']}),{'ok':!![],'digest':'DIGEST1'};},'now':()=>c,'logger':()=>{},...b};return{'deps':e,'executed':d,'advance':f=>{c+=f;},'setClock':f=>{c=f;}};}describe('runKeeperScan',()=>{it('skips\x20when\x20disabled\x20and\x20when\x20inside\x20the\x20cadence\x20interval',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a);await a['saveConfig'](NET,{'enabled':![]});let c=await runKeeperScan(NET,makeScope(),b);expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('disabled'),await a['saveConfig'](NET,{'enabled':!![]}),await a['setLastScanAt'](NET,0x2710),c=await runKeeperScan(NET,makeScope(),b),expect(c['scanned'])['toBe'](![]),expect(c['reason'])['toBe']('interval');}),it('auto-executes\x20a\x20payment\x20task\x20ONLY\x20with\x20a\x20covering\x20enabled\x20rule',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);let d=await runKeeperScan(NET,makeScope(),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0}),d=await runKeeperScan(NET,makeScope(),b,{'force':!![]}),expect(d['auto_executed'])['toBe'](0x1),expect(c[0x0])['toEqual']({'operation_type':'payment','account':ACCT,'via':'rule\x20krule_1'});const e=(await a['listTasks'](NET))[0x0];expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('auto_executed'),expect(e['rule_id'])['toBe']('krule_1'),expect(e['resolution_note'])['toContain']('DIGEST1');}),it('never\x20auto-executes\x20progress\x20tasks\x20(reminder-only\x20boundary)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a,{'payment':{'queryUnclaimed':async()=>null},'progress':{'fetchProgressFields':async()=>new Map([['0xprog1',{'machine':'0xm1','current':'start','session':[],'namedOperator':[{'name':'courier','operators':[ACCT]}]}]]),'fetchMachineNodes':async()=>[{'name':'shipped','pairs':[{'prev_node':'start','threshold':0x1,'forwards':[{'name':'deliver','weight':0x1,'namedOperator':'courier'}]}]}],'fetchMachinePermissionAddr':async()=>undefined,'fetchPermissionContext':async()=>undefined,'fetchOrderContext':async()=>undefined}});await a['upsertRule'](NET,{'id':'krule_p','enabled':!![],'detector':'progress_actionable','accounts':[],'auto_execute':!![],'created_at':0x0});const d=await runKeeperScan(NET,makeScope({'order_children':[{'type':'progress','object':'0xprog1'}]}),b,{'force':!![]});expect(d['opened'])['toBe'](0x1),expect(d['auto_executed'])['toBe'](0x0),expect(c)['toHaveLength'](0x0),expect((await a['listTasks'](NET))[0x0]['status'])['toBe']('pending');}),it('backs\x20off\x20after\x20a\x20failed\x20auto-exec\x20until\x20the\x20cooldown\x20passes',async()=>{const a=makeStore(),b=scanDepsFor(a,{'execute':async()=>({'ok':![],'error':'insufficient\x20gas'})});await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});let c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]});expect(c['auto_failed'])['toBe'](0x1);const d=(await a['listTasks'](NET))[0x0];expect(d['status'])['toBe']('pending'),expect(d['resolution_note'])['toBe']('insufficient\x20gas'),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x0),expect(c['auto_executed'])['toBe'](0x0),b['advance'](0x1f*0xea60),c=await runKeeperScan(NET,makeScope(),b['deps'],{'force':!![]}),expect(c['auto_failed'])['toBe'](0x1);}),it('caps\x20auto-executions\x20per\x20scan\x20(gas\x20guard)',async()=>{const a=makeStore(),{deps:b,executed:c}=scanDepsFor(a);await a['saveConfig'](NET,{'max_auto_execute_per_scan':0x1}),await a['upsertRule'](NET,{'id':'krule_1','enabled':!![],'detector':'payment_unclaimed','accounts':[],'auto_execute':!![],'created_at':0x0});const d=makeScope({'accounts':[ACCT,OTHER]}),e=await runKeeperScan(NET,d,b,{'force':!![]});expect(e['opened'])['toBe'](0x2),expect(e['auto_executed'])['toBe'](0x1),expect(c)['toHaveLength'](0x1),expect(await a['listTasks'](NET,{'status':'pending'}))['toHaveLength'](0x1);});}),describe('executeKeeperTask\x20(manual)',()=>{it('resolves\x20a\x20payment\x20task\x20as\x20manual_executed',async()=>{const a=makeStore();await a['upsertDesired'](NET,'payment_unclaimed',[paymentItem(ACCT,0x64n)],0x3e8);const b=(await a['listTasks'](NET))[0x0],{deps:c}=scanDepsFor(a),d=await executeKeeperTask(NET,b,c);expect(d['ok'])['toBe'](!![]);const e=await a['getTask'](NET,b['id']);expect(e['status'])['toBe']('executed'),expect(e['resolution'])['toBe']('manual_executed');}),it('refuses\x20reminder-only\x20tasks\x20(progress)\x20with\x20guidance',async()=>{const a=makeStore(),{deps:b}=scanDepsFor(a),c={'id':'ktask_x','dedupe_key':'progress_actionable:0xp:0xaaa111:shipped|deliver','detector':'progress_actionable','network':NET,'beneficiary':ACCT,'title':'Workflow\x20action\x20available','state_fingerprint':'1:1::named_operator','status':'pending','created_at':0x0,'updated_at':0x0},d=await executeKeeperTask(NET,c,b);expect(d['ok'])['toBe'](![]),expect(d['error'])['toContain']('reminder-only');});});
@@ -1,4 +1,4 @@
1
- export type KeeperDetectorKind = "payment_unclaimed" | "progress_actionable";
1
+ export type KeeperDetectorKind = "payment_unclaimed" | "progress_actionable" | "settlement_pending";
2
2
  export declare const KEEPER_DETECTORS: readonly KeeperDetectorKind[];
3
3
  export declare const AUTO_EXECUTABLE_DETECTORS: readonly KeeperDetectorKind[];
4
4
  export type KeeperTaskStatus = "pending" | "executed" | "dismissed" | "superseded";
@@ -1 +1 @@
1
- export const KEEPER_DETECTORS=['payment_unclaimed','progress_actionable'];export const AUTO_EXECUTABLE_DETECTORS=['payment_unclaimed'];export const KEEPER_DEFAULTS={'scan_interval_ms':0x1d4c0,'max_scan_objects':0x14,'max_auto_execute_per_scan':0x5,'auto_retry_cooldown_ms':0x1b7740};export const KEEPER_MIN={'scan_interval_ms':0x7530,'max_scan_objects':0x1,'max_auto_execute_per_scan':0x1,'auto_retry_cooldown_ms':0xea60};export function defaultKeeperConfig(){return{'enabled':!![],'detectors':{'payment_unclaimed':!![],'progress_actionable':!![]},'scan_interval_ms':KEEPER_DEFAULTS['scan_interval_ms'],'max_scan_objects':KEEPER_DEFAULTS['max_scan_objects'],'max_auto_execute_per_scan':KEEPER_DEFAULTS['max_auto_execute_per_scan'],'auto_retry_cooldown_ms':KEEPER_DEFAULTS['auto_retry_cooldown_ms']};}export function clampKeeperConfig(a){const b=(c,d,e)=>{const f=Number(c);return Number['isFinite'](f)?Math['max'](e,Math['floor'](f)):d;};return{...a,'scan_interval_ms':b(a['scan_interval_ms'],KEEPER_DEFAULTS['scan_interval_ms'],KEEPER_MIN['scan_interval_ms']),'max_scan_objects':b(a['max_scan_objects'],KEEPER_DEFAULTS['max_scan_objects'],KEEPER_MIN['max_scan_objects']),'max_auto_execute_per_scan':b(a['max_auto_execute_per_scan'],KEEPER_DEFAULTS['max_auto_execute_per_scan'],KEEPER_MIN['max_auto_execute_per_scan']),'auto_retry_cooldown_ms':b(a['auto_retry_cooldown_ms'],KEEPER_DEFAULTS['auto_retry_cooldown_ms'],KEEPER_MIN['auto_retry_cooldown_ms'])};}export function newKeeperTaskId(){return'ktask_'+Date['now']()['toString'](0x24)+'_'+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}export function newKeeperRuleId(){return'krule_'+Date['now']()['toString'](0x24)+'_'+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}
1
+ export const KEEPER_DETECTORS=['payment_unclaimed','progress_actionable','settlement_pending'];export const AUTO_EXECUTABLE_DETECTORS=['payment_unclaimed'];export const KEEPER_DEFAULTS={'scan_interval_ms':0x1d4c0,'max_scan_objects':0x14,'max_auto_execute_per_scan':0x5,'auto_retry_cooldown_ms':0x1b7740};export const KEEPER_MIN={'scan_interval_ms':0x7530,'max_scan_objects':0x1,'max_auto_execute_per_scan':0x1,'auto_retry_cooldown_ms':0xea60};export function defaultKeeperConfig(){return{'enabled':!![],'detectors':{'payment_unclaimed':!![],'progress_actionable':!![],'settlement_pending':!![]},'scan_interval_ms':KEEPER_DEFAULTS['scan_interval_ms'],'max_scan_objects':KEEPER_DEFAULTS['max_scan_objects'],'max_auto_execute_per_scan':KEEPER_DEFAULTS['max_auto_execute_per_scan'],'auto_retry_cooldown_ms':KEEPER_DEFAULTS['auto_retry_cooldown_ms']};}export function clampKeeperConfig(a){const b=(c,d,e)=>{const f=Number(c);return Number['isFinite'](f)?Math['max'](e,Math['floor'](f)):d;};return{...a,'scan_interval_ms':b(a['scan_interval_ms'],KEEPER_DEFAULTS['scan_interval_ms'],KEEPER_MIN['scan_interval_ms']),'max_scan_objects':b(a['max_scan_objects'],KEEPER_DEFAULTS['max_scan_objects'],KEEPER_MIN['max_scan_objects']),'max_auto_execute_per_scan':b(a['max_auto_execute_per_scan'],KEEPER_DEFAULTS['max_auto_execute_per_scan'],KEEPER_MIN['max_auto_execute_per_scan']),'auto_retry_cooldown_ms':b(a['auto_retry_cooldown_ms'],KEEPER_DEFAULTS['auto_retry_cooldown_ms'],KEEPER_MIN['auto_retry_cooldown_ms'])};}export function newKeeperTaskId(){return'ktask_'+Date['now']()['toString'](0x24)+'_'+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}export function newKeeperRuleId(){return'krule_'+Date['now']()['toString'](0x24)+'_'+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}
@@ -1,5 +1,5 @@
1
1
  import { MAX_ALLOCATOR_COUNT } from "@wowok/wowok";
2
- export type AllocationMode = "Amount" | "Rate" | "Surplus";
2
+ export type AllocationMode = "Amount" | "Rate" | "Surplus" | "RateGross";
3
3
  export type RecipientType = "GuardIdentifier" | "Entity" | "Signer";
4
4
  export type TriggerSource = "service_order_allocators" | "arbitration_fees" | "standalone";
5
5
  export interface AllocationScene {
@@ -24,6 +24,7 @@ export declare const ALLOCATION_MAX_SHARING_COUNT: 100;
24
24
  export declare const ALLOCATION_MODE_AMOUNT = 0;
25
25
  export declare const ALLOCATION_MODE_RATE = 1;
26
26
  export declare const ALLOCATION_MODE_SURPLUS = 2;
27
+ export declare const ALLOCATION_MODE_RATE_GROSS = 3;
27
28
  export declare const RATE_TOTAL_FULL = 10000;
28
29
  export declare const ALLOCATION_ERROR_CODES: {
29
30
  readonly ERECIPIENT_IDENTIFIER_NOT_ADDRESS: 1;
@@ -41,6 +42,8 @@ export declare const ALLOCATION_ERROR_CODES: {
41
42
  readonly EAMOUNT_EXCEEDS_MAX: 13;
42
43
  readonly EZERO_DISTRIBUTION: 14;
43
44
  readonly ERECIPIENT_NOT_FOR_OBJECT: 15;
45
+ readonly E_ONCE_TRIGGERED: 16;
46
+ readonly EMIXED_RATE_BASES: 17;
44
47
  };
45
48
  export declare const ORDER_ALLOCATION_ALREADY_SPECIFIED = "E_ALLOCATION_ALREADY_SPECIFIED";
46
49
  export declare const ALLOCATION_SCENES: AllocationScene[];
@@ -1 +1 @@
1
- import{MAX_SHARING_COUNT,MAX_ALLOCATOR_COUNT}from'@wowok/wowok';export{MAX_ALLOCATOR_COUNT};export const ALLOCATION_MAX_SHARING_COUNT=MAX_SHARING_COUNT;export const ALLOCATION_MODE_AMOUNT=0x0;export const ALLOCATION_MODE_RATE=0x1;export const ALLOCATION_MODE_SURPLUS=0x2;export const RATE_TOTAL_FULL=0x2710;export const ALLOCATION_ERROR_CODES={'ERECIPIENT_IDENTIFIER_NOT_ADDRESS':0x1,'EALLOCATOR_COUNT_EXCEEDED':0x2,'ENO_ALLOCATOR':0x3,'ERATE_NOT_10000':0x4,'EMULTIPLE_SURPLUS':0x5,'ERATE_EXCEEDS_10000':0x6,'EINSUFFICIENT_BALANCE':0x7,'EALLOCATORS_EMPTY':0x8,'ENO_PAYMENT_INFO':0x9,'ESHARING_COUNT_EXCEEDED':0xa,'ESHARING_MODE_INVALID':0xb,'EAMOUNT_BELOW_THRESHOLD':0xc,'EAMOUNT_EXCEEDS_MAX':0xd,'EZERO_DISTRIBUTION':0xe,'ERECIPIENT_NOT_FOR_OBJECT':0xf};export const ORDER_ALLOCATION_ALREADY_SPECIFIED='E_ALLOCATION_ALREADY_SPECIFIED';export const ALLOCATION_SCENES=[{'id':'allocation_standard_three_way_split','name':'Standard\x20three-way\x20split\x20(merchant\x20/\x20platform\x20/\x20logistics)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'All\x20three\x20Treasury\x20objects\x20must\x20use\x20the\x20same\x20Coin<T>\x20type\x20as\x20the\x20Allocation','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20Treasury\x20address','Guard\x20verifies\x20order.service\x20binding\x20(query\x201563)\x20to\x20prevent\x20cross-project\x20bypass','Guard\x20verifies\x20progress.current_node\x20===\x20\x27Complete\x27'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','order_allocators\x20immutable\x20after\x20Service\x20publish\x20(R-A-10)'],'recommended_templates':['T-A-02']},{'id':'allocation_merchant_full_payment','name':'Merchant\x20full\x20payment\x20(single\x20recipient,\x20100%)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'Simplest\x20configuration\x20—\x20single\x20Treasury\x20or\x20personal\x20address','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'single_relaxed','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate\x20sharing\x20=\x2010000','Guard\x20only\x20verifies\x20order\x20status\x20(no\x20complex\x20conditions)','who=Entity\x20can\x20be\x20either\x20Treasury\x20or\x20personal\x20wallet'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['Simplest\x20allocation\x20configuration','No\x20multi-party\x20coordination\x20required'],'recommended_templates':['T-A-01']},{'id':'allocation_refund_first_surplus_to_merchant','name':'Refund\x20first\x20+\x20surplus\x20to\x20merchant\x20(Amount\x20+\x20Surplus\x20hybrid)','trigger_source':'service_order_allocators','distribution_strategy':'amount_plus_surplus','coin_type_note':'Refund\x20amount\x20must\x20match\x20Coin<T>\x20precision','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Surplus'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x202\x20sharing\x20items','sharing[0]:\x20Amount=refund_value,\x20who=Entity(customer_address)','sharing[1]:\x20Surplus,\x20who=Entity(merchant_treasury)','fix\x20=\x20refund_value\x20(cached\x20Amount\x20sum)','threshold\x20=\x20refund_value\x20(ensure\x20sufficient\x20balance\x20for\x20Amount)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator','F-A-07:\x20fix\x20>=\x20threshold\x20(Amount\x20sum\x20must\x20cover\x20threshold)','fix\x20must\x20precisely\x20match\x20the\x20refund\x20amount'],'recommended_templates':['T-A-03']},{'id':'allocation_treasury_personal_alternatives','name':'Treasury\x20+\x20Personal\x20alternative\x20strategies\x20(caller-specified\x20guard)','trigger_source':'service_order_allocators','distribution_strategy':'first_match_alternatives','coin_type_note':'Both\x20target\x20addresses\x20must\x20accept\x20the\x20same\x20Coin<T>','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators,\x20each\x20with\x201\x20Rate=10000\x20sharing','Allocator[0]:\x20guard=guard_treasury,\x20who=Entity(treasury_address)','Allocator[1]:\x20guard=guard_personal,\x20who=Entity(personal_address)','Two\x20Guard\x20objects\x20must\x20be\x20different\x20addresses\x20(R-A-11)','caller-specified\x20guard:\x20caller\x20selects\x20Treasury\x20or\x20Personal\x20path\x20via\x20alloc_by_guard;\x20the\x20Passport\x20hard-verifies\x20the\x20selected\x20Guard\x20(failure\x20aborts\x20with\x20E_VERIFY_FAILED;\x20caller\x20must\x20switch\x20guard\x20and\x20retry)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-14:\x20allocators[].guard\x20must\x20be\x20unique','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','Guard\x20A\x20and\x20Guard\x20B\x20may\x20share\x20root/table\x20but\x20must\x20differ\x20in\x20description'],'recommended_templates':['T-A-04']},{'id':'allocation_tiered_by_order_amount','name':'Tiered\x20split\x20by\x20order\x20amount\x20(multi-Allocator\x20amount-threshold\x20switch)','trigger_source':'service_order_allocators','distribution_strategy':'tiered_by_amount','coin_type_note':'Amount\x20threshold\x20uses\x20Coin<T>\x20smallest\x20unit\x20(e.g.\x20MIST\x20for\x20WOW)','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators\x20triggered\x20by\x20mutually\x20exclusive\x20Guard\x20conditions','Allocator[0]:\x20guard\x20verifies\x20order.amount\x20<\x20threshold,\x20Rate=10000\x20to\x20merchant','Allocator[1]:\x20guard\x20verifies\x20order.amount\x20>=\x20threshold,\x20Rate=8000/2000\x20split','caller-specified\x20guard:\x20caller\x20selects\x20the\x20matching\x20Allocator\x20based\x20on\x20order\x20amount;\x20allocator\x20order\x20is\x20irrelevant','Guard\x20queries\x20order.amount\x20(query\x201561)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20(R-A-4-02\x20design\x20clarity)','Caller\x20must\x20select\x20correct\x20guard\x20based\x20on\x20order.amount\x20(no\x20auto-fallback)'],'recommended_templates':['T-A-05']},{'id':'allocation_dynamic_recipient','name':'Multi-role\x20split\x20with\x20dynamic\x20recipient\x20(GuardIdentifier)','trigger_source':'service_order_allocators','distribution_strategy':'dynamic_recipient','coin_type_note':'Passport\x20table\x20must\x20contain\x20address-typed\x20entry\x20at\x20the\x20referenced\x20identifier','typical_allocator_count':0x1,'sharing_who_types':['Entity','GuardIdentifier'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items','sharing[0]:\x20Rate=8000,\x20who=Entity(merchant_treasury)','sharing[1]:\x20Rate=1000,\x20who=Entity(platform_treasury)','sharing[2]:\x20Rate=1000,\x20who=GuardIdentifier(0)\x20—\x20resolves\x20from\x20Passport\x20table','Customer\x20submits\x20Passport\x20with\x20referrer\x20address\x20at\x20identifier=0'],'dependencies':['Service','Treasury','Guard','Passport','Order','Payment'],'key_constraints':['F-A-13:\x20Passport\x20table[identifier]\x20must\x20be\x20address\x20type\x20(else\x20ERECIPIENT_IDENTIFIER_NOT_ADDRESS)','Guard\x20must\x20verify\x20Passport\x20completeness','Customer\x20order\x20must\x20include\x20Passport\x20with\x20referrer\x20address'],'recommended_templates':['T-A-06']},{'id':'allocation_arbitration_fees','name':'Arbitration\x20fees\x20split\x20(arbitrator\x20/\x20platform)','trigger_source':'arbitration_fees','distribution_strategy':'pure_rate','coin_type_note':'Coin<T>\x20must\x20match\x20Arbitration\x27s\x20fee\x20Coin\x20type','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Triggered\x20by\x20the\x20Arbitration\x20fee-allocation\x20operation\x20(permission\x20365),\x20direct\x20or\x20Passport\x20path','Single\x20Allocator,\x202\x20Rate\x20sharing\x20items:\x208000\x20arbitrator\x20/\x202000\x20platform','payment_info\x20reuses\x20Arbitration\x27s\x20payment_info','Caller\x20must\x20hold\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'dependencies':['Arbitration','Treasury','Guard','Payment'],'key_constraints':['Independent\x20from\x20Service-order\x20Allocation','Requires\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'recommended_templates':['T-A-08']},{'id':'allocation_refund_to_order','name':'Refund\x20Allocator\x20(100%\x20to\x20Order\x20object)','trigger_source':'service_order_allocators','distribution_strategy':'refund_to_order','coin_type_note':'who=Entity\x20must\x20be\x20the\x20Order\x20object\x20address\x20(NOT\x20a\x20personal\x20wallet)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate=10000\x20sharing','who=Entity(order_address)\x20—\x20funds\x20flow\x20back\x20to\x20Order,\x20not\x20personal\x20wallet','Guard\x20verifies\x20customer\x20refund\x20request\x20and\x20eligibility','Customer-side\x20risk\x20assessment\x20adds\x208-point\x20weight\x20(onchain_topology\x20graph\x20evaluation)'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['who=Entity\x20MUST\x20be\x20Order\x20object\x20address\x20(not\x20personal\x20address)','Customer\x20due-diligence\x20rewards\x20this\x20configuration\x20(8-point\x20weight)','Refund\x20funds\x20return\x20to\x20Order\x20for\x20downstream\x20handling'],'recommended_templates':['T-A-07']},{'id':'allocation_max_capped_retain','name':'Max-capped\x20allocation\x20(retain\x20residual\x20balance)','trigger_source':'service_order_allocators','distribution_strategy':'max_capped','coin_type_note':'max\x20field\x20uses\x20Coin<T>\x20smallest\x20unit','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['Single\x20Allocator\x20with\x20max\x20field\x20set','max\x20triple\x20role:\x20Amount\x20cap\x20+\x20Rate\x20base\x20+\x20Surplus\x20cap','Amount\x20sharing\x20consumes\x20fix;\x20Rate\x20sharing\x20uses\x20(max\x20-\x20fix)\x20as\x20base','Residual\x20balance\x20remains\x20in\x20Allocation\x20for\x20subsequent\x20alloc()\x20calls'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','max\x20-\x20fix\x20becomes\x20Rate\x20base\x20(NOT\x20balance\x20-\x20fix)','Residual\x20balance\x20may\x20be\x20claimed\x20by\x20re-triggering\x20alloc()'],'recommended_templates':[]},{'id':'allocation_multi_node_trigger','name':'Multi-Machine-node\x20triggered\x20allocation\x20(Complete\x20/\x20Refund\x20/\x20Lost)','trigger_source':'service_order_allocators','distribution_strategy':'multi_node_trigger','coin_type_note':'All\x20Allocators\x20share\x20the\x20same\x20Allocation\x27s\x20Coin<T>','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['3\x20Allocators\x20mapped\x20to\x20Machine\x20terminal\x20nodes\x20(Complete/Refund/Lost)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20progress.current_node\x20==\x20<node_name>','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20terminal\x20node\x20active\x20at\x20a\x20time)','Machine.required_allocators[]\x20describes\x20each\x20trigger_node\x20mapping'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive','Sequence-sensitive:\x20business-flow\x20order','Machine.required_allocators[trigger_node]\x20must\x20map\x20to\x20Allocator\x20indices'],'recommended_templates':[]},{'id':'allocation_standalone_periodic_split','name':'Standalone\x20periodic\x20split\x20(investment\x20dividends\x20/\x20shared\x20income)','trigger_source':'standalone','distribution_strategy':'periodic_split','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20asset\x20being\x20distributed\x20(e.g.\x20profit\x20token)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x20N\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20beneficiary\x20wallet\x20(not\x20Treasury)','Guard\x20verifies\x20time-based\x20trigger\x20(e.g.\x20context(Clock).timestamp\x20>=\x20next_release)\x20or\x20signer\x20authorization','User\x20calls\x20receive()\x20to\x20deposit\x20funds,\x20then\x20alloc()\x20to\x20trigger\x20distribution','No\x20Service/Order/Progress/Machine\x20context\x20required'],'dependencies':['Treasury','Guard','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20+\x20Passport\x20MUST\x20be\x20sufficient','Caller\x20is\x20fully\x20responsible\x20for\x20receive\x20→\x20alloc\x20lifecycle\x20(no\x20auto-trigger)','Guard\x20should\x20bind\x20Signer\x20to\x20prevent\x20unauthorized\x20alloc()\x20calls'],'recommended_templates':['T-A-09']},{'id':'allocation_standalone_vesting','name':'Standalone\x20vesting\x20release\x20(time-locked\x20multi-stage\x20unlock)','trigger_source':'standalone','distribution_strategy':'time_locked_vesting','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20vested\x20asset\x20(e.g.\x20locked\x20team\x20tokens)','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate','Surplus'],'guard_requirement':'multiple_unique','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['N\x20Allocators,\x20each\x20mapped\x20to\x20a\x20vesting\x20stage\x20(e.g.\x2025%\x20at\x20month\x2012,\x2025%\x20at\x20month\x2024,\x2050%\x20surplus\x20at\x20month\x2036)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20context(Clock).timestamp\x20>=\x20stage_unlock_time','Amount\x20sharing\x20per\x20stage\x20with\x20max\x20field\x20capping\x20the\x20cumulative\x20release','Final\x20Allocator\x20uses\x20Surplus\x20to\x20drain\x20remaining\x20balance\x20after\x20last\x20vesting\x20stage','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20stage\x20active\x20at\x20a\x20time,\x20based\x20on\x20timestamp)','User\x20calls\x20receive()\x20to\x20deposit\x20locked\x20tokens,\x20then\x20alloc()\x20at\x20each\x20vesting\x20milestone'],'dependencies':['Treasury','Guard','Passport','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator\x20(final\x20stage\x20uses\x20Surplus\x20to\x20drain\x20remainder)','F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20time-lock\x20MUST\x20be\x20enforced','Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20by\x20timestamp\x20(R-A-4-02)','Caller\x20must\x20wait\x20for\x20time-lock\x20expiry\x20before\x20alloc()\x20succeeds;\x20otherwise\x20alloc()\x20silently\x20returns\x20(R-A-4-01)'],'recommended_templates':['T-A-10']}];export const ALLOCATION_LEDGER_VERSION='1.0.0';export function getScenesByTriggerSource(a){return ALLOCATION_SCENES['filter'](b=>b['trigger_source']===a);}export function getScenesByMode(a){return ALLOCATION_SCENES['filter'](b=>b['modes_used']['includes'](a));}export function getScenesByStrategy(a){return ALLOCATION_SCENES['filter'](b=>b['distribution_strategy']===a);}export function findSceneById(a){return ALLOCATION_SCENES['find'](b=>b['id']===a);}export function inferSceneFromIntent(a){const b=a['toLowerCase']();if(b['includes']('arbitration')||b['includes']('fees\x20alloc'))return findSceneById('allocation_arbitration_fees');if(b['includes']('standalone')||b['includes']('periodic\x20split')||b['includes']('investment\x20dividend')||b['includes']('shared\x20income')||b['includes']('dividend'))return findSceneById('allocation_standalone_periodic_split');if(b['includes']('vesting')||b['includes']('time-lock')||b['includes']('unlock\x20period')||b['includes']('locked\x20release')||b['includes']('token\x20unlock'))return findSceneById('allocation_standalone_vesting');if(b['includes']('refund')){if(b['includes']('order')||b['includes']('100%'))return findSceneById('allocation_refund_to_order');if(b['includes']('surplus')||b['includes']('merchant'))return findSceneById('allocation_refund_first_surplus_to_merchant');}if(b['includes']('alternative')||b['includes']('priority')||b['includes']('treasury')&&b['includes']('personal'))return findSceneById('allocation_treasury_personal_alternatives');if(b['includes']('tiered')||b['includes']('threshold\x20switch'))return findSceneById('allocation_tiered_by_order_amount');if(b['includes']('dynamic\x20recipient')||b['includes']('referrer')||b['includes']('guardidentifier'))return findSceneById('allocation_dynamic_recipient');if(b['includes']('retain')||b['includes']('max'))return findSceneById('allocation_max_capped_retain');if(b['includes']('multi-node')||b['includes']('multi\x20machine')||b['includes']('multi_node'))return findSceneById('allocation_multi_node_trigger');const c=(a['match'](/%/g)||[])['length'];if(c<=0x1)return findSceneById('allocation_merchant_full_payment');if(c>=0x2)return findSceneById('allocation_standard_three_way_split');return undefined;}export function getAllScenes(){return[...ALLOCATION_SCENES];}export function getScenesCount(){return ALLOCATION_SCENES['length'];}export function allocationModeToNumber(a){switch(a){case'Amount':return ALLOCATION_MODE_AMOUNT;case'Rate':return ALLOCATION_MODE_RATE;case'Surplus':return ALLOCATION_MODE_SURPLUS;}}export function allocationModeFromNumber(a){switch(a){case ALLOCATION_MODE_AMOUNT:return'Amount';case ALLOCATION_MODE_RATE:return'Rate';case ALLOCATION_MODE_SURPLUS:return'Surplus';default:throw new Error('Invalid\x20AllocationMode\x20number:\x20'+a);}}export function getRecipientType(a){if('GuardIdentifier'in a)return'GuardIdentifier';if('Entity'in a)return'Entity';return'Signer';}export function isSignerRecipient(a){return'Signer'in a;}export function isEntityRecipient(a){return'Entity'in a;}export function isGuardIdentifierRecipient(a){return'GuardIdentifier'in a;}export function getErrorName(a){for(const [b,d]of Object['entries'](ALLOCATION_ERROR_CODES)){if(d===a)return b;}return undefined;}export function getErrorDescription(a){const b={0x1:'GuardIdentifier\x20resolved\x20value\x20is\x20not\x20an\x20address\x20type',0x2:'Allocator\x20count\x20exceeds\x20MAX_ALLOCATOR_COUNT\x20(100)',0x3:'No\x20Allocator\x20in\x20the\x20allocators\x20vector',0x4:'Pure\x20Rate\x20mode\x20sum\x20!=\x2010000\x20(no\x20Surplus\x20to\x20absorb\x20remainder)',0x5:'Multiple\x20Surplus\x20sharing\x20in\x20a\x20single\x20Allocator',0x6:'Rate\x20+\x20Surplus\x20sum\x20>\x2010000',0x7:'balance\x20<\x20threshold\x20(insufficient\x20balance\x20to\x20trigger\x20alloc)',0x8:'allocators.allocators\x20is\x20empty',0x9:'payment_info\x20is\x20None\x20when\x20alloc()\x20is\x20called',0xa:'sharing\x20count\x20exceeds\x20MAX_SHARING_COUNT\x20(100)',0xb:'sharing\x20mode\x20is\x20not\x200\x20(Amount)\x20/\x201\x20(Rate)\x20/\x202\x20(Surplus)',0xc:'Amount\x20sum\x20(fix)\x20<\x20threshold',0xd:'Amount\x20sum\x20(fix)\x20>\x20max',0xe:'distribution\x20computes\x20to\x20zero\x20while\x20the\x20pool\x20still\x20holds\x20funds\x20(or\x20balance\x20is\x200)',0xf:'GuardIdentifier\x20recipient\x20address\x20!=\x20payment_info.for_object\x20anchor\x20(abort\x20fires\x20only\x20when\x20a\x20for_object\x20binding\x20is\x20declared)'};return b[a];}
1
+ import{MAX_SHARING_COUNT,MAX_ALLOCATOR_COUNT}from'@wowok/wowok';export{MAX_ALLOCATOR_COUNT};export const ALLOCATION_MAX_SHARING_COUNT=MAX_SHARING_COUNT;export const ALLOCATION_MODE_AMOUNT=0x0;export const ALLOCATION_MODE_RATE=0x1;export const ALLOCATION_MODE_SURPLUS=0x2;export const ALLOCATION_MODE_RATE_GROSS=0x3;export const RATE_TOTAL_FULL=0x2710;export const ALLOCATION_ERROR_CODES={'ERECIPIENT_IDENTIFIER_NOT_ADDRESS':0x1,'EALLOCATOR_COUNT_EXCEEDED':0x2,'ENO_ALLOCATOR':0x3,'ERATE_NOT_10000':0x4,'EMULTIPLE_SURPLUS':0x5,'ERATE_EXCEEDS_10000':0x6,'EINSUFFICIENT_BALANCE':0x7,'EALLOCATORS_EMPTY':0x8,'ENO_PAYMENT_INFO':0x9,'ESHARING_COUNT_EXCEEDED':0xa,'ESHARING_MODE_INVALID':0xb,'EAMOUNT_BELOW_THRESHOLD':0xc,'EAMOUNT_EXCEEDS_MAX':0xd,'EZERO_DISTRIBUTION':0xe,'ERECIPIENT_NOT_FOR_OBJECT':0xf,'E_ONCE_TRIGGERED':0x10,'EMIXED_RATE_BASES':0x11};export const ORDER_ALLOCATION_ALREADY_SPECIFIED='E_ALLOCATION_ALREADY_SPECIFIED';export const ALLOCATION_SCENES=[{'id':'allocation_standard_three_way_split','name':'Standard\x20three-way\x20split\x20(merchant\x20/\x20platform\x20/\x20logistics)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'All\x20three\x20Treasury\x20objects\x20must\x20use\x20the\x20same\x20Coin<T>\x20type\x20as\x20the\x20Allocation','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20Treasury\x20address','Guard\x20verifies\x20order.service\x20binding\x20(query\x201563)\x20to\x20prevent\x20cross-project\x20bypass','Guard\x20verifies\x20progress.current_node\x20===\x20\x27Complete\x27'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','order_allocators\x20immutable\x20after\x20Service\x20publish\x20(R-A-10)'],'recommended_templates':['T-A-02']},{'id':'allocation_merchant_full_payment','name':'Merchant\x20full\x20payment\x20(single\x20recipient,\x20100%)','trigger_source':'service_order_allocators','distribution_strategy':'pure_rate','coin_type_note':'Simplest\x20configuration\x20—\x20single\x20Treasury\x20or\x20personal\x20address','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'single_relaxed','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate\x20sharing\x20=\x2010000','Guard\x20only\x20verifies\x20order\x20status\x20(no\x20complex\x20conditions)','who=Entity\x20can\x20be\x20either\x20Treasury\x20or\x20personal\x20wallet'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['Simplest\x20allocation\x20configuration','No\x20multi-party\x20coordination\x20required'],'recommended_templates':['T-A-01']},{'id':'allocation_refund_first_surplus_to_merchant','name':'Refund\x20first\x20+\x20surplus\x20to\x20merchant\x20(Amount\x20+\x20Surplus\x20hybrid)','trigger_source':'service_order_allocators','distribution_strategy':'amount_plus_surplus','coin_type_note':'Refund\x20amount\x20must\x20match\x20Coin<T>\x20precision','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Surplus'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x202\x20sharing\x20items','sharing[0]:\x20Amount=refund_value,\x20who=Entity(customer_address)','sharing[1]:\x20Surplus,\x20who=Entity(merchant_treasury)','fix\x20=\x20refund_value\x20(cached\x20Amount\x20sum)','threshold\x20=\x20refund_value\x20(ensure\x20sufficient\x20balance\x20for\x20Amount)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator','F-A-07:\x20fix\x20>=\x20threshold\x20(Amount\x20sum\x20must\x20cover\x20threshold)','fix\x20must\x20precisely\x20match\x20the\x20refund\x20amount'],'recommended_templates':['T-A-03']},{'id':'allocation_treasury_personal_alternatives','name':'Treasury\x20+\x20Personal\x20alternative\x20strategies\x20(caller-specified\x20guard)','trigger_source':'service_order_allocators','distribution_strategy':'first_match_alternatives','coin_type_note':'Both\x20target\x20addresses\x20must\x20accept\x20the\x20same\x20Coin<T>','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators,\x20each\x20with\x201\x20Rate=10000\x20sharing','Allocator[0]:\x20guard=guard_treasury,\x20who=Entity(treasury_address)','Allocator[1]:\x20guard=guard_personal,\x20who=Entity(personal_address)','Two\x20Guard\x20objects\x20must\x20be\x20different\x20addresses\x20(R-A-11)','caller-specified\x20guard:\x20caller\x20selects\x20Treasury\x20or\x20Personal\x20path\x20via\x20alloc_by_guard;\x20the\x20Passport\x20hard-verifies\x20the\x20selected\x20Guard\x20(failure\x20aborts\x20with\x20E_VERIFY_FAILED;\x20caller\x20must\x20switch\x20guard\x20and\x20retry)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-14:\x20allocators[].guard\x20must\x20be\x20unique','Treasury\x20Permission\x20should\x20match\x20Service\x20Permission\x20(R-A-12)','Guard\x20A\x20and\x20Guard\x20B\x20may\x20share\x20root/table\x20but\x20must\x20differ\x20in\x20description'],'recommended_templates':['T-A-04']},{'id':'allocation_tiered_by_order_amount','name':'Tiered\x20split\x20by\x20order\x20amount\x20(multi-Allocator\x20amount-threshold\x20switch)','trigger_source':'service_order_allocators','distribution_strategy':'tiered_by_amount','coin_type_note':'Amount\x20threshold\x20uses\x20Coin<T>\x20smallest\x20unit\x20(e.g.\x20MIST\x20for\x20WOW)','typical_allocator_count':0x2,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['2\x20Allocators\x20triggered\x20by\x20mutually\x20exclusive\x20Guard\x20conditions','Allocator[0]:\x20guard\x20verifies\x20order.amount\x20<\x20threshold,\x20Rate=10000\x20to\x20merchant','Allocator[1]:\x20guard\x20verifies\x20order.amount\x20>=\x20threshold,\x20Rate=8000/2000\x20split','caller-specified\x20guard:\x20caller\x20selects\x20the\x20matching\x20Allocator\x20based\x20on\x20order\x20amount;\x20allocator\x20order\x20is\x20irrelevant','Guard\x20queries\x20order.amount\x20(query\x201561)'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20(R-A-4-02\x20design\x20clarity)','Caller\x20must\x20select\x20correct\x20guard\x20based\x20on\x20order.amount\x20(no\x20auto-fallback)'],'recommended_templates':['T-A-05']},{'id':'allocation_dynamic_recipient','name':'Multi-role\x20split\x20with\x20dynamic\x20recipient\x20(GuardIdentifier)','trigger_source':'service_order_allocators','distribution_strategy':'dynamic_recipient','coin_type_note':'Passport\x20table\x20must\x20contain\x20address-typed\x20entry\x20at\x20the\x20referenced\x20identifier','typical_allocator_count':0x1,'sharing_who_types':['Entity','GuardIdentifier'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x203\x20Rate\x20sharing\x20items','sharing[0]:\x20Rate=8000,\x20who=Entity(merchant_treasury)','sharing[1]:\x20Rate=1000,\x20who=Entity(platform_treasury)','sharing[2]:\x20Rate=1000,\x20who=GuardIdentifier(0)\x20—\x20resolves\x20from\x20Passport\x20table','Customer\x20submits\x20Passport\x20with\x20referrer\x20address\x20at\x20identifier=0'],'dependencies':['Service','Treasury','Guard','Passport','Order','Payment'],'key_constraints':['F-A-13:\x20Passport\x20table[identifier]\x20must\x20be\x20address\x20type\x20(else\x20ERECIPIENT_IDENTIFIER_NOT_ADDRESS)','Guard\x20must\x20verify\x20Passport\x20completeness','Customer\x20order\x20must\x20include\x20Passport\x20with\x20referrer\x20address'],'recommended_templates':['T-A-06']},{'id':'allocation_arbitration_fees','name':'Arbitration\x20fees\x20split\x20(arbitrator\x20/\x20platform)','trigger_source':'arbitration_fees','distribution_strategy':'pure_rate','coin_type_note':'Coin<T>\x20must\x20match\x20Arbitration\x27s\x20fee\x20Coin\x20type','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Triggered\x20by\x20the\x20Arbitration\x20fee-allocation\x20operation\x20(permission\x20365),\x20direct\x20or\x20Passport\x20path','Single\x20Allocator,\x202\x20Rate\x20sharing\x20items:\x208000\x20arbitrator\x20/\x202000\x20platform','payment_info\x20reuses\x20Arbitration\x27s\x20payment_info','Caller\x20must\x20hold\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'dependencies':['Arbitration','Treasury','Guard','Payment'],'key_constraints':['Independent\x20from\x20Service-order\x20Allocation','Requires\x20ARBITRATION_FEES_ALLOC=365\x20permission'],'recommended_templates':['T-A-08']},{'id':'allocation_refund_to_order','name':'Refund\x20Allocator\x20(100%\x20to\x20Order\x20object)','trigger_source':'service_order_allocators','distribution_strategy':'refund_to_order','coin_type_note':'who=Entity\x20must\x20be\x20the\x20Order\x20object\x20address\x20(NOT\x20a\x20personal\x20wallet)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x201\x20Rate=10000\x20sharing','who=Entity(order_address)\x20—\x20funds\x20flow\x20back\x20to\x20Order,\x20not\x20personal\x20wallet','Guard\x20verifies\x20customer\x20refund\x20request\x20and\x20eligibility','Customer-side\x20risk\x20assessment\x20adds\x208-point\x20weight\x20(onchain_topology\x20graph\x20evaluation)'],'dependencies':['Service','Guard','Order','Payment'],'key_constraints':['who=Entity\x20MUST\x20be\x20Order\x20object\x20address\x20(not\x20personal\x20address)','Customer\x20due-diligence\x20rewards\x20this\x20configuration\x20(8-point\x20weight)','Refund\x20funds\x20return\x20to\x20Order\x20for\x20downstream\x20handling'],'recommended_templates':['T-A-07']},{'id':'allocation_max_capped_retain','name':'Max-capped\x20allocation\x20(retain\x20residual\x20balance)','trigger_source':'service_order_allocators','distribution_strategy':'max_capped','coin_type_note':'max\x20field\x20uses\x20Coin<T>\x20smallest\x20unit','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate'],'guard_requirement':'required','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['Single\x20Allocator\x20with\x20max\x20field\x20set','max\x20triple\x20role:\x20Amount\x20cap\x20+\x20NET\x20Rate\x20base\x20+\x20Surplus\x20cap','Amount\x20sharing\x20consumes\x20fix;\x20NET\x20Rate\x20sharing\x20uses\x20(max\x20-\x20fix)\x20as\x20base\x20(RateGross\x20uses\x20max\x20itself)','Residual\x20balance\x20remains\x20in\x20Allocation\x20for\x20subsequent\x20alloc()\x20calls'],'dependencies':['Service','Treasury','Guard','Order','Payment'],'key_constraints':['F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','NET\x20Rate:\x20max\x20-\x20fix\x20becomes\x20the\x20base\x20(NOT\x20balance\x20-\x20fix);\x20RateGross:\x20the\x20base\x20is\x20max\x20(fix\x20not\x20removed)','Residual\x20balance\x20may\x20be\x20claimed\x20by\x20re-triggering\x20alloc()'],'recommended_templates':[]},{'id':'allocation_multi_node_trigger','name':'Multi-Machine-node\x20triggered\x20allocation\x20(Complete\x20/\x20Refund\x20/\x20Lost)','trigger_source':'service_order_allocators','distribution_strategy':'multi_node_trigger','coin_type_note':'All\x20Allocators\x20share\x20the\x20same\x20Allocation\x27s\x20Coin<T>','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'multiple_unique','non_zero_threshold':![],'uses_max':![],'common_patterns':['3\x20Allocators\x20mapped\x20to\x20Machine\x20terminal\x20nodes\x20(Complete/Refund/Lost)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20progress.current_node\x20==\x20<node_name>','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20terminal\x20node\x20active\x20at\x20a\x20time)','Machine.required_allocators[]\x20describes\x20each\x20trigger_node\x20mapping'],'dependencies':['Service','Treasury','Guard','Order','Progress','Machine','Payment'],'key_constraints':['Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive','Sequence-sensitive:\x20business-flow\x20order','Machine.required_allocators[trigger_node]\x20must\x20map\x20to\x20Allocator\x20indices'],'recommended_templates':[]},{'id':'allocation_standalone_periodic_split','name':'Standalone\x20periodic\x20split\x20(investment\x20dividends\x20/\x20shared\x20income)','trigger_source':'standalone','distribution_strategy':'periodic_split','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20asset\x20being\x20distributed\x20(e.g.\x20profit\x20token)','typical_allocator_count':0x1,'sharing_who_types':['Entity'],'modes_used':['Rate'],'guard_requirement':'required','non_zero_threshold':![],'uses_max':![],'common_patterns':['Single\x20Allocator,\x20N\x20Rate\x20sharing\x20items,\x20sum(rates)\x20===\x2010000','Each\x20sharing.who=Entity\x20points\x20to\x20a\x20beneficiary\x20wallet\x20(not\x20Treasury)','Guard\x20verifies\x20time-based\x20trigger\x20(e.g.\x20context(Clock).timestamp\x20>=\x20next_release)\x20or\x20signer\x20authorization','User\x20calls\x20receive()\x20to\x20deposit\x20funds,\x20then\x20alloc()\x20to\x20trigger\x20distribution','No\x20Service/Order/Progress/Machine\x20context\x20required'],'dependencies':['Treasury','Guard','Payment'],'key_constraints':['F-A-05:\x20sum(rates)\x20===\x2010000\x20(pure\x20Rate\x20mode)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20+\x20Passport\x20MUST\x20be\x20sufficient','Caller\x20is\x20fully\x20responsible\x20for\x20receive\x20→\x20alloc\x20lifecycle\x20(no\x20auto-trigger)','Guard\x20should\x20bind\x20Signer\x20to\x20prevent\x20unauthorized\x20alloc()\x20calls'],'recommended_templates':['T-A-09']},{'id':'allocation_standalone_vesting','name':'Standalone\x20vesting\x20release\x20(time-locked\x20multi-stage\x20unlock)','trigger_source':'standalone','distribution_strategy':'time_locked_vesting','coin_type_note':'Coin<T>\x20must\x20match\x20the\x20vested\x20asset\x20(e.g.\x20locked\x20team\x20tokens)','typical_allocator_count':0x3,'sharing_who_types':['Entity'],'modes_used':['Amount','Rate','Surplus'],'guard_requirement':'multiple_unique','non_zero_threshold':!![],'uses_max':!![],'common_patterns':['N\x20Allocators,\x20each\x20mapped\x20to\x20a\x20vesting\x20stage\x20(e.g.\x2025%\x20at\x20month\x2012,\x2025%\x20at\x20month\x2024,\x2050%\x20surplus\x20at\x20month\x2036)','Each\x20Allocator\x27s\x20Guard\x20verifies\x20context(Clock).timestamp\x20>=\x20stage_unlock_time','Amount\x20sharing\x20per\x20stage\x20with\x20max\x20field\x20capping\x20the\x20cumulative\x20release','Final\x20Allocator\x20uses\x20Surplus\x20to\x20drain\x20remaining\x20balance\x20after\x20last\x20vesting\x20stage','Mutually\x20exclusive\x20Guard\x20conditions\x20(only\x20one\x20stage\x20active\x20at\x20a\x20time,\x20based\x20on\x20timestamp)','User\x20calls\x20receive()\x20to\x20deposit\x20locked\x20tokens,\x20then\x20alloc()\x20at\x20each\x20vesting\x20milestone'],'dependencies':['Treasury','Guard','Passport','Payment'],'key_constraints':['F-A-04:\x20at\x20most\x201\x20Surplus\x20per\x20Allocator\x20(final\x20stage\x20uses\x20Surplus\x20to\x20drain\x20remainder)','F-A-08:\x20Amount\x20sum\x20<=\x20max\x20(EAMOUNT_EXCEEDS_MAX)','R-A-3-04:\x20standalone\x20mode\x20has\x20no\x20Service-layer\x20access\x20control\x20—\x20Guard\x20time-lock\x20MUST\x20be\x20enforced','Guard\x20conditions\x20must\x20be\x20mutually\x20exclusive\x20by\x20timestamp\x20(R-A-4-02)','Caller\x20must\x20wait\x20for\x20time-lock\x20expiry\x20before\x20alloc()\x20succeeds;\x20otherwise\x20alloc()\x20silently\x20returns\x20(R-A-4-01)'],'recommended_templates':['T-A-10']}];export const ALLOCATION_LEDGER_VERSION='1.0.0';export function getScenesByTriggerSource(a){return ALLOCATION_SCENES['filter'](b=>b['trigger_source']===a);}export function getScenesByMode(a){return ALLOCATION_SCENES['filter'](b=>b['modes_used']['includes'](a));}export function getScenesByStrategy(a){return ALLOCATION_SCENES['filter'](b=>b['distribution_strategy']===a);}export function findSceneById(a){return ALLOCATION_SCENES['find'](b=>b['id']===a);}export function inferSceneFromIntent(a){const b=a['toLowerCase']();if(b['includes']('arbitration')||b['includes']('fees\x20alloc'))return findSceneById('allocation_arbitration_fees');if(b['includes']('standalone')||b['includes']('periodic\x20split')||b['includes']('investment\x20dividend')||b['includes']('shared\x20income')||b['includes']('dividend'))return findSceneById('allocation_standalone_periodic_split');if(b['includes']('vesting')||b['includes']('time-lock')||b['includes']('unlock\x20period')||b['includes']('locked\x20release')||b['includes']('token\x20unlock'))return findSceneById('allocation_standalone_vesting');if(b['includes']('refund')){if(b['includes']('order')||b['includes']('100%'))return findSceneById('allocation_refund_to_order');if(b['includes']('surplus')||b['includes']('merchant'))return findSceneById('allocation_refund_first_surplus_to_merchant');}if(b['includes']('alternative')||b['includes']('priority')||b['includes']('treasury')&&b['includes']('personal'))return findSceneById('allocation_treasury_personal_alternatives');if(b['includes']('tiered')||b['includes']('threshold\x20switch'))return findSceneById('allocation_tiered_by_order_amount');if(b['includes']('dynamic\x20recipient')||b['includes']('referrer')||b['includes']('guardidentifier'))return findSceneById('allocation_dynamic_recipient');if(b['includes']('retain')||b['includes']('max'))return findSceneById('allocation_max_capped_retain');if(b['includes']('multi-node')||b['includes']('multi\x20machine')||b['includes']('multi_node'))return findSceneById('allocation_multi_node_trigger');const c=(a['match'](/%/g)||[])['length'];if(c<=0x1)return findSceneById('allocation_merchant_full_payment');if(c>=0x2)return findSceneById('allocation_standard_three_way_split');return undefined;}export function getAllScenes(){return[...ALLOCATION_SCENES];}export function getScenesCount(){return ALLOCATION_SCENES['length'];}export function allocationModeToNumber(a){switch(a){case'Amount':return ALLOCATION_MODE_AMOUNT;case'Rate':return ALLOCATION_MODE_RATE;case'Surplus':return ALLOCATION_MODE_SURPLUS;case'RateGross':return ALLOCATION_MODE_RATE_GROSS;}}export function allocationModeFromNumber(a){switch(a){case ALLOCATION_MODE_AMOUNT:return'Amount';case ALLOCATION_MODE_RATE:return'Rate';case ALLOCATION_MODE_SURPLUS:return'Surplus';case ALLOCATION_MODE_RATE_GROSS:return'RateGross';default:throw new Error('Invalid\x20AllocationMode\x20number:\x20'+a);}}export function getRecipientType(a){if('GuardIdentifier'in a)return'GuardIdentifier';if('Entity'in a)return'Entity';return'Signer';}export function isSignerRecipient(a){return'Signer'in a;}export function isEntityRecipient(a){return'Entity'in a;}export function isGuardIdentifierRecipient(a){return'GuardIdentifier'in a;}export function getErrorName(a){for(const [b,d]of Object['entries'](ALLOCATION_ERROR_CODES)){if(d===a)return b;}return undefined;}export function getErrorDescription(a){const b={0x1:'GuardIdentifier\x20resolved\x20value\x20is\x20not\x20an\x20address\x20type',0x2:'Allocator\x20count\x20exceeds\x20MAX_ALLOCATOR_COUNT\x20(100)',0x3:'No\x20Allocator\x20in\x20the\x20allocators\x20vector',0x4:'Pure\x20Rate\x20mode\x20sum\x20!=\x2010000\x20(no\x20Surplus\x20to\x20absorb\x20remainder)',0x5:'Multiple\x20Surplus\x20sharing\x20in\x20a\x20single\x20Allocator',0x6:'Rate\x20+\x20Surplus\x20sum\x20>\x2010000',0x7:'balance\x20<\x20threshold\x20(insufficient\x20balance\x20to\x20trigger\x20alloc)',0x8:'allocators.allocators\x20is\x20empty',0x9:'payment_info\x20is\x20None\x20when\x20alloc()\x20is\x20called',0xa:'sharing\x20count\x20exceeds\x20MAX_SHARING_COUNT\x20(100)',0xb:'sharing\x20mode\x20is\x20not\x200\x20(Amount)\x20/\x201\x20(Rate)\x20/\x202\x20(Surplus)\x20/\x203\x20(RateGross)',0xc:'Amount\x20sum\x20(fix)\x20<\x20threshold',0xd:'Amount\x20sum\x20(fix)\x20>\x20max',0xe:'distribution\x20computes\x20to\x20zero\x20while\x20the\x20pool\x20still\x20holds\x20funds\x20(or\x20balance\x20is\x200)',0xf:'GuardIdentifier\x20recipient\x20address\x20!=\x20payment_info.for_object\x20anchor\x20(abort\x20fires\x20only\x20when\x20a\x20for_object\x20binding\x20is\x20declared)',0x10:'once-trigger\x20key\x20already\x20consumed\x20—\x20the\x20guard\x20submitted\x20the\x20reserved\x20identifier\x20255\x20and\x20its\x20raw\x20submission\x20bytes\x20were\x20recorded\x20as\x20a\x20(guard,\x20allocator\x20index,\x20raw\x20bytes)\x20dynamic-field\x20key\x20on\x20this\x20Allocation',0x11:'mixed\x20rate\x20bases\x20—\x20one\x20allocator\x20carries\x20both\x20NET\x20Rate\x20and\x20RateGross\x20entries\x20while\x20a\x20fixed\x20Amount\x20total\x20is\x20present\x20(rejected\x20only\x20when\x20fix\x20>\x200;\x20with\x20fix\x20==\x200\x20the\x20two\x20bases\x20coincide\x20and\x20mixing\x20is\x20allowed)'};return b[a];}
@@ -97,6 +97,8 @@ export interface AllocationConstraintChecklist {
97
97
  F_A_13_guard_identifier_is_address: boolean;
98
98
  F_A_14_guard_addresses_unique: boolean;
99
99
  F_A_15_order_allocators_immutable_after_publish: boolean;
100
+ F_A_16_rate_gross_sum_le_10000: boolean;
101
+ F_A_17_no_mixed_rate_bases: boolean;
100
102
  }
101
103
  export type AllocationPuzzleDimension = "A" | "B" | "C" | "D" | "E" | "F";
102
104
  export interface AllocationPuzzle {