@oakagentkit/core 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/build/dist/api/addresses.d.ts +93 -0
  2. package/build/dist/api/addresses.js +1 -1
  3. package/build/dist/api/chain.js +1 -1
  4. package/build/dist/api/history.js +1 -1
  5. package/build/dist/api/identity-link.js +1 -1
  6. package/build/dist/api/metadata.js +1 -1
  7. package/build/dist/api/modules/beefy/boosts.js +1 -1
  8. package/build/dist/api/modules/beefy/clm.js +1 -1
  9. package/build/dist/api/modules/beefy/guard.js +1 -1
  10. package/build/dist/api/modules/beefy/index.js +1 -1
  11. package/build/dist/api/modules/beefy/liquidity.js +1 -1
  12. package/build/dist/api/modules/beefy/management.js +1 -1
  13. package/build/dist/api/modules/beefy/vaults.js +1 -1
  14. package/build/dist/api/modules/clanker/extensions.js +1 -1
  15. package/build/dist/api/modules/clanker/index.js +1 -1
  16. package/build/dist/api/modules/clanker/manage.js +1 -1
  17. package/build/dist/api/modules/clanker/pool-config.js +1 -1
  18. package/build/dist/api/modules/clanker/protocol.js +1 -1
  19. package/build/dist/api/modules/clanker/state.js +1 -1
  20. package/build/dist/api/modules/erc8004/common.js +1 -1
  21. package/build/dist/api/modules/erc8004/domain.js +1 -1
  22. package/build/dist/api/modules/erc8004/index.js +1 -1
  23. package/build/dist/api/modules/erc8004/management.js +1 -1
  24. package/build/dist/api/modules/erc8004/reputation.js +1 -1
  25. package/build/dist/api/modules/erc8004/services.js +1 -1
  26. package/build/dist/api/modules/erc8004/validation.js +1 -1
  27. package/build/dist/api/modules/grove/index.js +1 -1
  28. package/build/dist/api/modules/heyresearch/backoff.d.ts +6 -0
  29. package/build/dist/api/modules/heyresearch/backoff.js +1 -0
  30. package/build/dist/api/modules/heyresearch/builder-feed.d.ts +62 -0
  31. package/build/dist/api/modules/heyresearch/builder-feed.js +1 -0
  32. package/build/dist/api/modules/heyresearch/index.d.ts +3 -0
  33. package/build/dist/api/modules/heyresearch/index.js +1 -1
  34. package/build/dist/api/modules/heyresearch/proof-reads.d.ts +7 -0
  35. package/build/dist/api/modules/heyresearch/proof-reads.js +1 -0
  36. package/build/dist/api/modules/heyresearch/public-reads.d.ts +1 -0
  37. package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
  38. package/build/dist/api/modules/heyresearch/scan.d.ts +31 -0
  39. package/build/dist/api/modules/heyresearch/scan.js +1 -0
  40. package/build/dist/api/modules/heyresearch/status-labels.d.ts +5 -0
  41. package/build/dist/api/modules/heyresearch/status-labels.js +1 -0
  42. package/build/dist/api/modules/heyresearch/token-facts.d.ts +123 -0
  43. package/build/dist/api/modules/heyresearch/token-facts.js +1 -0
  44. package/build/dist/api/modules/hoodag/chain-reads.js +1 -1
  45. package/build/dist/api/modules/hoodag/index.js +1 -1
  46. package/build/dist/api/modules/hoodag/management.js +1 -1
  47. package/build/dist/api/modules/hoodag/public-reads.js +1 -1
  48. package/build/dist/api/modules/hoodag/reconstruct.js +1 -1
  49. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  50. package/build/dist/api/modules/hoodlock/buyback.js +1 -1
  51. package/build/dist/api/modules/hoodlock/commerce.js +1 -1
  52. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  53. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  54. package/build/dist/api/modules/hoodlock/index.js +1 -1
  55. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  56. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  57. package/build/dist/api/modules/hoodlock/public.js +1 -1
  58. package/build/dist/api/modules/hookr/actions.d.ts +1 -1
  59. package/build/dist/api/modules/hookr/actions.js +1 -1
  60. package/build/dist/api/modules/hookr/addons.js +1 -1
  61. package/build/dist/api/modules/hookr/agent-gate.d.ts +63 -0
  62. package/build/dist/api/modules/hookr/agent-gate.js +1 -0
  63. package/build/dist/api/modules/hookr/contracts.js +1 -1
  64. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  65. package/build/dist/api/modules/hookr/discovery.js +1 -1
  66. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  67. package/build/dist/api/modules/hookr/index.d.ts +1 -0
  68. package/build/dist/api/modules/hookr/index.js +1 -1
  69. package/build/dist/api/modules/hookr/launch-options.d.ts +119 -0
  70. package/build/dist/api/modules/hookr/launch-options.js +1 -0
  71. package/build/dist/api/modules/hookr/launch-profile.d.ts +5 -0
  72. package/build/dist/api/modules/hookr/launch-profile.js +1 -0
  73. package/build/dist/api/modules/hookr/launch-receipt.d.ts +144 -0
  74. package/build/dist/api/modules/hookr/launch-receipt.js +1 -0
  75. package/build/dist/api/modules/hookr/launch.d.ts +58 -0
  76. package/build/dist/api/modules/hookr/launch.js +1 -0
  77. package/build/dist/api/modules/hookr/liquidity.d.ts +48 -0
  78. package/build/dist/api/modules/hookr/liquidity.js +1 -0
  79. package/build/dist/api/modules/hookr/lp-positions.d.ts +2 -0
  80. package/build/dist/api/modules/hookr/lp-positions.js +1 -0
  81. package/build/dist/api/modules/hookr/lp-reads.d.ts +52 -0
  82. package/build/dist/api/modules/hookr/lp-reads.js +1 -0
  83. package/build/dist/api/modules/hookr/lp-receipt.d.ts +136 -0
  84. package/build/dist/api/modules/hookr/lp-receipt.js +1 -0
  85. package/build/dist/api/modules/hookr/lp-state.d.ts +33 -0
  86. package/build/dist/api/modules/hookr/lp-state.js +1 -0
  87. package/build/dist/api/modules/hookr/pins.d.ts +43 -0
  88. package/build/dist/api/modules/hookr/pins.js +1 -0
  89. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  90. package/build/dist/api/modules/hookr/read-utils.d.ts +59 -0
  91. package/build/dist/api/modules/hookr/read-utils.js +1 -0
  92. package/build/dist/api/modules/hookr/relay.js +1 -1
  93. package/build/dist/api/modules/hookr/revenue.js +1 -1
  94. package/build/dist/api/modules/kyberswap/index.js +1 -1
  95. package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
  96. package/build/dist/api/modules/lighter/index.js +1 -1
  97. package/build/dist/api/modules/longbow/administration.js +1 -1
  98. package/build/dist/api/modules/longbow/analytics.js +1 -1
  99. package/build/dist/api/modules/longbow/fixed.js +1 -1
  100. package/build/dist/api/modules/longbow/index.js +1 -1
  101. package/build/dist/api/modules/longbow/nft.js +1 -1
  102. package/build/dist/api/modules/longbow/rebates.js +1 -1
  103. package/build/dist/api/modules/longbow/staking.js +1 -1
  104. package/build/dist/api/modules/meridian/index.js +1 -1
  105. package/build/dist/api/modules/meridian/markets.js +1 -1
  106. package/build/dist/api/modules/meridian/rfq.js +1 -1
  107. package/build/dist/api/modules/merkl/discovery.js +1 -1
  108. package/build/dist/api/modules/merkl/index.js +1 -1
  109. package/build/dist/api/modules/merkl/manage.js +1 -1
  110. package/build/dist/api/modules/merkl/protocol.js +1 -1
  111. package/build/dist/api/modules/morpho/allocator.js +1 -1
  112. package/build/dist/api/modules/morpho/bundles.js +1 -1
  113. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  114. package/build/dist/api/modules/morpho/index.js +1 -1
  115. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  116. package/build/dist/api/modules/morpho/midnight.js +1 -1
  117. package/build/dist/api/modules/morpho/protocol.js +1 -1
  118. package/build/dist/api/modules/morpho/vault-management.js +1 -1
  119. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  120. package/build/dist/api/modules/morpho/vault-v2.js +1 -1
  121. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  122. package/build/dist/api/modules/netnet/card-read.js +1 -1
  123. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  124. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  125. package/build/dist/api/modules/netnet/desk-read.js +1 -1
  126. package/build/dist/api/modules/netnet/financial.js +1 -1
  127. package/build/dist/api/modules/netnet/index.js +1 -1
  128. package/build/dist/api/modules/netnet/staking.js +1 -1
  129. package/build/dist/api/modules/orbio/index.js +1 -1
  130. package/build/dist/api/modules/pons/claim.js +1 -1
  131. package/build/dist/api/modules/pons/index.js +1 -1
  132. package/build/dist/api/modules/pons/launch-status.js +1 -1
  133. package/build/dist/api/modules/pons/prices.js +1 -1
  134. package/build/dist/api/modules/pons/reads.js +1 -1
  135. package/build/dist/api/modules/pons/swap-terms.js +1 -1
  136. package/build/dist/api/modules/pons/trade.js +1 -1
  137. package/build/dist/api/modules/poolstrade/index.js +1 -1
  138. package/build/dist/api/modules/priors/coverage.js +1 -1
  139. package/build/dist/api/modules/priors/discovery.js +1 -1
  140. package/build/dist/api/modules/priors/features.js +1 -1
  141. package/build/dist/api/modules/priors/index.js +1 -1
  142. package/build/dist/api/modules/priors/integration.js +1 -1
  143. package/build/dist/api/modules/priors/market.js +1 -1
  144. package/build/dist/api/modules/priors/pt.js +1 -1
  145. package/build/dist/api/modules/priors/savings-exit.js +1 -1
  146. package/build/dist/api/modules/priors/starter-line.js +1 -1
  147. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  148. package/build/dist/api/modules/relay/bootstrap.js +1 -1
  149. package/build/dist/api/modules/relay/discovery.js +1 -1
  150. package/build/dist/api/modules/relay/inbound.js +1 -1
  151. package/build/dist/api/modules/relay/index.js +1 -1
  152. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  153. package/build/dist/api/modules/relay/reads.js +1 -1
  154. package/build/dist/api/modules/spark/actions.js +1 -1
  155. package/build/dist/api/modules/spark/details.js +1 -1
  156. package/build/dist/api/modules/spark/index.js +1 -1
  157. package/build/dist/api/modules/spark/management.js +1 -1
  158. package/build/dist/api/modules/steakhouse/analytics.js +1 -1
  159. package/build/dist/api/modules/steakhouse/erc4626.js +1 -1
  160. package/build/dist/api/modules/steakhouse/index.js +1 -1
  161. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  162. package/build/dist/api/modules/steakhouse/management.js +1 -1
  163. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  164. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  165. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  166. package/build/dist/api/modules/tickerspring/discovery.js +1 -1
  167. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  168. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  169. package/build/dist/api/modules/tickerspring/index.js +1 -1
  170. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  171. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  172. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  173. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  174. package/build/dist/api/modules/tickerspring/research.js +1 -1
  175. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  176. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  177. package/build/dist/api/modules/uniswap/auction.js +1 -1
  178. package/build/dist/api/modules/uniswap/batch.js +1 -1
  179. package/build/dist/api/modules/uniswap/common.js +1 -1
  180. package/build/dist/api/modules/uniswap/fees.js +1 -1
  181. package/build/dist/api/modules/uniswap/index.js +1 -1
  182. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  183. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  184. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  185. package/build/dist/api/modules/uniswap/pools.js +1 -1
  186. package/build/dist/api/modules/uniswap/position.js +1 -1
  187. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  188. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  189. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  190. package/build/dist/api/modules/uniswap/trade.js +1 -1
  191. package/build/dist/api/modules/uniswap/v2.js +1 -1
  192. package/build/dist/api/modules/uniswap/v3.js +1 -1
  193. package/build/dist/api/modules/uniswap/v4.js +1 -1
  194. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  195. package/build/dist/api/modules/velora/claims.js +1 -1
  196. package/build/dist/api/modules/velora/delta-reads.js +1 -1
  197. package/build/dist/api/modules/velora/index.js +1 -1
  198. package/build/dist/api/modules/wormhole/index.d.ts +5 -0
  199. package/build/dist/api/modules/wormhole/index.js +1 -0
  200. package/build/dist/api/modules/wormhole/license.d.ts +2 -0
  201. package/build/dist/api/modules/wormhole/license.js +1 -0
  202. package/build/dist/api/modules/wormhole/quotetext.d.ts +36 -0
  203. package/build/dist/api/modules/wormhole/quotetext.js +1 -0
  204. package/build/dist/api/modules/wormhole/scan-text.d.ts +40 -0
  205. package/build/dist/api/modules/wormhole/scan-text.js +1 -0
  206. package/build/dist/api/modules/wormhole/token-check.d.ts +54 -0
  207. package/build/dist/api/modules/wormhole/token-check.js +1 -0
  208. package/build/dist/api/positions.js +1 -1
  209. package/build/dist/api/pricenote.js +1 -1
  210. package/build/dist/api/prices.js +1 -1
  211. package/build/dist/api/pricing.js +1 -1
  212. package/build/dist/api/rpc.js +1 -1
  213. package/build/dist/api/send.js +1 -1
  214. package/build/dist/api/signing-registry.js +1 -1
  215. package/build/dist/api/signing.js +1 -1
  216. package/build/dist/api/simulate.js +1 -1
  217. package/build/dist/api/swap.js +1 -1
  218. package/build/dist/api/tokens.js +1 -1
  219. package/build/dist/api/tool-policy.js +1 -1
  220. package/build/dist/api/types.d.ts +7 -0
  221. package/build/dist/chunks/{QHHZDXRG.js → 2FSX7MMR.js} +1 -1
  222. package/build/dist/chunks/{RTBOMWCB.js → 2LM7U4S7.js} +1 -1
  223. package/build/dist/chunks/{BBVKWG65.js → 2MSQ6JII.js} +1 -1
  224. package/build/dist/chunks/{T6MTTMLQ.js → 2UU5TBBB.js} +1 -1
  225. package/build/dist/chunks/{OW7GOYKA.js → 2W46IRX6.js} +1 -1
  226. package/build/dist/chunks/{6LLOTPH2.js → 3EFV4FQF.js} +1 -1
  227. package/build/dist/chunks/{IAXKPME3.js → 3NDVXEBR.js} +1 -1
  228. package/build/dist/chunks/3SC5UI35.js +1 -0
  229. package/build/dist/chunks/{TCS3ICNE.js → 3WBDHUV2.js} +1 -1
  230. package/build/dist/chunks/{UPPYXY74.js → 4AKIXLXH.js} +1 -1
  231. package/build/dist/chunks/{RRSODRGT.js → 4GAWMCQC.js} +1 -1
  232. package/build/dist/chunks/{ZGXNTWYG.js → 4GHVIBL5.js} +1 -1
  233. package/build/dist/chunks/{NHCRJC5X.js → 4KQZTPMS.js} +1 -1
  234. package/build/dist/chunks/{N77ANGBT.js → 4X2JOQ2L.js} +1 -1
  235. package/build/dist/chunks/{ZPM2MFXZ.js → 52DHGSG4.js} +1 -1
  236. package/build/dist/chunks/{2CS3M32D.js → 57HAXNQV.js} +1 -1
  237. package/build/dist/chunks/5IIR3GIN.js +1 -0
  238. package/build/dist/chunks/{CAU44UWP.js → 5O5ZE3ZV.js} +1 -1
  239. package/build/dist/chunks/5OEHZJ6X.js +1 -0
  240. package/build/dist/chunks/{CBA776XQ.js → 5VHH5PW3.js} +1 -1
  241. package/build/dist/chunks/{NCEJZWGX.js → 66VBACC2.js} +1 -1
  242. package/build/dist/chunks/{6HV5BR7P.js → 6AWTAE4Q.js} +1 -1
  243. package/build/dist/chunks/{JRVTSGAT.js → 6UPPUHCL.js} +1 -1
  244. package/build/dist/chunks/{MEMVFR7Z.js → 6ZYLNB2B.js} +1 -1
  245. package/build/dist/chunks/7XLEYOZH.js +1 -0
  246. package/build/dist/chunks/{Q4RZQCDS.js → AAGDMH54.js} +1 -1
  247. package/build/dist/chunks/ACN2BFMA.js +1 -0
  248. package/build/dist/chunks/{L24EOVLT.js → AJP5LDM2.js} +1 -1
  249. package/build/dist/chunks/{F2YH72GF.js → ALK6NKFP.js} +1 -1
  250. package/build/dist/chunks/{EC5W3UZD.js → AMICUXS6.js} +1 -1
  251. package/build/dist/chunks/{5LQBHXFA.js → BX7XQANB.js} +1 -1
  252. package/build/dist/chunks/{QNPEKNWM.js → CEIPDEXZ.js} +1 -1
  253. package/build/dist/chunks/{HFQS5344.js → CQCVFRQ5.js} +1 -1
  254. package/build/dist/chunks/{OJLMF5AR.js → CUNQ5RG5.js} +1 -1
  255. package/build/dist/chunks/{IWALIX7Q.js → CXLEQCP3.js} +1 -1
  256. package/build/dist/chunks/{VJ3W2V3B.js → CY75R4FK.js} +1 -1
  257. package/build/dist/chunks/{65QFM4JU.js → DCTUYDWF.js} +1 -1
  258. package/build/dist/chunks/DHOBTJRD.js +1 -0
  259. package/build/dist/chunks/{N37ZLNCT.js → DRWWPBOQ.js} +1 -1
  260. package/build/dist/chunks/{7B5UH2VS.js → DZGEQBO7.js} +1 -1
  261. package/build/dist/chunks/{RFJCG4NA.js → E7R3J4H7.js} +1 -1
  262. package/build/dist/chunks/{7T4BYFD4.js → EGUMOD3A.js} +1 -1
  263. package/build/dist/chunks/ELZNT5Q3.js +1 -0
  264. package/build/dist/chunks/EPZ7SWKM.js +1 -0
  265. package/build/dist/chunks/{IUETZH6I.js → EXRKBBX2.js} +1 -1
  266. package/build/dist/chunks/{K7HIKXNT.js → FBSUTF3B.js} +1 -1
  267. package/build/dist/chunks/{LFN3OODW.js → FUXT7GRK.js} +1 -1
  268. package/build/dist/chunks/G6HCV67X.js +1 -0
  269. package/build/dist/chunks/{HNMOB76J.js → GGUEKSR4.js} +1 -1
  270. package/build/dist/chunks/{GZ5TW3WB.js → GIV5JMTE.js} +1 -1
  271. package/build/dist/chunks/{OMTCWXQR.js → GJY3P6OG.js} +1 -1
  272. package/build/dist/chunks/HOEQVPY7.js +1 -0
  273. package/build/dist/chunks/{3R3C3CU5.js → IBXYIN7Q.js} +1 -1
  274. package/build/dist/chunks/{SXX52Y27.js → IUE6RASI.js} +1 -1
  275. package/build/dist/chunks/J2XAEVKC.js +1 -0
  276. package/build/dist/chunks/{AYM5L6L7.js → J3GFCBZZ.js} +1 -1
  277. package/build/dist/chunks/JNZZLA2A.js +1 -0
  278. package/build/dist/chunks/{T3MGNKA6.js → JPOYTTTW.js} +1 -1
  279. package/build/dist/chunks/{AZGMF26W.js → JST5JGAP.js} +1 -1
  280. package/build/dist/chunks/{BG4S6MSN.js → JVI26KQO.js} +1 -1
  281. package/build/dist/chunks/{FBQWTWPT.js → JWCOXLYA.js} +1 -1
  282. package/build/dist/chunks/{G7UKNO2I.js → KHJFXJBU.js} +1 -1
  283. package/build/dist/chunks/{HQVC6X3T.js → KSZMMNXK.js} +1 -1
  284. package/build/dist/chunks/{O7PQDUVT.js → L3ZM77SJ.js} +1 -1
  285. package/build/dist/chunks/{QRUC7EFE.js → L62M7LOB.js} +1 -1
  286. package/build/dist/chunks/{22S4SFD5.js → L7YBCMZU.js} +1 -1
  287. package/build/dist/chunks/{H6ED3RHF.js → LMVB3B6T.js} +1 -1
  288. package/build/dist/chunks/{UIIJWIR6.js → LQGPMOD2.js} +1 -1
  289. package/build/dist/chunks/{WLACEU2Y.js → LQUDJCAR.js} +1 -1
  290. package/build/dist/chunks/LT5P6PZW.js +1 -0
  291. package/build/dist/chunks/M7U3A4EH.js +3 -0
  292. package/build/dist/chunks/MFNP4KOK.js +1 -0
  293. package/build/dist/chunks/MKQVS3IO.js +1 -0
  294. package/build/dist/chunks/{7US6PD56.js → MLPWQTBS.js} +1 -1
  295. package/build/dist/chunks/{5XFXH2JT.js → NATG6YA6.js} +1 -1
  296. package/build/dist/chunks/{O47JXRXN.js → NAYRD43N.js} +1 -1
  297. package/build/dist/chunks/{6L6DSMCU.js → NMYGNJIJ.js} +1 -1
  298. package/build/dist/chunks/NRBIXV7V.js +1 -0
  299. package/build/dist/chunks/{D6VP3N27.js → NSOEDRBU.js} +1 -1
  300. package/build/dist/chunks/{HL2MLC3O.js → NU4K3TEZ.js} +1 -1
  301. package/build/dist/chunks/NWSPC3NH.js +1 -0
  302. package/build/dist/chunks/{I7NUTSSX.js → OE3CLZHR.js} +1 -1
  303. package/build/dist/chunks/{2NA6JLEC.js → OQVZVR2S.js} +1 -1
  304. package/build/dist/chunks/{D3OWLDVB.js → OVK4EEOD.js} +1 -1
  305. package/build/dist/chunks/{Q2VMH2LB.js → PARWLWXW.js} +1 -1
  306. package/build/dist/chunks/{DHXVYHT4.js → PTAWEHKB.js} +1 -1
  307. package/build/dist/chunks/{DVKDWXEJ.js → PWBL4WKB.js} +1 -1
  308. package/build/dist/chunks/{PR2QED25.js → PZHR4ITH.js} +1 -1
  309. package/build/dist/chunks/{JG24LNUI.js → Q356HHCL.js} +1 -1
  310. package/build/dist/chunks/{OG5HRQU4.js → QRDDKA4I.js} +1 -1
  311. package/build/dist/chunks/{YR3QJVJQ.js → QXNPPCOU.js} +1 -1
  312. package/build/dist/chunks/{6NR7SVRO.js → QYYFRAWY.js} +1 -1
  313. package/build/dist/chunks/{QR7ALOR4.js → R53P2K3C.js} +1 -1
  314. package/build/dist/chunks/{5RKWSFD2.js → R7FXNZRM.js} +1 -1
  315. package/build/dist/chunks/{CCEWSOBT.js → R7QPJQP6.js} +1 -1
  316. package/build/dist/chunks/{SLSPWXR6.js → R7SXC74O.js} +1 -1
  317. package/build/dist/chunks/{IHGVCPVA.js → RAKUK5VR.js} +1 -1
  318. package/build/dist/chunks/{7LDAJ6BM.js → S3HNPTXA.js} +1 -1
  319. package/build/dist/chunks/SI6GCOAS.js +1 -0
  320. package/build/dist/chunks/{WIDTTGSH.js → SJPM5ST4.js} +1 -1
  321. package/build/dist/chunks/{QYHJWU5T.js → SJPYXNOK.js} +1 -1
  322. package/build/dist/chunks/{VY3P34PY.js → SKQGLGES.js} +1 -1
  323. package/build/dist/chunks/{ZT67OMLW.js → SOYQOE5P.js} +1 -1
  324. package/build/dist/chunks/{GUBB5P6V.js → SQZRVIVF.js} +1 -1
  325. package/build/dist/chunks/{E24S22BZ.js → SSTROLQM.js} +1 -1
  326. package/build/dist/chunks/{DGGOO4RN.js → SXAIXD56.js} +1 -1
  327. package/build/dist/chunks/{D4WURN33.js → SXX3VTBP.js} +1 -1
  328. package/build/dist/chunks/{UXG67LH3.js → TCPPYBGQ.js} +1 -1
  329. package/build/dist/chunks/TFVWAYHY.js +1 -0
  330. package/build/dist/chunks/{67TJOOBI.js → TLJPVYRJ.js} +1 -1
  331. package/build/dist/chunks/{ULJ6E4HP.js → TMGWXDCZ.js} +1 -1
  332. package/build/dist/chunks/{NMFVXBTL.js → TNSKEHPC.js} +1 -1
  333. package/build/dist/chunks/{C2FEXLMA.js → TQL7UDFL.js} +1 -1
  334. package/build/dist/chunks/{QXFJZGVB.js → TWCSCRFS.js} +1 -1
  335. package/build/dist/chunks/{2EDXKJ3B.js → TWSTOFN3.js} +1 -1
  336. package/build/dist/chunks/{X6G4BD35.js → U3F6DDML.js} +1 -1
  337. package/build/dist/chunks/{XGUKLFBU.js → UFS2RVEZ.js} +1 -1
  338. package/build/dist/chunks/{RM5W63LO.js → UNZRE3YU.js} +1 -1
  339. package/build/dist/chunks/{GECX5U3F.js → USSOVTD5.js} +1 -1
  340. package/build/dist/chunks/V2OOOV6B.js +1 -0
  341. package/build/dist/chunks/{IRWEY7TQ.js → V5LTA42G.js} +1 -1
  342. package/build/dist/chunks/{TAI63P6E.js → VC2RCYQE.js} +1 -1
  343. package/build/dist/chunks/{3ZVGHC6S.js → VFSRRDLY.js} +1 -1
  344. package/build/dist/chunks/{XW7RH7YY.js → VVEUJ36E.js} +1 -1
  345. package/build/dist/chunks/{5EHQM6DM.js → WQ6H62DM.js} +1 -1
  346. package/build/dist/chunks/{TDN3C4IG.js → WQQJ7UPJ.js} +1 -1
  347. package/build/dist/chunks/{F3TJCOVV.js → WTSMPDT5.js} +1 -1
  348. package/build/dist/chunks/{BYXBS45D.js → WVXW6VL3.js} +1 -1
  349. package/build/dist/chunks/WWFOYZT2.js +1 -0
  350. package/build/dist/chunks/WWNAGOCD.js +1 -0
  351. package/build/dist/chunks/X2NJSQUY.js +203 -0
  352. package/build/dist/chunks/{FKAA7VUR.js → XMA25DXR.js} +1 -1
  353. package/build/dist/chunks/{C3ZZSGSP.js → XQUPZ3GU.js} +1 -1
  354. package/build/dist/chunks/XQXLFF7Y.js +1 -0
  355. package/build/dist/chunks/XV2HQKND.js +1 -0
  356. package/build/dist/chunks/{QZM7CWZW.js → XVFLT275.js} +1 -1
  357. package/build/dist/chunks/{BV3AHLH5.js → XWEFKXKA.js} +1 -1
  358. package/build/dist/chunks/{BEPSWFJX.js → Y2KH6DCE.js} +1 -1
  359. package/build/dist/chunks/{NKY3DT34.js → YA5WWDEW.js} +1 -1
  360. package/build/dist/chunks/YHB55C5T.js +1 -0
  361. package/build/dist/chunks/YQUKU2LS.js +1 -0
  362. package/build/dist/chunks/{72AWP4BM.js → YZSTP2E6.js} +1 -1
  363. package/build/dist/chunks/{T3NPRRTY.js → Z7RL4NGX.js} +1 -1
  364. package/build/dist/chunks/{YMB553OJ.js → ZT47KN7A.js} +1 -1
  365. package/build/dist/chunks/{NUTHT4FE.js → ZUG6MG46.js} +1 -1
  366. package/package.json +1 -1
  367. package/build/dist/chunks/6SCCW74G.js +0 -1
  368. package/build/dist/chunks/DD7755AW.js +0 -1
  369. package/build/dist/chunks/EYYUWFUR.js +0 -1
  370. package/build/dist/chunks/JRO6WTK4.js +0 -1
  371. package/build/dist/chunks/MNFU7PO3.js +0 -1
  372. package/build/dist/chunks/N3GWFLG6.js +0 -1
  373. package/build/dist/chunks/UMK564HS.js +0 -1
  374. package/build/dist/chunks/XPFVT2EA.js +0 -1
  375. package/build/dist/chunks/XUJSQV52.js +0 -1
@@ -1 +1 @@
1
- import{a as c,b as T,e as v,f as F,g as I}from"./IAXKPME3.js";import{a as l}from"./UWOFA6GV.js";import{c as A,g,h as S}from"./73N3TOJL.js";import{a as h}from"./XPFVT2EA.js";import{a as d}from"./5YS5V2LK.js";import{encodeFunctionData as y,getAddress as M,parseAbi as j,parseAbiItem as D,zeroAddress as H}from"viem";var x=M("0x000000001f26a0044baa66024e7b6599c61963f8"),_=D("event AuctionCreated(address indexed auction,address indexed token,uint256 amount,bytes configData)"),n=j(["function currency() view returns (address)","function token() view returns (address)","function startBlock() view returns (uint64)","function endBlock() view returns (uint64)","function claimBlock() view returns (uint64)","function validationHook() view returns (address)","function clearingPrice() view returns (uint256)","function isGraduated() view returns (bool)","function bids(uint256) view returns ((uint64 startBlock,uint24 startCumulativeMps,uint64 exitedBlock,uint256 maxPrice,address owner,uint256 amountQ96,uint256 tokensFilled))","function submitBid(uint256 maxPrice,uint128 amount,address owner,uint256 prevTickPrice,bytes hookData) payable returns (uint256)","function exitBid(uint256)","function exitPartiallyFilledBid(uint256,uint64,uint64)","function claimTokens(uint256)","function claimTokensBatch(address,uint256[])","function checkpoint()","function sweepCurrency()","function sweepUnsoldTokens()"]);async function $(s,B){let o=T(B.auction),t=c(B.creationBlock,"creationBlock",64,!0),e=await s.getLogs({address:x,event:_,args:{auction:o},fromBlock:t,toBlock:t,strict:!0});if(e.length!==1||!g(e[0].address,x)||!S(e[0].args.auction,o))throw new d("Auction has no matching AuctionCreated event at the pinned CCA factory and creationBlock.");return o}async function Q(s,B){let o=s.clientFor(h),t=await $(o,B),e=await o.getBlockNumber(),[a,k,i,b,m,C,u,w]=await Promise.all([o.readContract({address:t,abi:n,functionName:"currency",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"token",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"startBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"endBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"claimBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"validationHook",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"clearingPrice",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"isGraduated",blockNumber:e})]);return{auction:t,currency:a,saleToken:k,startBlock:i,endBlock:b,claimBlock:m,validationHook:C,clearingPrice:u,graduated:w,blockNumber:e}}var U={auction:A,creationBlock:l(),bidId:l(),amount:l(),maxPrice:l(),prevTickPrice:l(),lastFullyFilledCheckpointBlock:l(),outbidBlock:l(),mode:{type:"string",enum:["full","partial"]},bidIds:{type:"array",minItems:1,maxItems:50,items:l()}};function R(s){let o=["status","bid","exit","claim","checkpoint","sweep_currency","sweep_tokens"].map(t=>({name:`uniswap_auction_${t}`,inputSchema:{type:"object",additionalProperties:!1,required:["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode"]:[]],properties:U},async execute(e,a){I(e,["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode","lastFullyFilledCheckpointBlock","outbidBlock"]:t==="claim"?["bidId","bidIds"]:t==="status"?["bidId"]:[]]);let i=await Q(s,e),b=s.clientFor(h),[m,C]=await Promise.all([v(s,i.currency,i.blockNumber),v(s,i.saleToken,i.blockNumber)]),u=e.bidId===void 0?void 0:await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[c(e.bidId,"bidId",256,!0)],blockNumber:i.blockNumber});if(t==="status")return{auction:i.auction,paymentToken:m,saleToken:C,startBlock:i.startBlock.toString(),endBlock:i.endBlock.toString(),claimBlock:i.claimBlock.toString(),validationHook:i.validationHook,clearingPrice:i.clearingPrice.toString(),graduated:i.graduated,...u?{bid:{...u,startBlock:u.startBlock.toString(),exitedBlock:u.exitedBlock.toString(),maxPrice:u.maxPrice.toString(),amountQ96:u.amountQ96.toString(),tokensFilled:u.tokensFilled.toString()}}:{},summary:"CCA prices use currency-base-units per sale-token-base-unit in Q96. Clearing price/graduation reflect the latest checkpoint and may lag the head."};let w=[],f,N=0n;if(t==="bid"){if(i.validationHook!==H)throw new d("This auction has a validation hook. Its validation/signing contract is not configured; do not pass an off-chain signature manually.");if(i.blockNumber<i.startBlock||i.blockNumber>=i.endBlock)throw new d("Auction is not in its bidding window.");let r=c(e.amount,"amount",128),p=c(e.maxPrice,"maxPrice"),P=c(e.prevTickPrice,"prevTickPrice",256,!0);if(p<=i.clearingPrice)throw new d("Bid maxPrice must be above the checkpoint clearing price.");i.currency===H?N=r:w.push(s.approval(i.currency,i.auction,r.toString(),h)),f=y({abi:n,functionName:"submitBid",args:[p,r,a,P,"0x"]})}else if(t==="exit"){if(!u||!g(u.owner,a))throw new d("Only exit a bid owned by the signing wallet.");let r=c(e.bidId,"bidId",256,!0);if(e.mode==="full"){if(e.lastFullyFilledCheckpointBlock!==void 0||e.outbidBlock!==void 0)throw new d("Full exit takes no checkpoint hints.");f=y({abi:n,functionName:"exitBid",args:[r]})}else if(e.mode==="partial")f=y({abi:n,functionName:"exitPartiallyFilledBid",args:[r,c(e.lastFullyFilledCheckpointBlock,"lastFullyFilledCheckpointBlock",64,!0),c(e.outbidBlock,"outbidBlock",64,!0)]});else throw new d("Choose full or partial exit explicitly; partial exits require checkpoint hints.")}else if(t==="claim"){if(e.bidId===void 0==(e.bidIds===void 0))throw new d("Provide bidId or bidIds, not both.");let r=e.bidIds===void 0?[c(e.bidId,"bidId",256,!0)]:Array.isArray(e.bidIds)?e.bidIds.map(p=>c(p,"bidIds",256,!0)):[];if(r.length<1||r.length>50||new Set(r.map(String)).size!==r.length)throw new d("Provide 1 to 50 unique bid IDs.");for(let p of r){let P=await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[p],blockNumber:i.blockNumber});if(!g(P.owner,a))throw new d("Claimed tokens must belong to the signing wallet.")}f=y({abi:n,functionName:"claimTokensBatch",args:[a,r]})}else f=y({abi:n,functionName:t==="checkpoint"?"checkpoint":t==="sweep_currency"?"sweepCurrency":"sweepUnsoldTokens"});return w.push(s.unsignedTx({to:i.auction,data:f,value:N.toString(),chainId:h,description:`CCA ${t} on factory-verified auction ${i.auction}. Bid owner ${a}.`})),F(s,w,a,`CCA ${t}; checkpoint/exit/claim eligibility and creator-only sweeps are checked by the contract in preview. Sweeps pay the auction's immutable funds/tokens recipient, not an arbitrary recipient.`)}}));return o.push({name:"uniswap_auctions",inputSchema:{type:"object",additionalProperties:!1,properties:{fromBlock:l(),toBlock:l()}},async execute(t){I(t,["fromBlock","toBlock"]);let e=s.clientFor(h),a=await e.getBlockNumber(),k=t.fromBlock===void 0?a>9999n?a-9999n:0n:c(t.fromBlock,"fromBlock",64,!0),i=t.toBlock===void 0?a:c(t.toBlock,"toBlock",64,!0);if(k>i||i>a||i-k>=10000n)throw new d("Scan an ordered range of at most 10000 blocks, ending at or before the head.");let b=await e.getLogs({address:x,event:_,fromBlock:k,toBlock:i,strict:!0});return{factory:x,fromBlock:k.toString(),toBlock:i.toString(),auctions:b.map(m=>({auction:m.args.auction,token:m.args.token,amount:m.args.amount.toString(),creationBlock:m.blockNumber.toString()})),summary:"Factory-verified auctions in this block window only. An empty result does not establish that no auctions exist outside it. Scan earlier windows for older launches."}}}),{tools:o}}export{x as a,_ as b,n as c,$ as d,Q as e,R as f};
1
+ import{a as c,b as T,e as v,f as F,g as I}from"./3NDVXEBR.js";import{a as l}from"./UWOFA6GV.js";import{c as A,g,h as S}from"./73N3TOJL.js";import{a as h}from"./G6HCV67X.js";import{a as d}from"./5YS5V2LK.js";import{encodeFunctionData as y,getAddress as M,parseAbi as j,parseAbiItem as D,zeroAddress as H}from"viem";var x=M("0x000000001f26a0044baa66024e7b6599c61963f8"),_=D("event AuctionCreated(address indexed auction,address indexed token,uint256 amount,bytes configData)"),n=j(["function currency() view returns (address)","function token() view returns (address)","function startBlock() view returns (uint64)","function endBlock() view returns (uint64)","function claimBlock() view returns (uint64)","function validationHook() view returns (address)","function clearingPrice() view returns (uint256)","function isGraduated() view returns (bool)","function bids(uint256) view returns ((uint64 startBlock,uint24 startCumulativeMps,uint64 exitedBlock,uint256 maxPrice,address owner,uint256 amountQ96,uint256 tokensFilled))","function submitBid(uint256 maxPrice,uint128 amount,address owner,uint256 prevTickPrice,bytes hookData) payable returns (uint256)","function exitBid(uint256)","function exitPartiallyFilledBid(uint256,uint64,uint64)","function claimTokens(uint256)","function claimTokensBatch(address,uint256[])","function checkpoint()","function sweepCurrency()","function sweepUnsoldTokens()"]);async function $(s,B){let o=T(B.auction),t=c(B.creationBlock,"creationBlock",64,!0),e=await s.getLogs({address:x,event:_,args:{auction:o},fromBlock:t,toBlock:t,strict:!0});if(e.length!==1||!g(e[0].address,x)||!S(e[0].args.auction,o))throw new d("Auction has no matching AuctionCreated event at the pinned CCA factory and creationBlock.");return o}async function Q(s,B){let o=s.clientFor(h),t=await $(o,B),e=await o.getBlockNumber(),[a,k,i,b,m,C,u,w]=await Promise.all([o.readContract({address:t,abi:n,functionName:"currency",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"token",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"startBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"endBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"claimBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"validationHook",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"clearingPrice",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"isGraduated",blockNumber:e})]);return{auction:t,currency:a,saleToken:k,startBlock:i,endBlock:b,claimBlock:m,validationHook:C,clearingPrice:u,graduated:w,blockNumber:e}}var U={auction:A,creationBlock:l(),bidId:l(),amount:l(),maxPrice:l(),prevTickPrice:l(),lastFullyFilledCheckpointBlock:l(),outbidBlock:l(),mode:{type:"string",enum:["full","partial"]},bidIds:{type:"array",minItems:1,maxItems:50,items:l()}};function R(s){let o=["status","bid","exit","claim","checkpoint","sweep_currency","sweep_tokens"].map(t=>({name:`uniswap_auction_${t}`,inputSchema:{type:"object",additionalProperties:!1,required:["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode"]:[]],properties:U},async execute(e,a){I(e,["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode","lastFullyFilledCheckpointBlock","outbidBlock"]:t==="claim"?["bidId","bidIds"]:t==="status"?["bidId"]:[]]);let i=await Q(s,e),b=s.clientFor(h),[m,C]=await Promise.all([v(s,i.currency,i.blockNumber),v(s,i.saleToken,i.blockNumber)]),u=e.bidId===void 0?void 0:await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[c(e.bidId,"bidId",256,!0)],blockNumber:i.blockNumber});if(t==="status")return{auction:i.auction,paymentToken:m,saleToken:C,startBlock:i.startBlock.toString(),endBlock:i.endBlock.toString(),claimBlock:i.claimBlock.toString(),validationHook:i.validationHook,clearingPrice:i.clearingPrice.toString(),graduated:i.graduated,...u?{bid:{...u,startBlock:u.startBlock.toString(),exitedBlock:u.exitedBlock.toString(),maxPrice:u.maxPrice.toString(),amountQ96:u.amountQ96.toString(),tokensFilled:u.tokensFilled.toString()}}:{},summary:"CCA prices use currency-base-units per sale-token-base-unit in Q96. Clearing price/graduation reflect the latest checkpoint and may lag the head."};let w=[],f,N=0n;if(t==="bid"){if(i.validationHook!==H)throw new d("This auction has a validation hook. Its validation/signing contract is not configured; do not pass an off-chain signature manually.");if(i.blockNumber<i.startBlock||i.blockNumber>=i.endBlock)throw new d("Auction is not in its bidding window.");let r=c(e.amount,"amount",128),p=c(e.maxPrice,"maxPrice"),P=c(e.prevTickPrice,"prevTickPrice",256,!0);if(p<=i.clearingPrice)throw new d("Bid maxPrice must be above the checkpoint clearing price.");i.currency===H?N=r:w.push(s.approval(i.currency,i.auction,r.toString(),h)),f=y({abi:n,functionName:"submitBid",args:[p,r,a,P,"0x"]})}else if(t==="exit"){if(!u||!g(u.owner,a))throw new d("Only exit a bid owned by the signing wallet.");let r=c(e.bidId,"bidId",256,!0);if(e.mode==="full"){if(e.lastFullyFilledCheckpointBlock!==void 0||e.outbidBlock!==void 0)throw new d("Full exit takes no checkpoint hints.");f=y({abi:n,functionName:"exitBid",args:[r]})}else if(e.mode==="partial")f=y({abi:n,functionName:"exitPartiallyFilledBid",args:[r,c(e.lastFullyFilledCheckpointBlock,"lastFullyFilledCheckpointBlock",64,!0),c(e.outbidBlock,"outbidBlock",64,!0)]});else throw new d("Choose full or partial exit explicitly; partial exits require checkpoint hints.")}else if(t==="claim"){if(e.bidId===void 0==(e.bidIds===void 0))throw new d("Provide bidId or bidIds, not both.");let r=e.bidIds===void 0?[c(e.bidId,"bidId",256,!0)]:Array.isArray(e.bidIds)?e.bidIds.map(p=>c(p,"bidIds",256,!0)):[];if(r.length<1||r.length>50||new Set(r.map(String)).size!==r.length)throw new d("Provide 1 to 50 unique bid IDs.");for(let p of r){let P=await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[p],blockNumber:i.blockNumber});if(!g(P.owner,a))throw new d("Claimed tokens must belong to the signing wallet.")}f=y({abi:n,functionName:"claimTokensBatch",args:[a,r]})}else f=y({abi:n,functionName:t==="checkpoint"?"checkpoint":t==="sweep_currency"?"sweepCurrency":"sweepUnsoldTokens"});return w.push(s.unsignedTx({to:i.auction,data:f,value:N.toString(),chainId:h,description:`CCA ${t} on factory-verified auction ${i.auction}. Bid owner ${a}.`})),F(s,w,a,`CCA ${t}; checkpoint/exit/claim eligibility and creator-only sweeps are checked by the contract in preview. Sweeps pay the auction's immutable funds/tokens recipient, not an arbitrary recipient.`)}}));return o.push({name:"uniswap_auctions",inputSchema:{type:"object",additionalProperties:!1,properties:{fromBlock:l(),toBlock:l()}},async execute(t){I(t,["fromBlock","toBlock"]);let e=s.clientFor(h),a=await e.getBlockNumber(),k=t.fromBlock===void 0?a>9999n?a-9999n:0n:c(t.fromBlock,"fromBlock",64,!0),i=t.toBlock===void 0?a:c(t.toBlock,"toBlock",64,!0);if(k>i||i>a||i-k>=10000n)throw new d("Scan an ordered range of at most 10000 blocks, ending at or before the head.");let b=await e.getLogs({address:x,event:_,fromBlock:k,toBlock:i,strict:!0});return{factory:x,fromBlock:k.toString(),toBlock:i.toString(),auctions:b.map(m=>({auction:m.args.auction,token:m.args.token,amount:m.args.amount.toString(),creationBlock:m.blockNumber.toString()})),summary:"Factory-verified auctions in this block window only. An empty result does not establish that no auctions exist outside it. Scan earlier windows for older launches."}}}),{tools:o}}export{x as a,_ as b,n as c,$ as d,Q as e,R as f};
@@ -1 +1 @@
1
- import{a as B}from"./XGUKLFBU.js";import{c as _}from"./5RKWSFD2.js";import{c as V}from"./7B5UH2VS.js";import{c as P}from"./T6MTTMLQ.js";import{b as M}from"./YMB553OJ.js";import{k as R}from"./O47JXRXN.js";import{b as H,o as F}from"./CAU44UWP.js";import{b as W}from"./AXYOJBX6.js";import{a as k}from"./6IM6A5VA.js";import{a as G}from"./UWOFA6GV.js";import{g as A,m as I,n as O}from"./73N3TOJL.js";import{a as m,i as U}from"./XPFVT2EA.js";import{a as u}from"./5YS5V2LK.js";import{encodeFunctionData as C,getAddress as b,parseAbi as q}from"viem";var c=q(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)","function balanceOf(address) view returns (uint256)","function previewDeposit(uint256 assets) view returns (uint256)","function previewRedeem(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),J=q(["function deposit() payable"]),f=U[m],T=[{key:"core",name:"Longbow Core USDG",vault:f.vaults.longbowCore.address,asset:f.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"frontier",name:"Longbow Frontier USDG",vault:f.vaults.longbowFrontier.address,asset:f.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"eth",name:"Longbow ETH",vault:f.vaults.longbowEth.address,asset:f.tokens.WETH.address,symbol:"WETH",decimals:18}],D=[{key:"v1-usdg",name:"Longbow USDG Core V1 (legacy)",vault:b("0x8cb8AA35228c96C1C4E956E69AbAEBCc2aA7Dcfe"),asset:f.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"v1-weth",name:"Longbow WETH Core V1 (legacy)",vault:b("0x93777a9b917be3c8259c84456222f43a01dd6492"),asset:f.tokens.WETH.address,symbol:"WETH",decimals:18}];function x(a,i){return O(a,`${i} must be positive and within the uint256 range.`,{notString:`${i} must be a positive integer string in base units.`,positive:!0})}function h(a){return I(a,"Longbow returned an invalid integer response.")}function j(a,i=!1){if(typeof a!="string")throw new u("Provide the address of a current Longbow vault.");let p=D.find(y=>A(y.vault,a));if(p&&!i)throw new u("Longbow V1 vaults are withdraw-only; deposit into a current V2 vault from longbow_list instead.");let g=p??T.find(y=>A(y.vault,a));if(!g)throw new u("Provide the address of a current Longbow vault, or a Longbow V1 vault to withdraw from. Other vaults are not supported.");return g}function L(a,i){if(Object.keys(a).some(p=>!i.includes(p)))throw new u("Unsupported Longbow input. Use the fields in the tool schema.")}var Q=a=>{async function i(t){try{return await t()}catch(e){throw new u(a.plainError(e))}}async function p(){let t=a.clientFor(m);if(await t.getChainId()!==m)throw new u("Longbow requires a client on chain 4663.");return t}async function g(t,e){let[o,r,s]=await Promise.all([t.readContract({address:e.vault,abi:c,functionName:"asset"}),t.readContract({address:e.vault,abi:c,functionName:"decimals"}),t.readContract({address:e.asset,abi:c,functionName:"decimals"})]);if(typeof o!="string"||!A(o,e.asset))throw new u("Longbow vault asset does not match the recorded deployment.");if(r!==18||s!==e.decimals)throw new u("Longbow token decimals do not match the recorded deployment.");return{vault:e.vault,key:e.key,name:e.name,asset:{address:b(e.asset),symbol:e.symbol,decimals:s,chainId:m},share:{address:e.vault,symbol:`${e.key} shares`,decimals:r,chainId:m}}}async function y(t,e,o,r){let s=F(o.amount,H);if(BigInt(s)===0n)throw new u("The expected output is too small for a nonzero simulation minimum.");let n=await a.preview(t,e);if(n.changes.filter(l=>l.token.chainId===o.token.chainId&&A(l.token.address,o.token.address)&&l.token.decimals===o.token.decimals).reduce((l,v)=>l+BigInt(v.amount),0n)<BigInt(s))throw new u("Longbow simulated output is below the expected minimum.");let d=n.changes.map(({token:l,amount:v})=>{let N=v.startsWith("-");return`${N?"-":"+"}${a.formatAmount(N?v.slice(1):v,l.decimals)} ${l.symbol} (${l.address}, chain ${l.chainId})`}).join("; ");return{txs:t,preview:n,expectedOutput:o,minimumOutput:{token:o.token,amount:s},minimumEnforcedOnchain:!1,summary:`${r} ${d}. Simulation only; no on-chain minimum is enforced by these ERC-4626 calls. ${n.summary}`}}async function z(t){L(t,[]);let e=await p();return Promise.all(T.map(async o=>{let[r,s,n,w]=await Promise.all([g(e,o),e.readContract({address:o.vault,abi:c,functionName:"totalAssets"}),e.readContract({address:o.vault,abi:c,functionName:"performanceFee"}),e.readContract({address:o.vault,abi:c,functionName:"managementFee"})]);return{...r,totalAssets:{token:r.asset,amount:h(s).toString()},fees:{performanceFeeE18:h(n).toString(),managementFeeE18:h(w).toString()},caveat:"Morpho V2 max views can be zero even when writes succeed. Simulate the requested action; listing does not prove availability."}}))}async function Y(t,e){L(t,["vault","amount","wrapEth"]),k(e);let o=j(t.vault),r=x(t.amount,"Deposit amount");if(t.wrapEth!==void 0&&typeof t.wrapEth!="boolean")throw new u("wrapEth must be a boolean.");if(t.wrapEth&&!A(o.asset,f.tokens.WETH.address))throw new u("Only a WETH vault accepts explicit ETH wrapping.");let s=await p(),n=await g(s,o),w=h(await s.readContract({address:n.vault,abi:c,functionName:"previewDeposit",args:[r]})),d=[];return t.wrapEth&&d.push(a.unsignedTx({to:n.asset.address,data:C({abi:J,functionName:"deposit"}),value:r.toString(),chainId:m,description:`Wrap ${a.formatAmount(r.toString(),18)} ETH into WETH for ${n.name}.`})),d.push(a.approval(n.asset.address,n.vault,r.toString(),m)),d.push(a.unsignedTx({to:n.vault,data:C({abi:c,functionName:"deposit",args:[r,b(e)]}),value:"0",chainId:m,description:`Deposit ${a.formatAmount(r.toString(),n.asset.decimals)} ${n.asset.symbol} into ${n.name}.`})),y(d,e,{token:n.share,amount:w.toString()},`Deposit into ${n.name}.`)}async function K(t,e){L(t,["vault","shares"]),k(e);let o=j(t.vault,!0),r=t.shares==="all"?void 0:x(t.shares,"Redeem shares"),s=await p(),n=await g(s,o),w=h(await s.readContract({address:n.vault,abi:c,functionName:"balanceOf",args:[e]})),d=r??w;if(d===0n||d>w)throw new u("The wallet has insufficient Longbow shares for this redemption.");let l=h(await s.readContract({address:n.vault,abi:c,functionName:"previewRedeem",args:[d]})),v=[a.unsignedTx({to:n.vault,data:C({abi:c,functionName:"redeem",args:[d,b(e),b(e)]}),value:"0",chainId:m,description:`Redeem ${a.formatAmount(d.toString(),n.share.decimals)} shares from ${n.name} into ${n.asset.symbol}.`})];return y(v,e,{token:n.asset,amount:l.toString()},`Redeem from ${n.name}.`)}let E={type:"string",enum:T.map(t=>t.vault),description:"Current vault address on chain 4663."},$=G("Positive integer base units, never a human-unit decimal."),S=(t,e,o,r)=>({name:t,inputSchema:{type:"object",properties:e,required:o,additionalProperties:!1},execute:(s,n)=>i(()=>r(s,n))});return{tools:[S("longbow_list",{},[],z),S("longbow_deposit",{vault:E,amount:$,wrapEth:{type:"boolean",default:!1,description:"Explicitly wrap this amount of native ETH before depositing into the WETH vault."}},["vault","amount"],Y),S("longbow_withdraw",{vault:{...E,enum:[...E.enum,...D.map(t=>t.vault)],description:"Current vault address, or a Longbow V1 vault (withdraw-only) on chain 4663."},shares:{anyOf:[$,{const:"all"}],description:"Share base units (18 decimals), or all for the fresh wallet share balance. Returns the underlying asset, including WETH."}},["vault","shares"],K)],positions:t=>i(async()=>{k(t);let e=await p();return(await Promise.all([...T,...D].map(async r=>{let s=await g(e,r),n=h(await e.readContract({address:s.vault,abi:c,functionName:"balanceOf",args:[t]}));if(n===0n)return[];let w=h(await e.readContract({address:s.vault,abi:c,functionName:"previewRedeem",args:[n]}));return[{module:"longbow",id:`${m}:${s.vault.toLowerCase()}`,chainId:m,assets:[{token:s.asset,amount:w.toString()}],description:`${s.name}: ${a.formatAmount(n.toString(),s.share.decimals)} shares (${s.share.address}, ${s.share.decimals} decimals). Underlying is a preview, not a guaranteed redemption.`}]}))).flat()})}};function we(a){return W("longbow",[Q(a),P(a),R(a),V(a),M(a),_(a),{tools:B(a,"longbow",T.map(i=>({vault:i.vault,asset:{address:b(i.asset),symbol:i.symbol,decimals:i.decimals,chainId:m}})))}])}export{D as a,Q as b,we as c};
1
+ import{a as B}from"./UFS2RVEZ.js";import{b as M}from"./ZT47KN7A.js";import{c as _}from"./R7FXNZRM.js";import{c as V}from"./DZGEQBO7.js";import{k as R}from"./NAYRD43N.js";import{c as P}from"./2UU5TBBB.js";import{b as H,o as F}from"./5O5ZE3ZV.js";import{b as W}from"./AXYOJBX6.js";import{a as k}from"./6IM6A5VA.js";import{a as G}from"./UWOFA6GV.js";import{g as A,m as I,n as O}from"./73N3TOJL.js";import{a as m,i as U}from"./G6HCV67X.js";import{a as u}from"./5YS5V2LK.js";import{encodeFunctionData as C,getAddress as b,parseAbi as q}from"viem";var c=q(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)","function balanceOf(address) view returns (uint256)","function previewDeposit(uint256 assets) view returns (uint256)","function previewRedeem(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),J=q(["function deposit() payable"]),f=U[m],T=[{key:"core",name:"Longbow Core USDG",vault:f.vaults.longbowCore.address,asset:f.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"frontier",name:"Longbow Frontier USDG",vault:f.vaults.longbowFrontier.address,asset:f.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"eth",name:"Longbow ETH",vault:f.vaults.longbowEth.address,asset:f.tokens.WETH.address,symbol:"WETH",decimals:18}],D=[{key:"v1-usdg",name:"Longbow USDG Core V1 (legacy)",vault:b("0x8cb8AA35228c96C1C4E956E69AbAEBCc2aA7Dcfe"),asset:f.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"v1-weth",name:"Longbow WETH Core V1 (legacy)",vault:b("0x93777a9b917be3c8259c84456222f43a01dd6492"),asset:f.tokens.WETH.address,symbol:"WETH",decimals:18}];function x(a,i){return O(a,`${i} must be positive and within the uint256 range.`,{notString:`${i} must be a positive integer string in base units.`,positive:!0})}function h(a){return I(a,"Longbow returned an invalid integer response.")}function j(a,i=!1){if(typeof a!="string")throw new u("Provide the address of a current Longbow vault.");let p=D.find(y=>A(y.vault,a));if(p&&!i)throw new u("Longbow V1 vaults are withdraw-only; deposit into a current V2 vault from longbow_list instead.");let g=p??T.find(y=>A(y.vault,a));if(!g)throw new u("Provide the address of a current Longbow vault, or a Longbow V1 vault to withdraw from. Other vaults are not supported.");return g}function L(a,i){if(Object.keys(a).some(p=>!i.includes(p)))throw new u("Unsupported Longbow input. Use the fields in the tool schema.")}var Q=a=>{async function i(t){try{return await t()}catch(e){throw new u(a.plainError(e))}}async function p(){let t=a.clientFor(m);if(await t.getChainId()!==m)throw new u("Longbow requires a client on chain 4663.");return t}async function g(t,e){let[o,r,s]=await Promise.all([t.readContract({address:e.vault,abi:c,functionName:"asset"}),t.readContract({address:e.vault,abi:c,functionName:"decimals"}),t.readContract({address:e.asset,abi:c,functionName:"decimals"})]);if(typeof o!="string"||!A(o,e.asset))throw new u("Longbow vault asset does not match the recorded deployment.");if(r!==18||s!==e.decimals)throw new u("Longbow token decimals do not match the recorded deployment.");return{vault:e.vault,key:e.key,name:e.name,asset:{address:b(e.asset),symbol:e.symbol,decimals:s,chainId:m},share:{address:e.vault,symbol:`${e.key} shares`,decimals:r,chainId:m}}}async function y(t,e,o,r){let s=F(o.amount,H);if(BigInt(s)===0n)throw new u("The expected output is too small for a nonzero simulation minimum.");let n=await a.preview(t,e);if(n.changes.filter(l=>l.token.chainId===o.token.chainId&&A(l.token.address,o.token.address)&&l.token.decimals===o.token.decimals).reduce((l,v)=>l+BigInt(v.amount),0n)<BigInt(s))throw new u("Longbow simulated output is below the expected minimum.");let d=n.changes.map(({token:l,amount:v})=>{let N=v.startsWith("-");return`${N?"-":"+"}${a.formatAmount(N?v.slice(1):v,l.decimals)} ${l.symbol} (${l.address}, chain ${l.chainId})`}).join("; ");return{txs:t,preview:n,expectedOutput:o,minimumOutput:{token:o.token,amount:s},minimumEnforcedOnchain:!1,summary:`${r} ${d}. Simulation only; no on-chain minimum is enforced by these ERC-4626 calls. ${n.summary}`}}async function z(t){L(t,[]);let e=await p();return Promise.all(T.map(async o=>{let[r,s,n,w]=await Promise.all([g(e,o),e.readContract({address:o.vault,abi:c,functionName:"totalAssets"}),e.readContract({address:o.vault,abi:c,functionName:"performanceFee"}),e.readContract({address:o.vault,abi:c,functionName:"managementFee"})]);return{...r,totalAssets:{token:r.asset,amount:h(s).toString()},fees:{performanceFeeE18:h(n).toString(),managementFeeE18:h(w).toString()},caveat:"Morpho V2 max views can be zero even when writes succeed. Simulate the requested action; listing does not prove availability."}}))}async function Y(t,e){L(t,["vault","amount","wrapEth"]),k(e);let o=j(t.vault),r=x(t.amount,"Deposit amount");if(t.wrapEth!==void 0&&typeof t.wrapEth!="boolean")throw new u("wrapEth must be a boolean.");if(t.wrapEth&&!A(o.asset,f.tokens.WETH.address))throw new u("Only a WETH vault accepts explicit ETH wrapping.");let s=await p(),n=await g(s,o),w=h(await s.readContract({address:n.vault,abi:c,functionName:"previewDeposit",args:[r]})),d=[];return t.wrapEth&&d.push(a.unsignedTx({to:n.asset.address,data:C({abi:J,functionName:"deposit"}),value:r.toString(),chainId:m,description:`Wrap ${a.formatAmount(r.toString(),18)} ETH into WETH for ${n.name}.`})),d.push(a.approval(n.asset.address,n.vault,r.toString(),m)),d.push(a.unsignedTx({to:n.vault,data:C({abi:c,functionName:"deposit",args:[r,b(e)]}),value:"0",chainId:m,description:`Deposit ${a.formatAmount(r.toString(),n.asset.decimals)} ${n.asset.symbol} into ${n.name}.`})),y(d,e,{token:n.share,amount:w.toString()},`Deposit into ${n.name}.`)}async function K(t,e){L(t,["vault","shares"]),k(e);let o=j(t.vault,!0),r=t.shares==="all"?void 0:x(t.shares,"Redeem shares"),s=await p(),n=await g(s,o),w=h(await s.readContract({address:n.vault,abi:c,functionName:"balanceOf",args:[e]})),d=r??w;if(d===0n||d>w)throw new u("The wallet has insufficient Longbow shares for this redemption.");let l=h(await s.readContract({address:n.vault,abi:c,functionName:"previewRedeem",args:[d]})),v=[a.unsignedTx({to:n.vault,data:C({abi:c,functionName:"redeem",args:[d,b(e),b(e)]}),value:"0",chainId:m,description:`Redeem ${a.formatAmount(d.toString(),n.share.decimals)} shares from ${n.name} into ${n.asset.symbol}.`})];return y(v,e,{token:n.asset,amount:l.toString()},`Redeem from ${n.name}.`)}let E={type:"string",enum:T.map(t=>t.vault),description:"Current vault address on chain 4663."},$=G("Positive integer base units, never a human-unit decimal."),S=(t,e,o,r)=>({name:t,inputSchema:{type:"object",properties:e,required:o,additionalProperties:!1},execute:(s,n)=>i(()=>r(s,n))});return{tools:[S("longbow_list",{},[],z),S("longbow_deposit",{vault:E,amount:$,wrapEth:{type:"boolean",default:!1,description:"Explicitly wrap this amount of native ETH before depositing into the WETH vault."}},["vault","amount"],Y),S("longbow_withdraw",{vault:{...E,enum:[...E.enum,...D.map(t=>t.vault)],description:"Current vault address, or a Longbow V1 vault (withdraw-only) on chain 4663."},shares:{anyOf:[$,{const:"all"}],description:"Share base units (18 decimals), or all for the fresh wallet share balance. Returns the underlying asset, including WETH."}},["vault","shares"],K)],positions:t=>i(async()=>{k(t);let e=await p();return(await Promise.all([...T,...D].map(async r=>{let s=await g(e,r),n=h(await e.readContract({address:s.vault,abi:c,functionName:"balanceOf",args:[t]}));if(n===0n)return[];let w=h(await e.readContract({address:s.vault,abi:c,functionName:"previewRedeem",args:[n]}));return[{module:"longbow",id:`${m}:${s.vault.toLowerCase()}`,chainId:m,assets:[{token:s.asset,amount:w.toString()}],description:`${s.name}: ${a.formatAmount(n.toString(),s.share.decimals)} shares (${s.share.address}, ${s.share.decimals} decimals). Underlying is a preview, not a guaranteed redemption.`}]}))).flat()})}};function we(a){return W("longbow",[Q(a),P(a),R(a),V(a),M(a),_(a),{tools:B(a,"longbow",T.map(i=>({vault:i.vault,asset:{address:b(i.asset),symbol:i.symbol,decimals:i.decimals,chainId:m}})))}])}export{D as a,Q as b,we as c};
@@ -1 +1 @@
1
- import{c as pt}from"./OW7GOYKA.js";import{b as gt}from"./H6ED3RHF.js";import{b as ft}from"./FBQWTWPT.js";import{b as ut}from"./QXFJZGVB.js";import{c as ct}from"./6L6DSMCU.js";import{b as mt}from"./NHCRJC5X.js";import{h as lt}from"./HNMOB76J.js";import{a as C,b as x,c as Ie,d as me,e as Ge,g as it,h as Ve,j as U,l as E,o as Fe,p as rt,q as st,r as Me,s as at,t as qe,u as dt}from"./TCS3ICNE.js";import{b as nt,o as ot}from"./CAU44UWP.js";import{b as Qe}from"./AXYOJBX6.js";import{a as z}from"./6IM6A5VA.js";import{a as et,c as tt}from"./MYBDO5SA.js";import{a as Pe}from"./UWOFA6GV.js";import{a as ee}from"./RETS2ZEK.js";import{a as $,d as N,i as le}from"./XPFVT2EA.js";import{a}from"./5YS5V2LK.js";import{a as Ee}from"./JXOEJPJ4.js";import{BaseError as Ht,ContractFunctionRevertedError as ht,decodeEventLog as Wt,decodeFunctionResult as jt,encodeFunctionData as X,erc20Abi as zt,getAddress as B,parseAbi as ke,parseAbiItem as Jt,recoverAddress as Xt,recoverMessageAddress as Yt,recoverTypedDataAddress as Zt}from"viem";var Kt="https://priors.trade/api/check",He=604800n,bt=50n,wt=10000n,We=5000000n,yt=500000000n,je=86400n,$t=2592000n,Ye=`Register one with oak_setup {"mode":"register"}, then open Priors' 5 USDG starter line with priors_starter_line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent; each transaction and signature is confirmed).`,Qt="0x6982e39521a070a3c40782548bfbed6dc8f566ef",en=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],c={pool:B(le[4663].priors.pool.address),lens:B(le[4663].priors.lens.address),usdg:B(le[4663].priors.usdg.address),registry:B(le[4663].priors.registry.address),stockVault:B(le[4663].priors.stockVault.address)},ce={address:c.usdg,symbol:"USDG",decimals:N,chainId:$},S=ke(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool importedFromV1, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid)","function nonces(uint256 id) view returns (uint256)","function consentDigest((uint256 agentId, uint256 sponsorId, address owner, uint256 maxPremiumBps, uint256 nonce, uint256 deadline) c) view returns (bytes32)","function leave(uint256 agentId)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),St=ke(["function available(uint256 agentId) view returns (uint256)","function score(uint256 id) view returns (uint256)"]),Ct=ke(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),At=ke(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function Y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tn(e){return e.chainId===$&&e.address.toLowerCase()===c.usdg.toLowerCase()}function nn(e,i){let g=i.amount.trim(),u=g.startsWith("-"),f=u||g.startsWith("+")?g.slice(1):g,R=e.formatAmount(f,i.token.decimals),A=tn(i.token)?"USDG":i.token.address;return`${u?"-":"+"}${R} ${A}`}function te(e,i,g){if(!g.length)return i;let u=g.map(f=>nn(e,f)).join(", ");return`${i} Preview changes: ${u}.`}function vt(e,i,g,u){let f=e[i]===void 0?void 0:ee(e[i]),R=e[g]===void 0?void 0:ee(e[g]);if(f!==void 0)return f;if(R!==void 0)return R;throw new a(`Provide ${u} as an integer string in base units ("${i}" or "${g}").`)}async function De(e,i,g){try{return B(await e.clientFor($).readContract({address:c.registry,abi:Ct,functionName:"ownerOf",args:[i],blockNumber:g}))}catch{throw new a(`Could not read the owner of ERC-8004 agent ${i} from registry ${c.registry}. Check the agent ID and retry when the registry is available.`)}}function pe(e,i){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let g=BigInt(e.trim());if(g>0n)return g}throw new a(`Provide a positive integer ${i}.`)}function on(e,i){let g=i!==void 0?pe(i,"agentId"):void 0,u=[];for(let f of e)if(!(!f||typeof f.address!="string")&&f.address.toLowerCase()===c.pool.toLowerCase()&&!(!Array.isArray(f.topics)||f.topics.length===0))try{let R=Wt({abi:S,eventName:"Borrowed",data:f.data,topics:f.topics});if(g!==void 0&&R.args.agentId!==g)continue;u.push(R.args.loanId)}catch{continue}return u.length===0?null:u[u.length-1].toString()}function we(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],importedFromV1:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),recourseHonored:BigInt(e[18]),childrenDefaulted:BigInt(e[19]),qualifiedRepaid:BigInt(e[20]),dollarSecondsRepaid:BigInt(e[21])}}function Ce(e,i){return{loanId:e,agentId:BigInt(i[0]),sponsorId:BigInt(i[1]),principal:BigInt(i[2]),fee:BigInt(i[3]),sponsorCut:BigInt(i[4]),reserveCut:BigInt(i[5]),premium:BigInt(i[6]),owner:B(String(i[7])),issuedAt:BigInt(i[8]),dueAt:BigInt(i[9]),defaultableAt:BigInt(i[10]),minScoreTerm:BigInt(i[11]),closedAt:BigInt(i[12]),status:Number(i[13])}}async function _e(e,i){let g=e.clientFor($),u=await g.getBlockNumber({cacheTime:0}),f=await g.readContract({address:c.registry,abi:Ct,functionName:"balanceOf",args:[i],blockNumber:u});if(f===0n)return[];if(typeof f!="bigint"||f<0n)throw new a("Registry balance is unavailable. Retry or provide an explicit agentId.");let R=[],A=new Set,L=u;for(;;){let H=L>9999999n?L-9999999n:0n,ne=await g.getLogs({address:c.registry,event:Jt("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:i},fromBlock:H,toBlock:L,strict:!0});for(let O of ne){let J=O.args.tokenId;if(O.removed||A.has(J))continue;if(A.add(J),(await De(e,J,u)).toLowerCase()===i.toLowerCase()&&R.push(J),BigInt(R.length)===f)return R.sort((Z,re)=>Z<re?-1:Z>re?1:0)}if(H===0n)throw new a("Owned identities could not all be located. Retry or provide an explicit agentId.");L=H-1n}}async function Re(e,i,g){if(i.agentId!==void 0&&i.agentId!==null&&String(i.agentId).trim()!=="")return pe(i.agentId,"agentId");let u=await _e(e,g);if(u.length===0)throw new a(`Priors borrowing needs an ERC-8004 agent identity with a Priors credit line, and this wallet owns no identity. ${Ye}`);return u[0]}async function ze(e,i,g){let u=e.clientFor($),f=await De(e,i),[R,A]=await Promise.all([u.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[i]}),u.readContract({address:c.pool,abi:S,functionName:"isController",args:[i,g]})]),L=B(R);if(!A)throw new a(`Wallet ${g} is not an on-chain controller for ERC-8004 agent ${i} (ownerOf=${f}, delegateOf=${L}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:f,delegate:L}}function rn(e,i){if(!i.enrolled||i.isRoot||i.sponsor===0n)throw new a(`ERC-8004 agent ${e} has no sponsor-backed Priors credit line on CreditPoolV2 yet (enrolled=${i.enrolled}, sponsor=${i.sponsor}, isRoot=${i.isRoot}). For an agent with no Priors record, priors_starter_line opens Priors' 5 USDG treasury line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent), then borrow.`);if(i.defaulted||i.frozen)throw new a(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${i.defaulted}, frozen=${i.frozen}).`);let g=i.delegatedIn>i.principalOut?i.delegatedIn-i.principalOut:0n;if(g<=0n)throw new a(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${i.delegatedIn}, principalOut=${i.principalOut}).`);return g}function sn(e){let i=e.borrowReceiptLogs??(Y(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(i))return[];let g=[];for(let u of i)Y(u)&&(typeof u.address!="string"||!Array.isArray(u.topics)||typeof u.data!="string"||g.push({address:u.address,topics:u.topics,data:u.data}));return g}var Je="0x0000000000000000000000000000000000000000",ue=()=>Math.floor(Date.now()/1e3),G=e=>new Date(Number(e)*1e3).toISOString(),V=(e,i)=>e.toLowerCase()===i.toLowerCase();function ye(e){let i=(g,u)=>Array.isArray(e)?e[u]:e[g];return{depositor:B(String(i("depositor",0))),at:BigInt(i("at",1)),amount:BigInt(i("amount",2))}}async function he(e,i,g){let u=e.clientFor($),f=await u.getBlockNumber({cacheTime:0}),[R,A,L,H,ne,O,J,ge,Z,re,Te]=await Promise.all([De(e,i,f),u.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"firstLined",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"agentId",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"rules",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"epochRoom",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"bonds",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"amount",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedAfter",blockNumber:f}),u.readContract({address:c.usdg,abi:zt,functionName:"balanceOf",args:[g],blockNumber:f})]);return{owner:R,agent:we(A),firstLined:L===!0,root:BigInt(H),firstLineAmount:BigInt(ne[1]),epochRoom:BigInt(O),bond:ye(J),bondAmount:BigInt(ge),releaseAt:BigInt(Z),unusedAfter:BigInt(re),usdg:BigInt(Te)}}function Pt(e,i){return e.enrolled||e.enrolledAt>0n||e.isRoot||e.defaulted||e.importedFromV1||e.loansRepaid>0n||e.sponsor!==0n||i}function It(e,i,g,u){let f=R=>`${e.formatAmount(R.toString(),N)} USDG`;if(i.defaulted)return"it defaulted: the pool marks it, and Priors never lends to it again";if(i.isRoot)return"it is a root: it backs other agents' lines";if(i.delegatedIn>0n){let R=i.sponsor===g?`Priors' treasury (root #${g})`:`root #${i.sponsor}`;return`it has a ${f(i.delegatedIn)} line from ${R}${i.activeLoans>0n?` with ${i.activeLoans} loan(s) open`:""}`}return`it has no line now${i.enrolledAt>0n?` (it enrolled at ${G(i.enrolledAt)})`:""}${u?`; Priors' treasury opened a line for it once, and another needs a person at ${Ge}`:""}`}async function Xe(e,i){let g;try{g=await e.http(me,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(i)})}catch(f){if(!(f instanceof et))throw new a(`Priors' invite bot (${me}) could not be reached: ${e.plainError(f)}`);g=f.response}let u;try{u=JSON.parse(await g.text())}catch{u=void 0}if(!Y(u))throw new a(`Priors' invite bot (${me}) answered HTTP ${g.status} without a readable JSON object.`);return u}var be=e=>Ee(typeof e=="string"&&e?e:"no reason given");function an(e,i){let g=i instanceof Ht?i.walk(L=>L instanceof ht):void 0,u=g instanceof ht?g.data:void 0,f=u?.args??[],R=L=>`${e.formatAmount(String(L),N)} USDG`,A=u?.errorName;switch(A){case"EpochCapReached":return`Priors' treasury has no room for a new line this week (wanted ${R(f[0])}, ${R(f[1])} left); the treasury caps new lines each week, so ask again next week.`;case"InsufficientBacking":return`Priors' treasury root lacks free backing for the line now (requested ${R(f[1])}, free ${R(f[2])}); try again later.`;case"InviteExpired":return"the invite expired; call priors_starter_line again for a new one.";case"InviteUsed":return"the invite was already used.";case"NotInvited":return`the invite's signer ${String(f[1])} is not an inviter TreasurySponsorV4 names.`;case"AlreadyLined":return"the agent is already on a treasury line.";case"OwnerDefaulted":return"a default on this wallet's Priors record stops new treasury lines.";case"BadConsent":return"the pool refused the consent (its owner, nonce or signature no longer matches); call priors_starter_line again.";case"ConsentExpired":return"the consent expired; call priors_starter_line again.";case"Paused":return"the Priors pool is paused for new risk; try again later.";case void 0:return e.plainError(i);default:return`${A}(${f.map(String).join(", ")}).`}}var dn=e=>{let i={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",pattern:"^[0-9]+$",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",pattern:"^[0-9]+$",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=vt(n,"assets","amount","USDG deposit amount");if(r<=0n)throw new a("Deposit amount must be greater than zero.");let p=n.minShares===void 0?void 0:ee(n.minShares),d=e.approval(c.usdg,c.pool,r.toString(),$);if(p===void 0){let l;try{let v=await e.clientFor($).simulateCalls({account:o,calls:[{to:d.to,data:d.data},{to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,0n]})}]}),[P,_]=v.results;if(P?.status!=="success"||_?.status!=="success")throw new a("Approval or deposit simulation failed.");l=jt({abi:S,functionName:"deposit",data:_.data})}catch(v){throw new a(`Could not simulate Priors deposit shares: ${e.plainError(v)}`)}if(p=ee(ot(l.toString(),n.slippageBps??nt)),p===0n)throw new a("The simulated deposit cannot provide a positive minimum share amount.")}let w=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,p]}),value:"0",chainId:$,description:`Deposit ${r} USDG base units into Priors CreditPoolV2 (${c.pool}) for ${t}.`}),b=[d,w],m=await e.preview(b,o),I=`Approve ${e.formatAmount(r.toString(),N)} USDG and deposit into Priors CreditPoolV2 (${c.pool}) for ${t} (minShares=${p}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:b,summary:te(e,I,m.changes)}}},g={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",pattern:"^[0-9]+$",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=e.clientFor($),p=n.shares!==void 0?ee(n.shares):await r.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]});if(p<=0n)throw new a(`Wallet ${o} has no Priors CreditPoolV2 shares to withdraw.`);let[d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[p]}),r.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),r.getBlock()]),m=w>0n&&b.timestamp<w+He,h=m?d*bt/wt:0n,I=d-h,v=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"withdraw",args:[p,t]}),value:"0",chainId:$,description:`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t}.`})],P=await e.preview(v,o),_=e.formatAmount(I.toString(),N),F=e.formatAmount(d.toString(),N),k=e.formatAmount(h.toString(),N),D=m?`inside 7-day MIN_HOLD: ${k} USDG (0.5%) early-exit fee stays in pool, net payout ${_} USDG from ${F} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${_} USDG`,M=`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t} (${D}).`;return{txs:v,summary:te(e,M,P.changes)}}},u={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",pattern:"^[0-9]+$",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400"). The origination fee is pro-rated by term, so a longer term costs more.'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional ceiling on the origination fee, USDG base units; must equal the pool's current quote for this principal and term. Omit to use that quote. The fee is pro-rated by term, not flat: 1666 for 5 USDG over 1 day on the first live run (2026-10-31)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.recipient!==void 0&&(typeof n.recipient!="string"||n.recipient.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors recipient must be the signing wallet.");let r=await Re(e,n,o);await ze(e,r,o);let p=e.clientFor($),d=await p.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[r]}),w=we(d),b=rn(r,w),m=vt(n,"principal","amount","USDG borrow principal");if(m<We||m>yt)throw new a(`Borrow principal must be between ${We} (5 USDG) and ${yt} (500 USDG) base units.`);if(m>b)throw new a(`Borrow principal ${m} exceeds available credit line capacity ${b} USDG base units for agent ${r}.`);let h=n.term!==void 0&&String(n.term).trim()!==""?pe(n.term,"term"):je;if(h<je||h>$t)throw new a(`Loan term must be between ${je} (1 day) and ${$t} (30 days) seconds.`);let I=await p.readContract({address:c.pool,abi:S,functionName:"quoteFee",args:[r,m,h]}),l=I[0],v=n.maxFee!==void 0?ee(n.maxFee):l;if(v<l)throw new a(`Provided maxFee ${v} is below the origination fee the pool quotes for this term, ${l} USDG base units.`);if(v>l)throw new a(`Provided maxFee ${v} is above the quoted origination fee ${l} USDG base units. Use the quoted fee or omit maxFee.`);let P=m+l,_=m+v,k=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"borrow",args:[r,m,h,t,v]}),value:"0",chainId:$,description:`Borrow ${m} USDG base units on Priors CreditPoolV2 for agent ${r} to ${t} (quoted fee ${l}, expected debt ${P}, maxFee ${v}, debt ceiling ${_}).`})],D=await e.preview(k,o),M=e.formatAmount(m.toString(),N),W=e.formatAmount(l.toString(),N),se=e.formatAmount(P.toString(),N),j=e.formatAmount(v.toString(),N),$e=e.formatAmount(_.toString(),N),q=I[1]+I[3],K=I[2],ae=l-q-K,oe=`Borrow ${M} USDG for ERC-8004 agent ${r} to recipient ${t} on Priors CreditPoolV2 (${c.pool}) for ${h}s: expected origination fee ${W} USDG (${l} base units; pro-rated by term, set when the loan opens, none refunded on early repayment), expected total repayment due ${se} USDG (${P} base units); fee ceiling ${j} USDG (${v} base units), debt ceiling ${$e} USDG (${_} base units). Fee recipient on repayment: CreditPoolV2 (${c.pool}), allocating the quoted fee to sponsor ${w.sponsor} (${q} base units including premium), reserve (${K} base units), and lenders (${ae} base units).`;return{txs:k,summary:te(e,oe,D.changes)}}},f={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay; must equal the exact fixed principal + fee. Omit to use that debt."}}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),p;if(n.loanId!==void 0&&n.loanId!==null&&String(n.loanId).trim()!=="")p=pe(n.loanId,"loanId");else{let k=sn(n);if(k.length>0){let D=on(k,t);D!==null&&(p=BigInt(D))}}let d;if(p!==void 0){let k=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[p]}),D=Ce(p,k);if(D.agentId!==t)throw new a(`Loan ${p} belongs to agent ${D.agentId}, not agent ${t}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(D.status!==1)throw new a(`Loan ${p} for agent ${t} is not active (status=${D.status}).`);d=D}else{let k=await r.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[t]});if(k.length===0)throw new a(`ERC-8004 agent ${t} has no recorded loans on Priors CreditPoolV2.`);let M=(await Promise.all(k.map(async W=>{let se=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[W]});return Ce(W,se)}))).filter(W=>W.agentId===t&&W.status===1);if(M.length===0)throw new a(`ERC-8004 agent ${t} has no active loans to repay.`);d=M[M.length-1]}let w=d.principal+d.fee,b=n.maxDue!==void 0?ee(n.maxDue):w;if(b<w)throw new a(`Provided maxDue ${b} is below the exact fixed loan debt ${w} USDG base units (principal ${d.principal} + fixed fee ${d.fee}).`);if(b>w)throw new a(`Provided maxDue ${b} is above the exact fixed loan debt ${w} USDG base units. Use the fixed debt or omit maxDue.`);let m=e.approval(c.usdg,c.pool,w.toString(),$),h=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"repay",args:[d.loanId,t,b]}),value:"0",chainId:$,description:`Repay fixed debt ${w} USDG base units (principal ${d.principal} + fee ${d.fee}) for loan ${d.loanId} (agent ${t}).`}),I=[m,h],l=await e.preview(I,o),v=e.formatAmount(w.toString(),N),P=e.formatAmount(d.principal.toString(),N),_=e.formatAmount(d.fee.toString(),N),F=`Approve and repay ${v} USDG (${w} base units: ${P} USDG principal + ${_} USDG fixed fee) for Priors loan ${d.loanId} (agent ${t}).`;return{txs:I,summary:te(e,F,l.changes)}}},R={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(n,s){z(s);let o=B(s),t=e.clientFor($),[r,p,d,w]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]}),t.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),t.getBlock(),t.readContract({address:c.stockVault,abi:At,functionName:"assetList"})]),b=r>0n?await t.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[r]}):0n,m=r>0n&&p>0n&&d.timestamp<p+He,h=m?b*bt/wt:0n,I=b-h,l=null;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")l=pe(n.agentId,"agentId");else{let q=await _e(e,o);q.length>0&&(l=q[0])}let v=null,P=!1,_=[],F=null,k=null,D=null,M=null,W=null,se=null,j=`This wallet owns no ERC-8004 agent identity. ${Ye}`;if(l!==null){let[q,K,ae,oe,Lt,xt,Be,Ne,Le]=await Promise.all([t.readContract({address:c.lens,abi:St,functionName:"score",args:[l]}),t.readContract({address:x,abi:E,functionName:"firstLined",args:[l]}),t.readContract({address:x,abi:E,functionName:"agentId"}),t.readContract({address:x,abi:E,functionName:"rules"}),t.readContract({address:x,abi:E,functionName:"epochRoom"}),t.readContract({address:C,abi:U,functionName:"bonds",args:[l]}),t.readContract({address:C,abi:U,functionName:"amount"}),t.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[l]}),t.readContract({address:C,abi:U,functionName:"releasable",args:[l]})]),[Ot,Ut,Et,Gt,Vt,Ft]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[l]}),t.readContract({address:c.lens,abi:St,functionName:"available",args:[l]}),t.readContract({address:c.stockVault,abi:At,functionName:"borrowRoom",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"isController",args:[l,o]})]),xe=await De(e,l),Mt=B(Vt),Ze=Ft,y=we(Ot),Se=y.delegatedIn>y.principalOut?y.delegatedIn-y.principalOut:0n;P=y.enrolled&&!y.isRoot&&!y.defaulted&&!y.frozen&&y.sponsor>0n&&y.delegatedIn>0n,F=Et.toString(),k=Gt.toString();let qt=await Promise.all(Ut.map(async T=>{let de=await t.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[T]});return Ce(T,de)}));for(let T of qt)if(T.agentId===l&&T.status===1){let de=T.principal+T.fee;_.push({loanId:T.loanId.toString(),agentId:T.agentId.toString(),sponsorId:T.sponsorId.toString(),principal:T.principal.toString(),fee:T.fee.toString(),due:de.toString(),dueAt:T.dueAt.toString(),issuedAt:T.issuedAt.toString(),owner:T.owner,token:ce})}v={agentId:l.toString(),owner:xe,delegate:Mt,isAuthorizedController:Ze,enrolled:y.enrolled,isRoot:y.isRoot,defaulted:y.defaulted,frozen:y.frozen,sponsorId:y.sponsor.toString(),delegatedIn:y.delegatedIn.toString(),delegatedOut:y.delegatedOut.toString(),principalOut:y.principalOut.toString(),availableCapacity:Se.toString(),activeLoansCount:y.activeLoans.toString(),loansRepaid:y.loansRepaid.toString(),volumeRepaid:y.volumeRepaid.toString(),feesPaid:y.feesPaid.toString(),importedFromV1:y.importedFromV1,qualifiedRepaid:y.qualifiedRepaid.toString(),dollarSecondsRepaid:y.dollarSecondsRepaid.toString()};let Ae=BigInt(ae),Oe=K===!0,Q=ye(xt),ie=Q.depositor!==Je,ve=ie&&V(Q.depositor,o),Ke=Pt(y,Oe),Ue=V(xe,o);D={onchain:BigInt(q).toString(),scale:"0-1000",source:`CreditLensV2.score(${l}) at ${c.lens}, the score the pool computes on chain`,scoreV2:null},M={open:y.sponsor!==0n&&y.delegatedIn>0n,amount:y.delegatedIn.toString(),drawn:y.principalOut.toString(),available:Se.toString(),sponsorId:y.sponsor.toString(),backer:y.sponsor===0n?null:y.sponsor===Ae?`Priors' treasury v4 (root #${Ae})`:`root #${y.sponsor}`,token:ce},W={contract:C,posted:ie,depositor:ie?Q.depositor:null,postedByWallet:ve,postedAt:ie?Q.at.toString():null,amount:(ie?Q.amount:BigInt(Be)).toString(),releasable:ie&&Le===!0,releaseAt:ie?BigInt(Ne).toString():null,rule:"Back to its depositor once the agent holds no line and has no loan open, from 4 days after it was posted (close a line first with priors_close_line); a default forfeits it to Priors' Safe."},se={eligible:Ue&&!Ke,firstLined:Oe,lineAmount:BigInt(oe[1]).toString(),bondAmount:BigInt(Be).toString(),treasuryRoot:Ae.toString(),treasuryRoomThisWeek:BigInt(Lt).toString(),note:"Not instant: Priors' invite bot decides each invite, and the treasury caps new lines each week."};let fe=_.map(T=>({id:String(T.loanId),dueAt:BigInt(String(T.dueAt))})).sort((T,de)=>T.dueAt<de.dueAt?-1:T.dueAt>de.dueAt?1:0);y.defaulted?j=`Agent #${l} defaulted; Priors never lends to it again${ve?" and its bond is forfeited":""}.`:!Ze&&!Ue?j=`This wallet does not control agent #${l} on CreditPoolV2 (owner ${xe}); act from its owner or delegate.`:fe.length?j=`Repay loan ${fe[0].id} with priors_repay before it is due at ${G(fe[0].dueAt)}${fe.length>1?` (${fe.length} loans open)`:""}.`:P&&Se>=We?j=`Borrow with priors_borrow (5 USDG minimum, up to ${A(Se)}; the fee is pro-rated by term); Priors counts loans held 7 days or more toward the score.`:!Ke&&Ue?j=ve?`Call priors_starter_line again: the ${A(Q.amount)} bond is posted, and it goes on with the invite bot's ownership proof and the invite's redemption${Le===!0?", or priors_release_bond returns the bond":""}.`:`Call priors_starter_line: a refundable ${A(BigInt(Be))} bond, an invite from Priors' invite bot and your pool consent open a ${A(BigInt(oe[1]))} line from Priors' treasury (each transaction and signature is confirmed).`:ve?j=Le===!0?`Release the ${A(Q.amount)} invite bond with priors_release_bond.`:y.delegatedIn>0n?`The line is open with nothing to draw; to take the bond back, close it with priors_close_line, then priors_release_bond from ${G(BigInt(Ne))}.`:`The ${A(Q.amount)} invite bond comes back with priors_release_bond from ${G(BigInt(Ne))}.`:j=`Agent #${l} has a Priors record but no line to draw now; ${It(e,y,Ae,Oe)}.`}let $e=null;if(n.includeApiCheck){let q=l!==null?`agent=${l.toString()}`:`address=${o}`,K=await tt(e.http,`${Kt}?${q}`,{method:"GET"},Y),ae=Array.isArray(K.agents)?K.agents.find(oe=>Y(oe)&&String(oe.agentId)===String(l)):void 0;D&&Y(ae)&&(D.scoreV2=ae.scoreV2??null),$e={...K,grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:$,blockNumber:d.number?.toString()??null,blockTimestamp:d.timestamp.toString(),wallet:o,token:ce,contracts:c,lender:{shares:r.toString(),grossAssets:b.toString(),earlyExitFeeAssets:h.toString(),netWithdrawAssets:I.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:m,minHoldSeconds:He.toString()},hasFundedLine:P,agentId:l!==null?l.toString():null,nextStep:j,score:D,line:M,bond:W,starterLine:se,agent:v,activeLoans:_,lens:{address:c.lens,available:F,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:c.stockVault,borrowRoom:k,onchainAssetCount:w.length,hostedMcpStockCount:35,extraNonStockAsset:B(Qt),zeroCapAssets:en.map(q=>B(q)),caveat:"Use priors_stock_assets and priors_stock_asset_state for current collateral rules, then priors_stock_open. This summary is an observed asset-count snapshot, not a fixed allowlist; live caps, lending holds and prices control admission."},apiCheck:$e,limitations:["Borrowing and repayment require a sponsor-backed ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet).","Priors line routes are exposed by priors_line_options and priors_capabilities: treasury starter, V5 move/raise, direct sponsor, stock and owner PRIORS backing. Ethos execution uses Priors own owner workflow because its worker supplies no unsigned final transaction.","score.onchain is the pool's on-chain score (CreditLensV2); score.scoreV2 is Priors Score v2 from /api/check, present only with includeApiCheck.","Loan debt is the principal plus the origination fee the pool quotes for the term. The fee is pro-rated by term, not flat (1666 base units for 5 USDG over 1 day, observed live 2026-10-31; priors_borrow shows the exact quote), and is fixed once the loan opens: variable interest is never invented, and early repayment refunds none of it.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}},A=n=>`${e.formatAmount(n.toString(),N)} USDG`;function L(n){let s=V(n.bond.depositor,n.owner)&&n.bond.amount>0n?n.bond.amount:n.bondAmount;return`Bond first: ${A(s)} is locked in Priors' InviteBond for at least ${n.unusedAfter} seconds (${Number(n.unusedAfter)/86400} days) after posting${n.releaseAt>0n?`; unusedReleaseAt is ${G(n.releaseAt)}`:"; the exact release time is read after posting"}. Release requires no line and no open loan; default can forfeit the bond. Invites are not guaranteed. The credit score can lag qualifying repayments. `}function H(n,s,o){if(!V(o.owner,s))throw new a(`This wallet (${s}) does not own ERC-8004 agent ${n} (its owner is ${o.owner}). The bond, the ownership proof and the pool consent are the owner's. Nothing was signed.`);if(o.root!==Ie)throw new a(`TreasurySponsorV4 (${x}) answers root #${o.root}, not the pinned #${Ie}. Nothing was signed; update Oak.`);if(Pt(o.agent,o.firstLined))throw new a(`Agent #${n} already has a Priors record, so priors_starter_line posts no bond and signs nothing: ${It(e,o.agent,o.root,o.firstLined)}; ${o.agent.loansRepaid} loan(s) repaid. The starter line is only for an identity with no record; priors_status shows this one.`)}let ne="stays posted in InviteBond";function O(n){let s=n.agent.delegatedIn>0n?`with a line open it comes back only after priors_close_line (no loan open), then priors_release_bond from ${G(n.releaseAt)} at the earliest`:`while the agent holds no line it comes back with priors_release_bond from ${G(n.releaseAt)} (${Number(n.unusedAfter)/86400} days after it was posted)`;return`The ${A(n.bond.amount>0n?n.bond.amount:n.bondAmount)} bond ${ne} (${C}), posted from this wallet; ${s}, and priors_starter_line never posts a second bond.`}async function J(n,s,o){try{return await o()}catch(t){let r=t instanceof a?t.message:e.plainError(t);if(r.includes(ne)||n===void 0||!/^[0-9]{1,78}$/.test(n))throw t;let p;try{let d=await he(e,BigInt(n),s);p=V(d.bond.depositor,s)?O(d):""}catch{p=`If the bond transactions mined, the invite bond ${ne} (${C}) remains locked until its on-chain release conditions are met; priors_status shows the exact amount and time (its state could not be read just now).`}throw p?new a(`${r} ${p}`):t}}async function ge(n,s,o){let t=at(await Xe(e,{agentId:n}),{agentId:n,owner:s,now:ue()});if(!t.ok&&t.refused)throw new a(`Priors' invite bot gave no ownership proof to sign for agent #${n}: ${be(t.why)}. Nothing was signed. ${o}`.trim());if(!t.ok)throw new a(`Not signed: the invite bot's answer for agent #${n} is not one Oak signs: ${t.why}. Oak signs only the bot's own start-page text, rebuilt locally for this agent and this wallet. ${o}`.trim());if(t.exp-ue()<120)throw new a(`Not signed: the invite bot's proof for agent #${n} expires in under 2 minutes; call priors_starter_line again for a new one. ${o}`.trim());return t}function Z(n,s,o,t){return{steps:[{kind:"message",message:o.message}],continuation:{stage:"proof",wallet:s,chainId:$,agentId:n,n:o.n,exp:o.exp},summary:`${L(t)}Priors starter line for ERC-8004 agent ${n}, step 2 of 3: sign Priors' invite-bot ownership proof. It is a message signature (EIP-191) only: it sends no transaction and moves no funds. The text is the bot's own form, rebuilt locally for agent #${n} and this wallet, request ${o.n}, expiring ${G(o.exp)}. Oak then sends the signature to ${me}, and the bot decides the invite. ${O(t)}`}}function re(n,s,o){if(n.chainId!==$||typeof n.wallet!="string"||!V(n.wallet,s)||typeof n.agentId!="string"||!/^[1-9][0-9]{0,29}$/.test(n.agentId))throw new a("Priors starter-line continuation does not match this wallet or chain 4663; start priors_starter_line again.");if(o.agentId!==void 0&&String(o.agentId)!==n.agentId)throw new a("Priors starter-line continuation is for another agent; start priors_starter_line again.");return BigInt(n.agentId)}async function Te(n,s){let o;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")o=pe(n.agentId,"agentId");else{let l=await _e(e,s);if(!l.length)throw new a(`Priors' starter line needs an ERC-8004 agent identity, and this wallet owns none. ${Ye}`);o=l[0]}let t=await he(e,o,s);H(o,s,t);let r=o.toString(),p=V(t.bond.depositor,s);if(!p){if(t.usdg<t.bondAmount)throw new a(`This wallet holds ${A(t.usdg)} on Robinhood Chain, and Priors' treasury invite asks a ${A(t.bondAmount)} bond first (InviteBond ${C}), posted from this wallet. Nothing was signed: add USDG, then call priors_starter_line again.`);if(t.epochRoom<t.firstLineAmount)return{summary:`${L(t)}Not submitted. Priors' treasury has ${A(t.epochRoom)} of room left this week and a first line is ${A(t.firstLineAmount)}, so priors_starter_line posted no bond and signed nothing. The treasury caps new lines each week: ask again next week.`,starterLine:{agentId:r,open:!1,reason:"room",epochRoom:t.epochRoom.toString()}};let l=await Xe(e,{check:!0,owner:s.toLowerCase()});if(l.check!==!0)throw new a("Priors' invite bot did not answer its check, so whether an invite is open cannot be told. Nothing was signed.");if(l.ok!==!0)throw new a(`Whether an automatic invite is open could not be told: Priors' invite bot says ${be(l.error)}. Nothing was signed; try again later.`);if(l.open!==!0){let v=typeof l.reason=="string"?l.reason.replace(/[^a-z-]/g,"").slice(0,24):"",P=typeof l.reopensAt=="number"&&Number.isSafeInteger(l.reopensAt)&&l.reopensAt>0?l.reopensAt:null;return{summary:`${L(t)}Not submitted. No automatic invite is open to this wallet right now, so priors_starter_line posted no bond and signed nothing. Priors' invite bot answers: closed, reason ${Ee(v||"none given")}${P?`, reopens ${G(P)}`:""}. ${dt({...l,reason:v})} Priors lists its other ways to a first line (the Ethos lane, a stock line, the owner's $PRIORS stake) at https://priors.trade/skill.md.`,starterLine:{agentId:r,open:!1,reason:v||null,reopensAt:P}}}}let d=await ge(r,s,p?O(t):"");if(p)return Z(r,s,d,t);let w=[e.approval(c.usdg,C,t.bondAmount.toString(),$),e.unsignedTx({to:C,data:X({abi:U,functionName:"deposit",args:[o]}),value:"0",chainId:$,description:`Post the ${t.bondAmount} USDG base-unit Priors invite bond for agent ${r} in InviteBond (${C}).`})],b=await e.preview(w,s),m=t.bond.depositor!==Je?` This deposit replaces the bond ${t.bond.depositor} posted for this agent; InviteBond returns that bond to it in the same transaction.`:"",h=`${L(t)}Priors starter line for ERC-8004 agent ${r}, step 1 of 3: approve exactly ${A(t.bondAmount)} to Priors' InviteBond (${C}) and post it as the agent's refundable invite bond (InviteBond.deposit).${m} Priors' invite bot says an automatic invite is open now and gave the ownership proof to sign next. Step 2 signs that proof (a message, no transaction); step 3 signs your pool consent and redeems the invite (TreasurySponsorV4.firstLine, ${x}) for a ${A(t.firstLineAmount)} line from Priors' treasury (root #${t.root}). The invite is the bot's decision, not a promise: if it refuses, or any later step fails, the bond stays posted and comes back with priors_release_bond after the on-chain lock and release conditions are met. With a line, the bond comes back only once the line is closed with no loan open (priors_close_line, then priors_release_bond); a default forfeits it to Priors' Safe.`;return{steps:w.map(l=>({kind:"tx",tx:l})),continuation:{stage:"bond",wallet:s,chainId:$,agentId:r,n:d.n,exp:d.exp},summary:te(e,h,b.changes)}}async function Rt(n,s,o){let t=await he(e,n,s);H(n,s,t);let r=n.toString();if(!V(t.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet, so nothing more was signed. Check the deposit transaction, then call priors_starter_line again.`);return typeof o.n=="string"&&Ve.test(o.n)&&typeof o.exp=="number"&&Number.isSafeInteger(o.exp)&&o.exp-ue()>=300?Z(r,s,{n:o.n,exp:o.exp,message:Me(r,o.n,o.exp)},t):Z(r,s,await ge(r,s,O(t)),t)}async function _t(n,s,o,t){let r=n.toString();if(typeof o.n!="string"||!Ve.test(o.n)||typeof o.exp!="number"||!Number.isSafeInteger(o.exp))throw new a("Invalid Priors starter-line proof continuation; start priors_starter_line again.");if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the invite bot's ownership proof.");if(o.exp<=ue())throw new a(`The invite bot's proof for agent #${r} expired before it reached the bot; nothing was sent to it. Call priors_starter_line again for a fresh proof (the bond is not posted again).`);let p=Me(r,o.n,o.exp);if(!V(await Yt({message:p,signature:t}),s))throw new a("The ownership-proof signature is not this wallet's; nothing was sent to the invite bot.");let d=await he(e,n,s);if(H(n,s,d),!V(d.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet; nothing was sent to the invite bot. Call priors_starter_line again.`);let w=await Xe(e,{n:o.n,signature:t});if(w.ok!==!0)throw new a(`Priors' invite bot gave no invite for agent #${r}: ${be(w.error)}. ${O(d)}`);if(typeof w.code!="string")throw new a(`Priors' invite bot gave no invite for agent #${r}${w.reason?`: ${be(w.reason)}`:""}${typeof w.decided=="string"?` (its decision: ${be(w.decided)})`:""}. ${O(d)}`);let b=qe(w.code,r,ue()+60);if(!b.ok)throw new a(`Priors' invite bot's code for agent #${r} is not one Oak redeems: ${b.why}. Nothing more was signed. ${O(d)}`);let m=e.clientFor($),h=await m.readContract({address:x,abi:E,functionName:"inviteDigest",args:[n,b.expiry]});if(h.toLowerCase()!==st(n,b.expiry).toLowerCase())throw new a("TreasurySponsorV4's invite digest differs from its pinned EIP-712 domain; nothing more was signed. Update Oak.");let I=await Xt({hash:h,signature:b.signature}),[l,v]=await Promise.all([m.readContract({address:x,abi:E,functionName:"inviters",args:[I]}),m.readContract({address:x,abi:E,functionName:"inviteUsed",args:[h]})]);if(l!==!0)throw new a(`Priors' invite for agent #${r} was signed by ${I}, which TreasurySponsorV4 does not name an inviter, so the treasury would refuse it. Nothing more was signed. ${O(d)}`);if(v===!0)throw new a(`Priors' invite for agent #${r} was already used. Nothing more was signed. ${O(d)}`);let[P,_]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]),F=_.timestamp+BigInt(it),k=Fe({agentId:r,owner:s,nonce:P.toString(),deadline:F.toString()}),D=await m.readContract({address:c.pool,abi:S,functionName:"consentDigest",args:[{agentId:n,sponsorId:d.root,owner:s,maxPremiumBps:0n,nonce:P,deadline:F}]});if(D.toLowerCase()!==rt(k).toLowerCase())throw new a(`The pool's consentDigest (${D}) differs from the consent Oak builds for CreditPoolV2 (${c.pool}), so the pool would refuse it. Nothing more was signed. ${O(d)}`);return{steps:[{kind:"typedData",request:k}],continuation:{stage:"consent",wallet:s,chainId:$,agentId:r,invite:w.code,request:k},summary:`Priors starter line for ERC-8004 agent ${r}, step 3 of 3: Priors' invite bot gave an invite (signed by ${I}, an inviter TreasurySponsorV4 names; it expires ${G(b.expiry)}). Sign your pool consent (EIP-712 "Priors Credit" version 2 on CreditPoolV2 ${c.pool}): it lets Priors' treasury (root #${d.root}) back a line for agent #${r} with premium 0, nonce ${P}, valid until ${G(F)}. A transaction redeeming the invite (TreasurySponsorV4.firstLine) follows for your confirmation. ${O(d)}`}}async function kt(n,s,o,t){let r=n.toString();if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the Priors pool consent.");let p=qe(o.invite,r,ue()+60);if(!p.ok)throw new a(`The invite for agent #${r} is not one Oak redeems now: ${p.why}. Call priors_starter_line again for a new one.`);let d=Y(o.request)&&Y(o.request.message)?o.request.message:void 0;if(!d||typeof d.nonce!="string"||!/^[0-9]{1,78}$/.test(d.nonce)||typeof d.deadline!="string"||!/^[0-9]{1,20}$/.test(d.deadline))throw new a("Invalid Priors starter-line consent continuation; start priors_starter_line again.");let w=Fe({agentId:r,owner:s,nonce:d.nonce,deadline:d.deadline});if(!V(await Zt({...w,signature:t}),s))throw new a("The pool-consent signature is not this wallet's for the consent Oak built; nothing was offered.");let b=await he(e,n,s);H(n,s,b);let m=e.clientFor($),[h,I]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]);if(h.toString()!==d.nonce)throw new a(`Agent #${r}'s consent nonce moved on chain since it was signed; nothing was offered. Call priors_starter_line again.`);if(I.timestamp>=BigInt(d.deadline))throw new a(`The pool consent for agent #${r} expired at ${G(BigInt(d.deadline))}; nothing was offered. Call priors_starter_line again.`);let l={agentId:n,sponsorId:Ie,owner:s,maxPremiumBps:0n,nonce:h,deadline:BigInt(d.deadline)},v=[n,p.expiry,p.signature,l,t];try{await m.simulateContract({address:x,abi:E,functionName:"firstLine",args:v,account:s})}catch(k){throw new a(`TreasurySponsorV4.firstLine for agent #${r} would be refused: ${an(e,k)} Nothing was offered. ${O(b)}`)}let P=e.unsignedTx({to:x,data:X({abi:E,functionName:"firstLine",args:v}),value:"0",chainId:$,description:`Redeem Priors' invite for agent ${r}: TreasurySponsorV4.firstLine opens a ${b.firstLineAmount} USDG base-unit line from root ${b.root} with the owner's consent.`}),_=await e.preview([P],s),F=`Redeem agent #${r}'s Priors invite: TreasurySponsorV4.firstLine (${x}) opens a ${A(b.firstLineAmount)} line from Priors' treasury (root #${b.root}) with your signed consent. No USDG moves in this transaction. Then priors_status shows the line and priors_borrow draws it (5 USDG minimum; the fee is pro-rated by term; Priors counts loans held 7 days or more toward the score). The ${A(b.bondAmount)} bond stays in InviteBond until the line is closed with no loan open (priors_close_line, then priors_release_bond, from ${G(b.releaseAt)} at the earliest); a default forfeits it.`;return{txs:[P],summary:te(e,F,_.changes)}}let Dt={name:"priors_starter_line",inputSchema:{description:"Bond first: the launch bond is 5 USDG, locked at least 4 days. The first result reads amount(), unusedAfter() and unusedReleaseAt(agentId) for current terms before any approval. Invites are not guaranteed; the credit score can lag. Release needs no line or open loan; default can forfeit the bond.",type:"object",additionalProperties:!1,properties:{agentId:Pe("ERC-8004 agent ID this wallet owns, with no Priors record yet (default: the first identity this wallet owns)."),continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}}},async execute(n,s){z(s);let o=B(s);if(n.continuation===void 0){if(n.signature!==void 0)throw new a("A signature needs its Priors starter-line continuation; start priors_starter_line again.");return J(typeof n.agentId=="string"?n.agentId:void 0,o,()=>Te(n,o))}if(!Y(n.continuation))throw new a("Invalid Priors starter-line continuation; start priors_starter_line again.");let t=n.continuation,r=re(t,o,n),p=d=>J(r.toString(),o,d);if(t.stage==="bond"){if(n.signature!==void 0)throw new a("The bond stage takes no signature; start priors_starter_line again.");return p(()=>Rt(r,o,t))}if(t.stage==="proof")return p(()=>_t(r,o,t,n.signature));if(t.stage==="consent")return p(()=>kt(r,o,t,n.signature));throw new a("Unknown Priors starter-line stage; start priors_starter_line again.")}},Tt={name:"priors_close_line",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose Priors line to close (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),[p,d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:x,abi:E,functionName:"agentId"})]),m=we(p);if(m.sponsor===0n)throw new a(`Agent #${t} has no Priors line to close (no sponsor on CreditPoolV2).`);if(m.activeLoans>0n)throw new a(`Agent #${t} has ${m.activeLoans} loan(s) open; repay them with priors_repay first. The pool's leave refuses while a loan is open.`);let h=ye(d),I=m.sponsor===BigInt(b),l=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"leave",args:[t]}),value:"0",chainId:$,description:`Close agent ${t}'s Priors line on CreditPoolV2 (leave): the ${m.delegatedIn} USDG base-unit line returns to root ${m.sponsor}.`}),v=await e.preview([l],o),P=V(h.depositor,o)?` Its ${A(h.amount)} invite bond can then come back with priors_release_bond from ${G(w)} (4 days after it was posted).`:"",_=`Close agent #${t}'s Priors line (CreditPoolV2.leave, ${c.pool}): the whole ${A(m.delegatedIn)} line goes back to its backer (${I?`Priors' treasury, root #${b}`:`root #${m.sponsor}`}) and the agent can no longer borrow on it. This does not reopen: ${I?`priors_starter_line opens no second treasury line for an agent with a Priors record; another needs a person at ${Ge}.`:"a new line needs a backer's new consent."}${P} No USDG moves in this transaction.`;return{txs:[l],summary:te(e,_,v.changes)}}},Bt={name:"priors_release_bond",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose InviteBond bond this wallet posted (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o),r=e.clientFor($),[p,d,w,b,m]=await Promise.all([r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"releasable",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.getBlock()]),h=ye(p);if(h.depositor===Je)throw new a(`Agent #${t} has no bond in Priors' InviteBond (${C}).`);if(!V(h.depositor,o))throw new a(`Agent #${t}'s InviteBond bond was posted by ${h.depositor}, not this wallet, and InviteBond.release pays the depositor. Oak releases only a bond this wallet posted.`);if(d!==!0){let P=we(b),_=P.defaulted?"the agent defaulted, so the bond is forfeited to Priors' Safe (InviteBond.slash)":P.activeLoans>0n?`the agent has ${P.activeLoans} loan(s) open: repay with priors_repay, close the line with priors_close_line, then release`:P.delegatedIn>0n?`the agent still holds a ${A(P.delegatedIn)} line: close it with priors_close_line (no loan may be open), then release`:m.timestamp<w?`it comes back 4 days after it was posted, from ${G(w)}`:"InviteBond does not release it yet";throw new a(`Agent #${t}'s ${A(h.amount)} invite bond cannot be released now: ${_}. Nothing was signed.`)}let I=e.unsignedTx({to:C,data:X({abi:U,functionName:"release",args:[t]}),value:"0",chainId:$,description:`Release agent ${t}'s ${h.amount} USDG base-unit Priors invite bond from InviteBond (${C}) to its depositor ${h.depositor}.`}),l=await e.preview([I],o),v=`Release agent #${t}'s ${A(h.amount)} invite bond from Priors' InviteBond (${C}): InviteBond.release returns it to its depositor, this wallet (${o}).`;return{txs:[I],summary:te(e,v,l.changes)}}};async function Nt(n){z(n);let s=B(n),o=e.clientFor($),[t,r]=await Promise.all([o.readContract({address:c.pool,abi:S,functionName:"shares",args:[s]}),_e(e,s)]),p=[];if(t>0n){let d=await o.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[t]});p.push({module:"priors",id:`priors:lender:${s.toLowerCase()}`,chainId:$,assets:[{token:ce,amount:d.toString()}],description:`Priors CreditPoolV2 lender position (${t} shares = ${e.formatAmount(d.toString(),N)} USDG gross).`})}for(let d of r){let w=await o.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[d]}),b=await Promise.all(w.map(async h=>{let I=await o.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[h]});return Ce(h,I)}));for(let h of b)if(h.agentId===d&&h.status===1){let I=h.principal+h.fee;p.push({module:"priors",id:`priors:loan:${h.loanId.toString()}`,chainId:$,assets:[{token:ce,amount:I.toString()}],description:`Priors CreditPoolV2 active loan ${h.loanId} for agent ${d} (fixed due ${e.formatAmount(I.toString(),N)} USDG = ${h.principal} principal + ${h.fee} fee).`})}let m=ye(await o.readContract({address:C,abi:U,functionName:"bonds",args:[d]}));m.amount>0n&&V(m.depositor,s)&&p.push({module:"priors",id:`priors:bond:${d.toString()}`,chainId:$,assets:[{token:ce,amount:m.amount.toString()}],description:`Priors invite bond for agent ${d} in InviteBond (${C}): ${A(m.amount)}, back with priors_release_bond once the agent holds no line and no loan, from 4 days after posting; a default forfeits it.`})}return p}return{tools:[i,g,u,f,R,Dt,Tt,Bt],positions:Nt}},ln=e=>{let i=dn(e),g=[i,lt(e),ct(e),pt(e),gt(e),ft(e),mt(e),ut()];return{...i,tools:g.flatMap(u=>u.tools)}},_n=e=>Qe("priors",[ln(e)]);export{Kt as a,He as b,bt as c,wt as d,We as e,yt as f,je as g,$t as h,c as i,ce as j,on as k,ln as l,_n as m};
1
+ import{b as mt}from"./4KQZTPMS.js";import{c as pt}from"./2W46IRX6.js";import{b as gt}from"./LMVB3B6T.js";import{b as ft}from"./JWCOXLYA.js";import{b as ut}from"./TWCSCRFS.js";import{c as ct}from"./NMYGNJIJ.js";import{h as lt}from"./GGUEKSR4.js";import{a as C,b as x,c as Ie,d as me,e as Ge,g as it,h as Ve,j as U,l as E,o as Fe,p as rt,q as st,r as Me,s as at,t as qe,u as dt}from"./3WBDHUV2.js";import{b as nt,o as ot}from"./5O5ZE3ZV.js";import{b as Qe}from"./AXYOJBX6.js";import{a as z}from"./6IM6A5VA.js";import{a as et,c as tt}from"./MYBDO5SA.js";import{a as Pe}from"./UWOFA6GV.js";import{a as ee}from"./RETS2ZEK.js";import{a as $,d as N,i as le}from"./G6HCV67X.js";import{a}from"./5YS5V2LK.js";import{a as Ee}from"./JXOEJPJ4.js";import{BaseError as Ht,ContractFunctionRevertedError as ht,decodeEventLog as Wt,decodeFunctionResult as jt,encodeFunctionData as X,erc20Abi as zt,getAddress as B,parseAbi as ke,parseAbiItem as Jt,recoverAddress as Xt,recoverMessageAddress as Yt,recoverTypedDataAddress as Zt}from"viem";var Kt="https://priors.trade/api/check",He=604800n,bt=50n,wt=10000n,We=5000000n,yt=500000000n,je=86400n,$t=2592000n,Ye=`Register one with oak_setup {"mode":"register"}, then open Priors' 5 USDG starter line with priors_starter_line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent; each transaction and signature is confirmed).`,Qt="0x6982e39521a070a3c40782548bfbed6dc8f566ef",en=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],c={pool:B(le[4663].priors.pool.address),lens:B(le[4663].priors.lens.address),usdg:B(le[4663].priors.usdg.address),registry:B(le[4663].priors.registry.address),stockVault:B(le[4663].priors.stockVault.address)},ce={address:c.usdg,symbol:"USDG",decimals:N,chainId:$},S=ke(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool importedFromV1, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid)","function nonces(uint256 id) view returns (uint256)","function consentDigest((uint256 agentId, uint256 sponsorId, address owner, uint256 maxPremiumBps, uint256 nonce, uint256 deadline) c) view returns (bytes32)","function leave(uint256 agentId)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),St=ke(["function available(uint256 agentId) view returns (uint256)","function score(uint256 id) view returns (uint256)"]),Ct=ke(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),At=ke(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function Y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tn(e){return e.chainId===$&&e.address.toLowerCase()===c.usdg.toLowerCase()}function nn(e,i){let g=i.amount.trim(),u=g.startsWith("-"),f=u||g.startsWith("+")?g.slice(1):g,R=e.formatAmount(f,i.token.decimals),A=tn(i.token)?"USDG":i.token.address;return`${u?"-":"+"}${R} ${A}`}function te(e,i,g){if(!g.length)return i;let u=g.map(f=>nn(e,f)).join(", ");return`${i} Preview changes: ${u}.`}function vt(e,i,g,u){let f=e[i]===void 0?void 0:ee(e[i]),R=e[g]===void 0?void 0:ee(e[g]);if(f!==void 0)return f;if(R!==void 0)return R;throw new a(`Provide ${u} as an integer string in base units ("${i}" or "${g}").`)}async function De(e,i,g){try{return B(await e.clientFor($).readContract({address:c.registry,abi:Ct,functionName:"ownerOf",args:[i],blockNumber:g}))}catch{throw new a(`Could not read the owner of ERC-8004 agent ${i} from registry ${c.registry}. Check the agent ID and retry when the registry is available.`)}}function pe(e,i){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let g=BigInt(e.trim());if(g>0n)return g}throw new a(`Provide a positive integer ${i}.`)}function on(e,i){let g=i!==void 0?pe(i,"agentId"):void 0,u=[];for(let f of e)if(!(!f||typeof f.address!="string")&&f.address.toLowerCase()===c.pool.toLowerCase()&&!(!Array.isArray(f.topics)||f.topics.length===0))try{let R=Wt({abi:S,eventName:"Borrowed",data:f.data,topics:f.topics});if(g!==void 0&&R.args.agentId!==g)continue;u.push(R.args.loanId)}catch{continue}return u.length===0?null:u[u.length-1].toString()}function we(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],importedFromV1:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),recourseHonored:BigInt(e[18]),childrenDefaulted:BigInt(e[19]),qualifiedRepaid:BigInt(e[20]),dollarSecondsRepaid:BigInt(e[21])}}function Ce(e,i){return{loanId:e,agentId:BigInt(i[0]),sponsorId:BigInt(i[1]),principal:BigInt(i[2]),fee:BigInt(i[3]),sponsorCut:BigInt(i[4]),reserveCut:BigInt(i[5]),premium:BigInt(i[6]),owner:B(String(i[7])),issuedAt:BigInt(i[8]),dueAt:BigInt(i[9]),defaultableAt:BigInt(i[10]),minScoreTerm:BigInt(i[11]),closedAt:BigInt(i[12]),status:Number(i[13])}}async function _e(e,i){let g=e.clientFor($),u=await g.getBlockNumber({cacheTime:0}),f=await g.readContract({address:c.registry,abi:Ct,functionName:"balanceOf",args:[i],blockNumber:u});if(f===0n)return[];if(typeof f!="bigint"||f<0n)throw new a("Registry balance is unavailable. Retry or provide an explicit agentId.");let R=[],A=new Set,L=u;for(;;){let H=L>9999999n?L-9999999n:0n,ne=await g.getLogs({address:c.registry,event:Jt("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:i},fromBlock:H,toBlock:L,strict:!0});for(let O of ne){let J=O.args.tokenId;if(O.removed||A.has(J))continue;if(A.add(J),(await De(e,J,u)).toLowerCase()===i.toLowerCase()&&R.push(J),BigInt(R.length)===f)return R.sort((Z,re)=>Z<re?-1:Z>re?1:0)}if(H===0n)throw new a("Owned identities could not all be located. Retry or provide an explicit agentId.");L=H-1n}}async function Re(e,i,g){if(i.agentId!==void 0&&i.agentId!==null&&String(i.agentId).trim()!=="")return pe(i.agentId,"agentId");let u=await _e(e,g);if(u.length===0)throw new a(`Priors borrowing needs an ERC-8004 agent identity with a Priors credit line, and this wallet owns no identity. ${Ye}`);return u[0]}async function ze(e,i,g){let u=e.clientFor($),f=await De(e,i),[R,A]=await Promise.all([u.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[i]}),u.readContract({address:c.pool,abi:S,functionName:"isController",args:[i,g]})]),L=B(R);if(!A)throw new a(`Wallet ${g} is not an on-chain controller for ERC-8004 agent ${i} (ownerOf=${f}, delegateOf=${L}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:f,delegate:L}}function rn(e,i){if(!i.enrolled||i.isRoot||i.sponsor===0n)throw new a(`ERC-8004 agent ${e} has no sponsor-backed Priors credit line on CreditPoolV2 yet (enrolled=${i.enrolled}, sponsor=${i.sponsor}, isRoot=${i.isRoot}). For an agent with no Priors record, priors_starter_line opens Priors' 5 USDG treasury line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent), then borrow.`);if(i.defaulted||i.frozen)throw new a(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${i.defaulted}, frozen=${i.frozen}).`);let g=i.delegatedIn>i.principalOut?i.delegatedIn-i.principalOut:0n;if(g<=0n)throw new a(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${i.delegatedIn}, principalOut=${i.principalOut}).`);return g}function sn(e){let i=e.borrowReceiptLogs??(Y(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(i))return[];let g=[];for(let u of i)Y(u)&&(typeof u.address!="string"||!Array.isArray(u.topics)||typeof u.data!="string"||g.push({address:u.address,topics:u.topics,data:u.data}));return g}var Je="0x0000000000000000000000000000000000000000",ue=()=>Math.floor(Date.now()/1e3),G=e=>new Date(Number(e)*1e3).toISOString(),V=(e,i)=>e.toLowerCase()===i.toLowerCase();function ye(e){let i=(g,u)=>Array.isArray(e)?e[u]:e[g];return{depositor:B(String(i("depositor",0))),at:BigInt(i("at",1)),amount:BigInt(i("amount",2))}}async function he(e,i,g){let u=e.clientFor($),f=await u.getBlockNumber({cacheTime:0}),[R,A,L,H,ne,O,J,ge,Z,re,Te]=await Promise.all([De(e,i,f),u.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"firstLined",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"agentId",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"rules",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"epochRoom",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"bonds",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"amount",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedAfter",blockNumber:f}),u.readContract({address:c.usdg,abi:zt,functionName:"balanceOf",args:[g],blockNumber:f})]);return{owner:R,agent:we(A),firstLined:L===!0,root:BigInt(H),firstLineAmount:BigInt(ne[1]),epochRoom:BigInt(O),bond:ye(J),bondAmount:BigInt(ge),releaseAt:BigInt(Z),unusedAfter:BigInt(re),usdg:BigInt(Te)}}function Pt(e,i){return e.enrolled||e.enrolledAt>0n||e.isRoot||e.defaulted||e.importedFromV1||e.loansRepaid>0n||e.sponsor!==0n||i}function It(e,i,g,u){let f=R=>`${e.formatAmount(R.toString(),N)} USDG`;if(i.defaulted)return"it defaulted: the pool marks it, and Priors never lends to it again";if(i.isRoot)return"it is a root: it backs other agents' lines";if(i.delegatedIn>0n){let R=i.sponsor===g?`Priors' treasury (root #${g})`:`root #${i.sponsor}`;return`it has a ${f(i.delegatedIn)} line from ${R}${i.activeLoans>0n?` with ${i.activeLoans} loan(s) open`:""}`}return`it has no line now${i.enrolledAt>0n?` (it enrolled at ${G(i.enrolledAt)})`:""}${u?`; Priors' treasury opened a line for it once, and another needs a person at ${Ge}`:""}`}async function Xe(e,i){let g;try{g=await e.http(me,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(i)})}catch(f){if(!(f instanceof et))throw new a(`Priors' invite bot (${me}) could not be reached: ${e.plainError(f)}`);g=f.response}let u;try{u=JSON.parse(await g.text())}catch{u=void 0}if(!Y(u))throw new a(`Priors' invite bot (${me}) answered HTTP ${g.status} without a readable JSON object.`);return u}var be=e=>Ee(typeof e=="string"&&e?e:"no reason given");function an(e,i){let g=i instanceof Ht?i.walk(L=>L instanceof ht):void 0,u=g instanceof ht?g.data:void 0,f=u?.args??[],R=L=>`${e.formatAmount(String(L),N)} USDG`,A=u?.errorName;switch(A){case"EpochCapReached":return`Priors' treasury has no room for a new line this week (wanted ${R(f[0])}, ${R(f[1])} left); the treasury caps new lines each week, so ask again next week.`;case"InsufficientBacking":return`Priors' treasury root lacks free backing for the line now (requested ${R(f[1])}, free ${R(f[2])}); try again later.`;case"InviteExpired":return"the invite expired; call priors_starter_line again for a new one.";case"InviteUsed":return"the invite was already used.";case"NotInvited":return`the invite's signer ${String(f[1])} is not an inviter TreasurySponsorV4 names.`;case"AlreadyLined":return"the agent is already on a treasury line.";case"OwnerDefaulted":return"a default on this wallet's Priors record stops new treasury lines.";case"BadConsent":return"the pool refused the consent (its owner, nonce or signature no longer matches); call priors_starter_line again.";case"ConsentExpired":return"the consent expired; call priors_starter_line again.";case"Paused":return"the Priors pool is paused for new risk; try again later.";case void 0:return e.plainError(i);default:return`${A}(${f.map(String).join(", ")}).`}}var dn=e=>{let i={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",pattern:"^[0-9]+$",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",pattern:"^[0-9]+$",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=vt(n,"assets","amount","USDG deposit amount");if(r<=0n)throw new a("Deposit amount must be greater than zero.");let p=n.minShares===void 0?void 0:ee(n.minShares),d=e.approval(c.usdg,c.pool,r.toString(),$);if(p===void 0){let l;try{let v=await e.clientFor($).simulateCalls({account:o,calls:[{to:d.to,data:d.data},{to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,0n]})}]}),[P,_]=v.results;if(P?.status!=="success"||_?.status!=="success")throw new a("Approval or deposit simulation failed.");l=jt({abi:S,functionName:"deposit",data:_.data})}catch(v){throw new a(`Could not simulate Priors deposit shares: ${e.plainError(v)}`)}if(p=ee(ot(l.toString(),n.slippageBps??nt)),p===0n)throw new a("The simulated deposit cannot provide a positive minimum share amount.")}let w=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,p]}),value:"0",chainId:$,description:`Deposit ${r} USDG base units into Priors CreditPoolV2 (${c.pool}) for ${t}.`}),b=[d,w],m=await e.preview(b,o),I=`Approve ${e.formatAmount(r.toString(),N)} USDG and deposit into Priors CreditPoolV2 (${c.pool}) for ${t} (minShares=${p}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:b,summary:te(e,I,m.changes)}}},g={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",pattern:"^[0-9]+$",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=e.clientFor($),p=n.shares!==void 0?ee(n.shares):await r.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]});if(p<=0n)throw new a(`Wallet ${o} has no Priors CreditPoolV2 shares to withdraw.`);let[d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[p]}),r.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),r.getBlock()]),m=w>0n&&b.timestamp<w+He,h=m?d*bt/wt:0n,I=d-h,v=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"withdraw",args:[p,t]}),value:"0",chainId:$,description:`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t}.`})],P=await e.preview(v,o),_=e.formatAmount(I.toString(),N),F=e.formatAmount(d.toString(),N),k=e.formatAmount(h.toString(),N),D=m?`inside 7-day MIN_HOLD: ${k} USDG (0.5%) early-exit fee stays in pool, net payout ${_} USDG from ${F} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${_} USDG`,M=`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t} (${D}).`;return{txs:v,summary:te(e,M,P.changes)}}},u={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",pattern:"^[0-9]+$",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400"). The origination fee is pro-rated by term, so a longer term costs more.'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional ceiling on the origination fee, USDG base units; must equal the pool's current quote for this principal and term. Omit to use that quote. The fee is pro-rated by term, not flat: 1666 for 5 USDG over 1 day on the first live run (2026-10-31)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.recipient!==void 0&&(typeof n.recipient!="string"||n.recipient.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors recipient must be the signing wallet.");let r=await Re(e,n,o);await ze(e,r,o);let p=e.clientFor($),d=await p.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[r]}),w=we(d),b=rn(r,w),m=vt(n,"principal","amount","USDG borrow principal");if(m<We||m>yt)throw new a(`Borrow principal must be between ${We} (5 USDG) and ${yt} (500 USDG) base units.`);if(m>b)throw new a(`Borrow principal ${m} exceeds available credit line capacity ${b} USDG base units for agent ${r}.`);let h=n.term!==void 0&&String(n.term).trim()!==""?pe(n.term,"term"):je;if(h<je||h>$t)throw new a(`Loan term must be between ${je} (1 day) and ${$t} (30 days) seconds.`);let I=await p.readContract({address:c.pool,abi:S,functionName:"quoteFee",args:[r,m,h]}),l=I[0],v=n.maxFee!==void 0?ee(n.maxFee):l;if(v<l)throw new a(`Provided maxFee ${v} is below the origination fee the pool quotes for this term, ${l} USDG base units.`);if(v>l)throw new a(`Provided maxFee ${v} is above the quoted origination fee ${l} USDG base units. Use the quoted fee or omit maxFee.`);let P=m+l,_=m+v,k=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"borrow",args:[r,m,h,t,v]}),value:"0",chainId:$,description:`Borrow ${m} USDG base units on Priors CreditPoolV2 for agent ${r} to ${t} (quoted fee ${l}, expected debt ${P}, maxFee ${v}, debt ceiling ${_}).`})],D=await e.preview(k,o),M=e.formatAmount(m.toString(),N),W=e.formatAmount(l.toString(),N),se=e.formatAmount(P.toString(),N),j=e.formatAmount(v.toString(),N),$e=e.formatAmount(_.toString(),N),q=I[1]+I[3],K=I[2],ae=l-q-K,oe=`Borrow ${M} USDG for ERC-8004 agent ${r} to recipient ${t} on Priors CreditPoolV2 (${c.pool}) for ${h}s: expected origination fee ${W} USDG (${l} base units; pro-rated by term, set when the loan opens, none refunded on early repayment), expected total repayment due ${se} USDG (${P} base units); fee ceiling ${j} USDG (${v} base units), debt ceiling ${$e} USDG (${_} base units). Fee recipient on repayment: CreditPoolV2 (${c.pool}), allocating the quoted fee to sponsor ${w.sponsor} (${q} base units including premium), reserve (${K} base units), and lenders (${ae} base units).`;return{txs:k,summary:te(e,oe,D.changes)}}},f={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay; must equal the exact fixed principal + fee. Omit to use that debt."}}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),p;if(n.loanId!==void 0&&n.loanId!==null&&String(n.loanId).trim()!=="")p=pe(n.loanId,"loanId");else{let k=sn(n);if(k.length>0){let D=on(k,t);D!==null&&(p=BigInt(D))}}let d;if(p!==void 0){let k=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[p]}),D=Ce(p,k);if(D.agentId!==t)throw new a(`Loan ${p} belongs to agent ${D.agentId}, not agent ${t}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(D.status!==1)throw new a(`Loan ${p} for agent ${t} is not active (status=${D.status}).`);d=D}else{let k=await r.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[t]});if(k.length===0)throw new a(`ERC-8004 agent ${t} has no recorded loans on Priors CreditPoolV2.`);let M=(await Promise.all(k.map(async W=>{let se=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[W]});return Ce(W,se)}))).filter(W=>W.agentId===t&&W.status===1);if(M.length===0)throw new a(`ERC-8004 agent ${t} has no active loans to repay.`);d=M[M.length-1]}let w=d.principal+d.fee,b=n.maxDue!==void 0?ee(n.maxDue):w;if(b<w)throw new a(`Provided maxDue ${b} is below the exact fixed loan debt ${w} USDG base units (principal ${d.principal} + fixed fee ${d.fee}).`);if(b>w)throw new a(`Provided maxDue ${b} is above the exact fixed loan debt ${w} USDG base units. Use the fixed debt or omit maxDue.`);let m=e.approval(c.usdg,c.pool,w.toString(),$),h=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"repay",args:[d.loanId,t,b]}),value:"0",chainId:$,description:`Repay fixed debt ${w} USDG base units (principal ${d.principal} + fee ${d.fee}) for loan ${d.loanId} (agent ${t}).`}),I=[m,h],l=await e.preview(I,o),v=e.formatAmount(w.toString(),N),P=e.formatAmount(d.principal.toString(),N),_=e.formatAmount(d.fee.toString(),N),F=`Approve and repay ${v} USDG (${w} base units: ${P} USDG principal + ${_} USDG fixed fee) for Priors loan ${d.loanId} (agent ${t}).`;return{txs:I,summary:te(e,F,l.changes)}}},R={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(n,s){z(s);let o=B(s),t=e.clientFor($),[r,p,d,w]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]}),t.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),t.getBlock(),t.readContract({address:c.stockVault,abi:At,functionName:"assetList"})]),b=r>0n?await t.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[r]}):0n,m=r>0n&&p>0n&&d.timestamp<p+He,h=m?b*bt/wt:0n,I=b-h,l=null;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")l=pe(n.agentId,"agentId");else{let q=await _e(e,o);q.length>0&&(l=q[0])}let v=null,P=!1,_=[],F=null,k=null,D=null,M=null,W=null,se=null,j=`This wallet owns no ERC-8004 agent identity. ${Ye}`;if(l!==null){let[q,K,ae,oe,Lt,xt,Be,Ne,Le]=await Promise.all([t.readContract({address:c.lens,abi:St,functionName:"score",args:[l]}),t.readContract({address:x,abi:E,functionName:"firstLined",args:[l]}),t.readContract({address:x,abi:E,functionName:"agentId"}),t.readContract({address:x,abi:E,functionName:"rules"}),t.readContract({address:x,abi:E,functionName:"epochRoom"}),t.readContract({address:C,abi:U,functionName:"bonds",args:[l]}),t.readContract({address:C,abi:U,functionName:"amount"}),t.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[l]}),t.readContract({address:C,abi:U,functionName:"releasable",args:[l]})]),[Ot,Ut,Et,Gt,Vt,Ft]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[l]}),t.readContract({address:c.lens,abi:St,functionName:"available",args:[l]}),t.readContract({address:c.stockVault,abi:At,functionName:"borrowRoom",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"isController",args:[l,o]})]),xe=await De(e,l),Mt=B(Vt),Ze=Ft,y=we(Ot),Se=y.delegatedIn>y.principalOut?y.delegatedIn-y.principalOut:0n;P=y.enrolled&&!y.isRoot&&!y.defaulted&&!y.frozen&&y.sponsor>0n&&y.delegatedIn>0n,F=Et.toString(),k=Gt.toString();let qt=await Promise.all(Ut.map(async T=>{let de=await t.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[T]});return Ce(T,de)}));for(let T of qt)if(T.agentId===l&&T.status===1){let de=T.principal+T.fee;_.push({loanId:T.loanId.toString(),agentId:T.agentId.toString(),sponsorId:T.sponsorId.toString(),principal:T.principal.toString(),fee:T.fee.toString(),due:de.toString(),dueAt:T.dueAt.toString(),issuedAt:T.issuedAt.toString(),owner:T.owner,token:ce})}v={agentId:l.toString(),owner:xe,delegate:Mt,isAuthorizedController:Ze,enrolled:y.enrolled,isRoot:y.isRoot,defaulted:y.defaulted,frozen:y.frozen,sponsorId:y.sponsor.toString(),delegatedIn:y.delegatedIn.toString(),delegatedOut:y.delegatedOut.toString(),principalOut:y.principalOut.toString(),availableCapacity:Se.toString(),activeLoansCount:y.activeLoans.toString(),loansRepaid:y.loansRepaid.toString(),volumeRepaid:y.volumeRepaid.toString(),feesPaid:y.feesPaid.toString(),importedFromV1:y.importedFromV1,qualifiedRepaid:y.qualifiedRepaid.toString(),dollarSecondsRepaid:y.dollarSecondsRepaid.toString()};let Ae=BigInt(ae),Oe=K===!0,Q=ye(xt),ie=Q.depositor!==Je,ve=ie&&V(Q.depositor,o),Ke=Pt(y,Oe),Ue=V(xe,o);D={onchain:BigInt(q).toString(),scale:"0-1000",source:`CreditLensV2.score(${l}) at ${c.lens}, the score the pool computes on chain`,scoreV2:null},M={open:y.sponsor!==0n&&y.delegatedIn>0n,amount:y.delegatedIn.toString(),drawn:y.principalOut.toString(),available:Se.toString(),sponsorId:y.sponsor.toString(),backer:y.sponsor===0n?null:y.sponsor===Ae?`Priors' treasury v4 (root #${Ae})`:`root #${y.sponsor}`,token:ce},W={contract:C,posted:ie,depositor:ie?Q.depositor:null,postedByWallet:ve,postedAt:ie?Q.at.toString():null,amount:(ie?Q.amount:BigInt(Be)).toString(),releasable:ie&&Le===!0,releaseAt:ie?BigInt(Ne).toString():null,rule:"Back to its depositor once the agent holds no line and has no loan open, from 4 days after it was posted (close a line first with priors_close_line); a default forfeits it to Priors' Safe."},se={eligible:Ue&&!Ke,firstLined:Oe,lineAmount:BigInt(oe[1]).toString(),bondAmount:BigInt(Be).toString(),treasuryRoot:Ae.toString(),treasuryRoomThisWeek:BigInt(Lt).toString(),note:"Not instant: Priors' invite bot decides each invite, and the treasury caps new lines each week."};let fe=_.map(T=>({id:String(T.loanId),dueAt:BigInt(String(T.dueAt))})).sort((T,de)=>T.dueAt<de.dueAt?-1:T.dueAt>de.dueAt?1:0);y.defaulted?j=`Agent #${l} defaulted; Priors never lends to it again${ve?" and its bond is forfeited":""}.`:!Ze&&!Ue?j=`This wallet does not control agent #${l} on CreditPoolV2 (owner ${xe}); act from its owner or delegate.`:fe.length?j=`Repay loan ${fe[0].id} with priors_repay before it is due at ${G(fe[0].dueAt)}${fe.length>1?` (${fe.length} loans open)`:""}.`:P&&Se>=We?j=`Borrow with priors_borrow (5 USDG minimum, up to ${A(Se)}; the fee is pro-rated by term); Priors counts loans held 7 days or more toward the score.`:!Ke&&Ue?j=ve?`Call priors_starter_line again: the ${A(Q.amount)} bond is posted, and it goes on with the invite bot's ownership proof and the invite's redemption${Le===!0?", or priors_release_bond returns the bond":""}.`:`Call priors_starter_line: a refundable ${A(BigInt(Be))} bond, an invite from Priors' invite bot and your pool consent open a ${A(BigInt(oe[1]))} line from Priors' treasury (each transaction and signature is confirmed).`:ve?j=Le===!0?`Release the ${A(Q.amount)} invite bond with priors_release_bond.`:y.delegatedIn>0n?`The line is open with nothing to draw; to take the bond back, close it with priors_close_line, then priors_release_bond from ${G(BigInt(Ne))}.`:`The ${A(Q.amount)} invite bond comes back with priors_release_bond from ${G(BigInt(Ne))}.`:j=`Agent #${l} has a Priors record but no line to draw now; ${It(e,y,Ae,Oe)}.`}let $e=null;if(n.includeApiCheck){let q=l!==null?`agent=${l.toString()}`:`address=${o}`,K=await tt(e.http,`${Kt}?${q}`,{method:"GET"},Y),ae=Array.isArray(K.agents)?K.agents.find(oe=>Y(oe)&&String(oe.agentId)===String(l)):void 0;D&&Y(ae)&&(D.scoreV2=ae.scoreV2??null),$e={...K,grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:$,blockNumber:d.number?.toString()??null,blockTimestamp:d.timestamp.toString(),wallet:o,token:ce,contracts:c,lender:{shares:r.toString(),grossAssets:b.toString(),earlyExitFeeAssets:h.toString(),netWithdrawAssets:I.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:m,minHoldSeconds:He.toString()},hasFundedLine:P,agentId:l!==null?l.toString():null,nextStep:j,score:D,line:M,bond:W,starterLine:se,agent:v,activeLoans:_,lens:{address:c.lens,available:F,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:c.stockVault,borrowRoom:k,onchainAssetCount:w.length,hostedMcpStockCount:35,extraNonStockAsset:B(Qt),zeroCapAssets:en.map(q=>B(q)),caveat:"Use priors_stock_assets and priors_stock_asset_state for current collateral rules, then priors_stock_open. This summary is an observed asset-count snapshot, not a fixed allowlist; live caps, lending holds and prices control admission."},apiCheck:$e,limitations:["Borrowing and repayment require a sponsor-backed ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet).","Priors line routes are exposed by priors_line_options and priors_capabilities: treasury starter, V5 move/raise, direct sponsor, stock and owner PRIORS backing. Ethos execution uses Priors own owner workflow because its worker supplies no unsigned final transaction.","score.onchain is the pool's on-chain score (CreditLensV2); score.scoreV2 is Priors Score v2 from /api/check, present only with includeApiCheck.","Loan debt is the principal plus the origination fee the pool quotes for the term. The fee is pro-rated by term, not flat (1666 base units for 5 USDG over 1 day, observed live 2026-10-31; priors_borrow shows the exact quote), and is fixed once the loan opens: variable interest is never invented, and early repayment refunds none of it.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}},A=n=>`${e.formatAmount(n.toString(),N)} USDG`;function L(n){let s=V(n.bond.depositor,n.owner)&&n.bond.amount>0n?n.bond.amount:n.bondAmount;return`Bond first: ${A(s)} is locked in Priors' InviteBond for at least ${n.unusedAfter} seconds (${Number(n.unusedAfter)/86400} days) after posting${n.releaseAt>0n?`; unusedReleaseAt is ${G(n.releaseAt)}`:"; the exact release time is read after posting"}. Release requires no line and no open loan; default can forfeit the bond. Invites are not guaranteed. The credit score can lag qualifying repayments. `}function H(n,s,o){if(!V(o.owner,s))throw new a(`This wallet (${s}) does not own ERC-8004 agent ${n} (its owner is ${o.owner}). The bond, the ownership proof and the pool consent are the owner's. Nothing was signed.`);if(o.root!==Ie)throw new a(`TreasurySponsorV4 (${x}) answers root #${o.root}, not the pinned #${Ie}. Nothing was signed; update Oak.`);if(Pt(o.agent,o.firstLined))throw new a(`Agent #${n} already has a Priors record, so priors_starter_line posts no bond and signs nothing: ${It(e,o.agent,o.root,o.firstLined)}; ${o.agent.loansRepaid} loan(s) repaid. The starter line is only for an identity with no record; priors_status shows this one.`)}let ne="stays posted in InviteBond";function O(n){let s=n.agent.delegatedIn>0n?`with a line open it comes back only after priors_close_line (no loan open), then priors_release_bond from ${G(n.releaseAt)} at the earliest`:`while the agent holds no line it comes back with priors_release_bond from ${G(n.releaseAt)} (${Number(n.unusedAfter)/86400} days after it was posted)`;return`The ${A(n.bond.amount>0n?n.bond.amount:n.bondAmount)} bond ${ne} (${C}), posted from this wallet; ${s}, and priors_starter_line never posts a second bond.`}async function J(n,s,o){try{return await o()}catch(t){let r=t instanceof a?t.message:e.plainError(t);if(r.includes(ne)||n===void 0||!/^[0-9]{1,78}$/.test(n))throw t;let p;try{let d=await he(e,BigInt(n),s);p=V(d.bond.depositor,s)?O(d):""}catch{p=`If the bond transactions mined, the invite bond ${ne} (${C}) remains locked until its on-chain release conditions are met; priors_status shows the exact amount and time (its state could not be read just now).`}throw p?new a(`${r} ${p}`):t}}async function ge(n,s,o){let t=at(await Xe(e,{agentId:n}),{agentId:n,owner:s,now:ue()});if(!t.ok&&t.refused)throw new a(`Priors' invite bot gave no ownership proof to sign for agent #${n}: ${be(t.why)}. Nothing was signed. ${o}`.trim());if(!t.ok)throw new a(`Not signed: the invite bot's answer for agent #${n} is not one Oak signs: ${t.why}. Oak signs only the bot's own start-page text, rebuilt locally for this agent and this wallet. ${o}`.trim());if(t.exp-ue()<120)throw new a(`Not signed: the invite bot's proof for agent #${n} expires in under 2 minutes; call priors_starter_line again for a new one. ${o}`.trim());return t}function Z(n,s,o,t){return{steps:[{kind:"message",message:o.message}],continuation:{stage:"proof",wallet:s,chainId:$,agentId:n,n:o.n,exp:o.exp},summary:`${L(t)}Priors starter line for ERC-8004 agent ${n}, step 2 of 3: sign Priors' invite-bot ownership proof. It is a message signature (EIP-191) only: it sends no transaction and moves no funds. The text is the bot's own form, rebuilt locally for agent #${n} and this wallet, request ${o.n}, expiring ${G(o.exp)}. Oak then sends the signature to ${me}, and the bot decides the invite. ${O(t)}`}}function re(n,s,o){if(n.chainId!==$||typeof n.wallet!="string"||!V(n.wallet,s)||typeof n.agentId!="string"||!/^[1-9][0-9]{0,29}$/.test(n.agentId))throw new a("Priors starter-line continuation does not match this wallet or chain 4663; start priors_starter_line again.");if(o.agentId!==void 0&&String(o.agentId)!==n.agentId)throw new a("Priors starter-line continuation is for another agent; start priors_starter_line again.");return BigInt(n.agentId)}async function Te(n,s){let o;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")o=pe(n.agentId,"agentId");else{let l=await _e(e,s);if(!l.length)throw new a(`Priors' starter line needs an ERC-8004 agent identity, and this wallet owns none. ${Ye}`);o=l[0]}let t=await he(e,o,s);H(o,s,t);let r=o.toString(),p=V(t.bond.depositor,s);if(!p){if(t.usdg<t.bondAmount)throw new a(`This wallet holds ${A(t.usdg)} on Robinhood Chain, and Priors' treasury invite asks a ${A(t.bondAmount)} bond first (InviteBond ${C}), posted from this wallet. Nothing was signed: add USDG, then call priors_starter_line again.`);if(t.epochRoom<t.firstLineAmount)return{summary:`${L(t)}Not submitted. Priors' treasury has ${A(t.epochRoom)} of room left this week and a first line is ${A(t.firstLineAmount)}, so priors_starter_line posted no bond and signed nothing. The treasury caps new lines each week: ask again next week.`,starterLine:{agentId:r,open:!1,reason:"room",epochRoom:t.epochRoom.toString()}};let l=await Xe(e,{check:!0,owner:s.toLowerCase()});if(l.check!==!0)throw new a("Priors' invite bot did not answer its check, so whether an invite is open cannot be told. Nothing was signed.");if(l.ok!==!0)throw new a(`Whether an automatic invite is open could not be told: Priors' invite bot says ${be(l.error)}. Nothing was signed; try again later.`);if(l.open!==!0){let v=typeof l.reason=="string"?l.reason.replace(/[^a-z-]/g,"").slice(0,24):"",P=typeof l.reopensAt=="number"&&Number.isSafeInteger(l.reopensAt)&&l.reopensAt>0?l.reopensAt:null;return{summary:`${L(t)}Not submitted. No automatic invite is open to this wallet right now, so priors_starter_line posted no bond and signed nothing. Priors' invite bot answers: closed, reason ${Ee(v||"none given")}${P?`, reopens ${G(P)}`:""}. ${dt({...l,reason:v})} Priors lists its other ways to a first line (the Ethos lane, a stock line, the owner's $PRIORS stake) at https://priors.trade/skill.md.`,starterLine:{agentId:r,open:!1,reason:v||null,reopensAt:P}}}}let d=await ge(r,s,p?O(t):"");if(p)return Z(r,s,d,t);let w=[e.approval(c.usdg,C,t.bondAmount.toString(),$),e.unsignedTx({to:C,data:X({abi:U,functionName:"deposit",args:[o]}),value:"0",chainId:$,description:`Post the ${t.bondAmount} USDG base-unit Priors invite bond for agent ${r} in InviteBond (${C}).`})],b=await e.preview(w,s),m=t.bond.depositor!==Je?` This deposit replaces the bond ${t.bond.depositor} posted for this agent; InviteBond returns that bond to it in the same transaction.`:"",h=`${L(t)}Priors starter line for ERC-8004 agent ${r}, step 1 of 3: approve exactly ${A(t.bondAmount)} to Priors' InviteBond (${C}) and post it as the agent's refundable invite bond (InviteBond.deposit).${m} Priors' invite bot says an automatic invite is open now and gave the ownership proof to sign next. Step 2 signs that proof (a message, no transaction); step 3 signs your pool consent and redeems the invite (TreasurySponsorV4.firstLine, ${x}) for a ${A(t.firstLineAmount)} line from Priors' treasury (root #${t.root}). The invite is the bot's decision, not a promise: if it refuses, or any later step fails, the bond stays posted and comes back with priors_release_bond after the on-chain lock and release conditions are met. With a line, the bond comes back only once the line is closed with no loan open (priors_close_line, then priors_release_bond); a default forfeits it to Priors' Safe.`;return{steps:w.map(l=>({kind:"tx",tx:l})),continuation:{stage:"bond",wallet:s,chainId:$,agentId:r,n:d.n,exp:d.exp},summary:te(e,h,b.changes)}}async function Rt(n,s,o){let t=await he(e,n,s);H(n,s,t);let r=n.toString();if(!V(t.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet, so nothing more was signed. Check the deposit transaction, then call priors_starter_line again.`);return typeof o.n=="string"&&Ve.test(o.n)&&typeof o.exp=="number"&&Number.isSafeInteger(o.exp)&&o.exp-ue()>=300?Z(r,s,{n:o.n,exp:o.exp,message:Me(r,o.n,o.exp)},t):Z(r,s,await ge(r,s,O(t)),t)}async function _t(n,s,o,t){let r=n.toString();if(typeof o.n!="string"||!Ve.test(o.n)||typeof o.exp!="number"||!Number.isSafeInteger(o.exp))throw new a("Invalid Priors starter-line proof continuation; start priors_starter_line again.");if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the invite bot's ownership proof.");if(o.exp<=ue())throw new a(`The invite bot's proof for agent #${r} expired before it reached the bot; nothing was sent to it. Call priors_starter_line again for a fresh proof (the bond is not posted again).`);let p=Me(r,o.n,o.exp);if(!V(await Yt({message:p,signature:t}),s))throw new a("The ownership-proof signature is not this wallet's; nothing was sent to the invite bot.");let d=await he(e,n,s);if(H(n,s,d),!V(d.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet; nothing was sent to the invite bot. Call priors_starter_line again.`);let w=await Xe(e,{n:o.n,signature:t});if(w.ok!==!0)throw new a(`Priors' invite bot gave no invite for agent #${r}: ${be(w.error)}. ${O(d)}`);if(typeof w.code!="string")throw new a(`Priors' invite bot gave no invite for agent #${r}${w.reason?`: ${be(w.reason)}`:""}${typeof w.decided=="string"?` (its decision: ${be(w.decided)})`:""}. ${O(d)}`);let b=qe(w.code,r,ue()+60);if(!b.ok)throw new a(`Priors' invite bot's code for agent #${r} is not one Oak redeems: ${b.why}. Nothing more was signed. ${O(d)}`);let m=e.clientFor($),h=await m.readContract({address:x,abi:E,functionName:"inviteDigest",args:[n,b.expiry]});if(h.toLowerCase()!==st(n,b.expiry).toLowerCase())throw new a("TreasurySponsorV4's invite digest differs from its pinned EIP-712 domain; nothing more was signed. Update Oak.");let I=await Xt({hash:h,signature:b.signature}),[l,v]=await Promise.all([m.readContract({address:x,abi:E,functionName:"inviters",args:[I]}),m.readContract({address:x,abi:E,functionName:"inviteUsed",args:[h]})]);if(l!==!0)throw new a(`Priors' invite for agent #${r} was signed by ${I}, which TreasurySponsorV4 does not name an inviter, so the treasury would refuse it. Nothing more was signed. ${O(d)}`);if(v===!0)throw new a(`Priors' invite for agent #${r} was already used. Nothing more was signed. ${O(d)}`);let[P,_]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]),F=_.timestamp+BigInt(it),k=Fe({agentId:r,owner:s,nonce:P.toString(),deadline:F.toString()}),D=await m.readContract({address:c.pool,abi:S,functionName:"consentDigest",args:[{agentId:n,sponsorId:d.root,owner:s,maxPremiumBps:0n,nonce:P,deadline:F}]});if(D.toLowerCase()!==rt(k).toLowerCase())throw new a(`The pool's consentDigest (${D}) differs from the consent Oak builds for CreditPoolV2 (${c.pool}), so the pool would refuse it. Nothing more was signed. ${O(d)}`);return{steps:[{kind:"typedData",request:k}],continuation:{stage:"consent",wallet:s,chainId:$,agentId:r,invite:w.code,request:k},summary:`Priors starter line for ERC-8004 agent ${r}, step 3 of 3: Priors' invite bot gave an invite (signed by ${I}, an inviter TreasurySponsorV4 names; it expires ${G(b.expiry)}). Sign your pool consent (EIP-712 "Priors Credit" version 2 on CreditPoolV2 ${c.pool}): it lets Priors' treasury (root #${d.root}) back a line for agent #${r} with premium 0, nonce ${P}, valid until ${G(F)}. A transaction redeeming the invite (TreasurySponsorV4.firstLine) follows for your confirmation. ${O(d)}`}}async function kt(n,s,o,t){let r=n.toString();if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the Priors pool consent.");let p=qe(o.invite,r,ue()+60);if(!p.ok)throw new a(`The invite for agent #${r} is not one Oak redeems now: ${p.why}. Call priors_starter_line again for a new one.`);let d=Y(o.request)&&Y(o.request.message)?o.request.message:void 0;if(!d||typeof d.nonce!="string"||!/^[0-9]{1,78}$/.test(d.nonce)||typeof d.deadline!="string"||!/^[0-9]{1,20}$/.test(d.deadline))throw new a("Invalid Priors starter-line consent continuation; start priors_starter_line again.");let w=Fe({agentId:r,owner:s,nonce:d.nonce,deadline:d.deadline});if(!V(await Zt({...w,signature:t}),s))throw new a("The pool-consent signature is not this wallet's for the consent Oak built; nothing was offered.");let b=await he(e,n,s);H(n,s,b);let m=e.clientFor($),[h,I]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]);if(h.toString()!==d.nonce)throw new a(`Agent #${r}'s consent nonce moved on chain since it was signed; nothing was offered. Call priors_starter_line again.`);if(I.timestamp>=BigInt(d.deadline))throw new a(`The pool consent for agent #${r} expired at ${G(BigInt(d.deadline))}; nothing was offered. Call priors_starter_line again.`);let l={agentId:n,sponsorId:Ie,owner:s,maxPremiumBps:0n,nonce:h,deadline:BigInt(d.deadline)},v=[n,p.expiry,p.signature,l,t];try{await m.simulateContract({address:x,abi:E,functionName:"firstLine",args:v,account:s})}catch(k){throw new a(`TreasurySponsorV4.firstLine for agent #${r} would be refused: ${an(e,k)} Nothing was offered. ${O(b)}`)}let P=e.unsignedTx({to:x,data:X({abi:E,functionName:"firstLine",args:v}),value:"0",chainId:$,description:`Redeem Priors' invite for agent ${r}: TreasurySponsorV4.firstLine opens a ${b.firstLineAmount} USDG base-unit line from root ${b.root} with the owner's consent.`}),_=await e.preview([P],s),F=`Redeem agent #${r}'s Priors invite: TreasurySponsorV4.firstLine (${x}) opens a ${A(b.firstLineAmount)} line from Priors' treasury (root #${b.root}) with your signed consent. No USDG moves in this transaction. Then priors_status shows the line and priors_borrow draws it (5 USDG minimum; the fee is pro-rated by term; Priors counts loans held 7 days or more toward the score). The ${A(b.bondAmount)} bond stays in InviteBond until the line is closed with no loan open (priors_close_line, then priors_release_bond, from ${G(b.releaseAt)} at the earliest); a default forfeits it.`;return{txs:[P],summary:te(e,F,_.changes)}}let Dt={name:"priors_starter_line",inputSchema:{description:"Bond first: the launch bond is 5 USDG, locked at least 4 days. The first result reads amount(), unusedAfter() and unusedReleaseAt(agentId) for current terms before any approval. Invites are not guaranteed; the credit score can lag. Release needs no line or open loan; default can forfeit the bond.",type:"object",additionalProperties:!1,properties:{agentId:Pe("ERC-8004 agent ID this wallet owns, with no Priors record yet (default: the first identity this wallet owns)."),continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}}},async execute(n,s){z(s);let o=B(s);if(n.continuation===void 0){if(n.signature!==void 0)throw new a("A signature needs its Priors starter-line continuation; start priors_starter_line again.");return J(typeof n.agentId=="string"?n.agentId:void 0,o,()=>Te(n,o))}if(!Y(n.continuation))throw new a("Invalid Priors starter-line continuation; start priors_starter_line again.");let t=n.continuation,r=re(t,o,n),p=d=>J(r.toString(),o,d);if(t.stage==="bond"){if(n.signature!==void 0)throw new a("The bond stage takes no signature; start priors_starter_line again.");return p(()=>Rt(r,o,t))}if(t.stage==="proof")return p(()=>_t(r,o,t,n.signature));if(t.stage==="consent")return p(()=>kt(r,o,t,n.signature));throw new a("Unknown Priors starter-line stage; start priors_starter_line again.")}},Tt={name:"priors_close_line",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose Priors line to close (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),[p,d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:x,abi:E,functionName:"agentId"})]),m=we(p);if(m.sponsor===0n)throw new a(`Agent #${t} has no Priors line to close (no sponsor on CreditPoolV2).`);if(m.activeLoans>0n)throw new a(`Agent #${t} has ${m.activeLoans} loan(s) open; repay them with priors_repay first. The pool's leave refuses while a loan is open.`);let h=ye(d),I=m.sponsor===BigInt(b),l=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"leave",args:[t]}),value:"0",chainId:$,description:`Close agent ${t}'s Priors line on CreditPoolV2 (leave): the ${m.delegatedIn} USDG base-unit line returns to root ${m.sponsor}.`}),v=await e.preview([l],o),P=V(h.depositor,o)?` Its ${A(h.amount)} invite bond can then come back with priors_release_bond from ${G(w)} (4 days after it was posted).`:"",_=`Close agent #${t}'s Priors line (CreditPoolV2.leave, ${c.pool}): the whole ${A(m.delegatedIn)} line goes back to its backer (${I?`Priors' treasury, root #${b}`:`root #${m.sponsor}`}) and the agent can no longer borrow on it. This does not reopen: ${I?`priors_starter_line opens no second treasury line for an agent with a Priors record; another needs a person at ${Ge}.`:"a new line needs a backer's new consent."}${P} No USDG moves in this transaction.`;return{txs:[l],summary:te(e,_,v.changes)}}},Bt={name:"priors_release_bond",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose InviteBond bond this wallet posted (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o),r=e.clientFor($),[p,d,w,b,m]=await Promise.all([r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"releasable",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.getBlock()]),h=ye(p);if(h.depositor===Je)throw new a(`Agent #${t} has no bond in Priors' InviteBond (${C}).`);if(!V(h.depositor,o))throw new a(`Agent #${t}'s InviteBond bond was posted by ${h.depositor}, not this wallet, and InviteBond.release pays the depositor. Oak releases only a bond this wallet posted.`);if(d!==!0){let P=we(b),_=P.defaulted?"the agent defaulted, so the bond is forfeited to Priors' Safe (InviteBond.slash)":P.activeLoans>0n?`the agent has ${P.activeLoans} loan(s) open: repay with priors_repay, close the line with priors_close_line, then release`:P.delegatedIn>0n?`the agent still holds a ${A(P.delegatedIn)} line: close it with priors_close_line (no loan may be open), then release`:m.timestamp<w?`it comes back 4 days after it was posted, from ${G(w)}`:"InviteBond does not release it yet";throw new a(`Agent #${t}'s ${A(h.amount)} invite bond cannot be released now: ${_}. Nothing was signed.`)}let I=e.unsignedTx({to:C,data:X({abi:U,functionName:"release",args:[t]}),value:"0",chainId:$,description:`Release agent ${t}'s ${h.amount} USDG base-unit Priors invite bond from InviteBond (${C}) to its depositor ${h.depositor}.`}),l=await e.preview([I],o),v=`Release agent #${t}'s ${A(h.amount)} invite bond from Priors' InviteBond (${C}): InviteBond.release returns it to its depositor, this wallet (${o}).`;return{txs:[I],summary:te(e,v,l.changes)}}};async function Nt(n){z(n);let s=B(n),o=e.clientFor($),[t,r]=await Promise.all([o.readContract({address:c.pool,abi:S,functionName:"shares",args:[s]}),_e(e,s)]),p=[];if(t>0n){let d=await o.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[t]});p.push({module:"priors",id:`priors:lender:${s.toLowerCase()}`,chainId:$,assets:[{token:ce,amount:d.toString()}],description:`Priors CreditPoolV2 lender position (${t} shares = ${e.formatAmount(d.toString(),N)} USDG gross).`})}for(let d of r){let w=await o.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[d]}),b=await Promise.all(w.map(async h=>{let I=await o.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[h]});return Ce(h,I)}));for(let h of b)if(h.agentId===d&&h.status===1){let I=h.principal+h.fee;p.push({module:"priors",id:`priors:loan:${h.loanId.toString()}`,chainId:$,assets:[{token:ce,amount:I.toString()}],description:`Priors CreditPoolV2 active loan ${h.loanId} for agent ${d} (fixed due ${e.formatAmount(I.toString(),N)} USDG = ${h.principal} principal + ${h.fee} fee).`})}let m=ye(await o.readContract({address:C,abi:U,functionName:"bonds",args:[d]}));m.amount>0n&&V(m.depositor,s)&&p.push({module:"priors",id:`priors:bond:${d.toString()}`,chainId:$,assets:[{token:ce,amount:m.amount.toString()}],description:`Priors invite bond for agent ${d} in InviteBond (${C}): ${A(m.amount)}, back with priors_release_bond once the agent holds no line and no loan, from 4 days after posting; a default forfeits it.`})}return p}return{tools:[i,g,u,f,R,Dt,Tt,Bt],positions:Nt}},ln=e=>{let i=dn(e),g=[i,lt(e),ct(e),pt(e),gt(e),ft(e),mt(e),ut()];return{...i,tools:g.flatMap(u=>u.tools)}},_n=e=>Qe("priors",[ln(e)]);export{Kt as a,He as b,bt as c,wt as d,We as e,yt as f,je as g,$t as h,c as i,ce as j,on as k,ln as l,_n as m};
@@ -1 +1 @@
1
- import{b as f}from"./EC5W3UZD.js";import{a as p}from"./6IM6A5VA.js";import{a as u}from"./XPFVT2EA.js";import{a as r}from"./5YS5V2LK.js";import{encodeFunctionData as A,getAddress as w,parseAbi as T,parseAbiItem as F}from"viem";var R=[["setOwner(address newOwner)","owner"],["setCurator(address newCurator)","owner"],["setIsSentinel(address account,bool enabled)","owner"],["setName(string name)","owner"],["setSymbol(string symbol)","owner"],["setIsAllocator(address account,bool enabled)","timelock"],["setReceiveSharesGate(address gate)","timelock"],["setSendSharesGate(address gate)","timelock"],["setReceiveAssetsGate(address gate)","timelock"],["setSendAssetsGate(address gate)","timelock"],["setAdapterRegistry(address registry)","timelock"],["addAdapter(address adapter)","timelock"],["removeAdapter(address adapter)","timelock"],["increaseTimelock(bytes4 selector,uint256 duration)","timelock"],["decreaseTimelock(bytes4 selector,uint256 duration)","timelock"],["abdicate(bytes4 selector)","timelock"],["setPerformanceFee(uint256 fee)","timelock"],["setManagementFee(uint256 fee)","timelock"],["setPerformanceFeeRecipient(address recipient)","timelock"],["setManagementFeeRecipient(address recipient)","timelock"],["increaseAbsoluteCap(bytes idData,uint256 cap)","timelock"],["increaseRelativeCap(bytes idData,uint256 cap)","timelock"],["decreaseAbsoluteCap(bytes idData,uint256 cap)","curatorOrSentinel"],["decreaseRelativeCap(bytes idData,uint256 cap)","curatorOrSentinel"],["setForceDeallocatePenalty(address adapter,uint256 penalty)","timelock"],["allocate(address adapter,bytes data,uint256 assets)","allocator"],["deallocate(address adapter,bytes data,uint256 assets)","allocatorOrSentinel"],["setLiquidityAdapterAndData(address adapter,bytes data)","allocator"],["setMaxRate(uint256 rate)","allocator"],["accrueInterest()","any"]],S=R.map(([a,t])=>({abi:F(`function ${a}`),authority:t})),x=T(["function asset() view returns (address)","function owner() view returns (address)","function curator() view returns (address)","function isSentinel(address) view returns (bool)","function isAllocator(address) view returns (bool)","function executableAt(bytes) view returns (uint256)","function abdicated(bytes4) view returns (bool)","function submit(bytes data)","function revoke(bytes data)"]);function M(a,t){if(a==="bool"){if(typeof t!="boolean")throw new r("Boolean operation values must be booleans.");return t}if(typeof t!="string")throw new r("All address, byte, text and integer operation values must be strings.");if(a==="address")return p(t),w(t);if(a==="uint256"){if(!/^\d+$/.test(t)||BigInt(t)>=1n<<256n)throw new r("Integer operation values must be uint256 decimal base-unit strings.");return BigInt(t)}if((a==="bytes"||a==="bytes4")&&!(a==="bytes4"?/^0x[0-9a-f]{8}$/i:/^0x(?:[0-9a-f]{2})*$/i).test(t))throw new r("Invalid hexadecimal operation bytes.");return t}function E(a,t,m,O){return{name:t,inputSchema:{type:"object",additionalProperties:!1,required:["operation","values"],properties:{operation:{type:"string",enum:S.map(i=>i.abi.name)},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]},description:"Ordered ABI values. Integers are decimal base-unit strings; addresses and bytes are explicit strings."},mode:{enum:["call","submit","revoke"],default:"call",description:"Submit/revoke only for timelocked curator operations. Execution is a separate call after the delay."}}},execute:async(i,c)=>{try{if(p(c),Object.keys(i).some(e=>!["operation","values","mode"].includes(e)))throw new r("Unexpected vault management argument.");let n=S.find(e=>e.abi.name===i.operation);if(!n||!Array.isArray(i.values)||i.values.length!==n.abi.inputs.length)throw new r("Provide a supported operation and its exact ordered values.");let o=i.mode??"call";if(!["call","submit","revoke"].includes(String(o))||o!=="call"&&n.authority!=="timelock")throw new r("Submit/revoke is available only for timelocked curator operations.");let I=n.abi.inputs.map((e,d)=>M(e.type,i.values[d])),l=A({abi:[n.abi],functionName:n.abi.name,args:I}),b=a.clientFor(u);if(await b.getChainId()!==u)throw new r("Vault management requires chain 4663.");let s=(e,d=[])=>b.readContract({address:m,abi:x,functionName:e,args:d}),y=await s("asset");if(typeof y!="string"||w(y)!==w(O.address))throw new r("Vault management requires the pinned vault asset.");let g=e=>typeof e=="string"&&e.toLowerCase()===c.toLowerCase(),C=async e=>e==="any"?!0:e==="owner"?g(await s("owner")):e==="allocator"?await s("isAllocator",[c])===!0:e==="allocatorOrSentinel"?await s("isAllocator",[c])===!0||await s("isSentinel",[c])===!0:g(await s("curator"))||e==="curatorOrSentinel"&&await s("isSentinel",[c])===!0;if(n.authority==="timelock"&&o==="call"){let[e,d,D]=await Promise.all([s("executableAt",[l]),s("abdicated",[l.slice(0,10)]),b.getBlock()]);if(f(e)===0n||f(e)>D.timestamp||d!==!1)throw new r("This exact operation has not matured or its selector is abdicated. Submit it with the curator, then wait for its executable time.")}else if(!await C(o==="submit"?"timelock":o==="revoke"?"curatorOrSentinel":n.authority))throw new r("This wallet does not hold the required vault management role. No transaction was built.");let $=o==="call"?l:A({abi:x,functionName:o==="submit"?"submit":"revoke",args:[l]}),k=`${o} ${n.abi.name} on ${m}; ordered values ${JSON.stringify(i.values)}. ${n.abi.name==="abdicate"?"Abdication is irreversible.":""}`,h=[a.unsignedTx({to:m,data:$,value:"0",chainId:u,description:k})],v=await a.preview(h,c);return{txs:h,preview:v,summary:`${k} ${v.summary} ${o==="submit"?"Submission schedules this exact operation; it does not execute the configuration change.":"Role, cap and timing checks can change before execution."}`}}catch(n){throw new r(a.plainError(n))}}}}export{S as a,M as b,E as c};
1
+ import{b as f}from"./AMICUXS6.js";import{a as p}from"./6IM6A5VA.js";import{a as u}from"./G6HCV67X.js";import{a as r}from"./5YS5V2LK.js";import{encodeFunctionData as A,getAddress as w,parseAbi as T,parseAbiItem as F}from"viem";var R=[["setOwner(address newOwner)","owner"],["setCurator(address newCurator)","owner"],["setIsSentinel(address account,bool enabled)","owner"],["setName(string name)","owner"],["setSymbol(string symbol)","owner"],["setIsAllocator(address account,bool enabled)","timelock"],["setReceiveSharesGate(address gate)","timelock"],["setSendSharesGate(address gate)","timelock"],["setReceiveAssetsGate(address gate)","timelock"],["setSendAssetsGate(address gate)","timelock"],["setAdapterRegistry(address registry)","timelock"],["addAdapter(address adapter)","timelock"],["removeAdapter(address adapter)","timelock"],["increaseTimelock(bytes4 selector,uint256 duration)","timelock"],["decreaseTimelock(bytes4 selector,uint256 duration)","timelock"],["abdicate(bytes4 selector)","timelock"],["setPerformanceFee(uint256 fee)","timelock"],["setManagementFee(uint256 fee)","timelock"],["setPerformanceFeeRecipient(address recipient)","timelock"],["setManagementFeeRecipient(address recipient)","timelock"],["increaseAbsoluteCap(bytes idData,uint256 cap)","timelock"],["increaseRelativeCap(bytes idData,uint256 cap)","timelock"],["decreaseAbsoluteCap(bytes idData,uint256 cap)","curatorOrSentinel"],["decreaseRelativeCap(bytes idData,uint256 cap)","curatorOrSentinel"],["setForceDeallocatePenalty(address adapter,uint256 penalty)","timelock"],["allocate(address adapter,bytes data,uint256 assets)","allocator"],["deallocate(address adapter,bytes data,uint256 assets)","allocatorOrSentinel"],["setLiquidityAdapterAndData(address adapter,bytes data)","allocator"],["setMaxRate(uint256 rate)","allocator"],["accrueInterest()","any"]],S=R.map(([a,t])=>({abi:F(`function ${a}`),authority:t})),x=T(["function asset() view returns (address)","function owner() view returns (address)","function curator() view returns (address)","function isSentinel(address) view returns (bool)","function isAllocator(address) view returns (bool)","function executableAt(bytes) view returns (uint256)","function abdicated(bytes4) view returns (bool)","function submit(bytes data)","function revoke(bytes data)"]);function M(a,t){if(a==="bool"){if(typeof t!="boolean")throw new r("Boolean operation values must be booleans.");return t}if(typeof t!="string")throw new r("All address, byte, text and integer operation values must be strings.");if(a==="address")return p(t),w(t);if(a==="uint256"){if(!/^\d+$/.test(t)||BigInt(t)>=1n<<256n)throw new r("Integer operation values must be uint256 decimal base-unit strings.");return BigInt(t)}if((a==="bytes"||a==="bytes4")&&!(a==="bytes4"?/^0x[0-9a-f]{8}$/i:/^0x(?:[0-9a-f]{2})*$/i).test(t))throw new r("Invalid hexadecimal operation bytes.");return t}function E(a,t,m,O){return{name:t,inputSchema:{type:"object",additionalProperties:!1,required:["operation","values"],properties:{operation:{type:"string",enum:S.map(i=>i.abi.name)},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]},description:"Ordered ABI values. Integers are decimal base-unit strings; addresses and bytes are explicit strings."},mode:{enum:["call","submit","revoke"],default:"call",description:"Submit/revoke only for timelocked curator operations. Execution is a separate call after the delay."}}},execute:async(i,c)=>{try{if(p(c),Object.keys(i).some(e=>!["operation","values","mode"].includes(e)))throw new r("Unexpected vault management argument.");let n=S.find(e=>e.abi.name===i.operation);if(!n||!Array.isArray(i.values)||i.values.length!==n.abi.inputs.length)throw new r("Provide a supported operation and its exact ordered values.");let o=i.mode??"call";if(!["call","submit","revoke"].includes(String(o))||o!=="call"&&n.authority!=="timelock")throw new r("Submit/revoke is available only for timelocked curator operations.");let I=n.abi.inputs.map((e,d)=>M(e.type,i.values[d])),l=A({abi:[n.abi],functionName:n.abi.name,args:I}),b=a.clientFor(u);if(await b.getChainId()!==u)throw new r("Vault management requires chain 4663.");let s=(e,d=[])=>b.readContract({address:m,abi:x,functionName:e,args:d}),y=await s("asset");if(typeof y!="string"||w(y)!==w(O.address))throw new r("Vault management requires the pinned vault asset.");let g=e=>typeof e=="string"&&e.toLowerCase()===c.toLowerCase(),C=async e=>e==="any"?!0:e==="owner"?g(await s("owner")):e==="allocator"?await s("isAllocator",[c])===!0:e==="allocatorOrSentinel"?await s("isAllocator",[c])===!0||await s("isSentinel",[c])===!0:g(await s("curator"))||e==="curatorOrSentinel"&&await s("isSentinel",[c])===!0;if(n.authority==="timelock"&&o==="call"){let[e,d,D]=await Promise.all([s("executableAt",[l]),s("abdicated",[l.slice(0,10)]),b.getBlock()]);if(f(e)===0n||f(e)>D.timestamp||d!==!1)throw new r("This exact operation has not matured or its selector is abdicated. Submit it with the curator, then wait for its executable time.")}else if(!await C(o==="submit"?"timelock":o==="revoke"?"curatorOrSentinel":n.authority))throw new r("This wallet does not hold the required vault management role. No transaction was built.");let $=o==="call"?l:A({abi:x,functionName:o==="submit"?"submit":"revoke",args:[l]}),k=`${o} ${n.abi.name} on ${m}; ordered values ${JSON.stringify(i.values)}. ${n.abi.name==="abdicate"?"Abdication is irreversible.":""}`,h=[a.unsignedTx({to:m,data:$,value:"0",chainId:u,description:k})],v=await a.preview(h,c);return{txs:h,preview:v,summary:`${k} ${v.summary} ${o==="submit"?"Submission schedules this exact operation; it does not execute the configuration change.":"Role, cap and timing checks can change before execution."}`}}catch(n){throw new r(a.plainError(n))}}}}export{S as a,M as b,E as c};
@@ -0,0 +1 @@
1
+ import{A as le,s as D,x as W}from"./Q356HHCL.js";import{d as fe}from"./MKQVS3IO.js";import{a as me,b as ee,c as de,e as oe,f as ye,g as pe,h as V,i as b,j as g,l as M,m as N,o as U,p as B,q as T,s as O,u as E,v as _}from"./5OEHZJ6X.js";import{b as G,g as K,h as X,i as se,j as ue}from"./ACN2BFMA.js";import{c as Z}from"./73N3TOJL.js";import{a as i}from"./5YS5V2LK.js";import{encodeAbiParameters as Oe,getAddress as we,keccak256 as Ke,parseAbi as Ve,toHex as ae,zeroAddress as je}from"viem";import{encodeAbiParameters as ge,encodePacked as Ce,getAddress as Ae,keccak256 as te,parseAbi as Fe,toHex as Le,zeroAddress as ke}from"viem";var Re=1n<<256n,ve=1n<<128n,Ue=Fe(["function extsload(bytes32[] slots) view returns (bytes32[])"]),$=(o,n)=>({type:"object",additionalProperties:!1,properties:o,required:n}),qe={oneOf:[$({kind:{const:"family"},launcher:Z,familyId:ee,member:{type:"string",enum:["0","1","2","3","4","5","6","7"]}},["kind","launcher","familyId","member"]),$({kind:{const:"nft"},tokenId:me},["kind","tokenId"]),$({kind:{const:"agent-account"},account:Z,positionId:ee},["kind","account","positionId"])]};function Ne(o){let n=N(o);if(n.kind!=="family")throw new i("This step supports Launcher family positions only. NFT and agent-account position reads are reserved for a later integration.");oe(n,["kind","launcher","familyId","member"],["kind","launcher","familyId","member"]);let e=ye(n.member,8);if(e>7n)throw new i("Hookr family member must be a decimal string from 0 to 7.");return{kind:"family",launcher:ue(n.launcher),familyId:V(n.familyId),member:e.toString()}}var C=o=>Le(BigInt.asUintN(256,o),{size:32}),ne=(o,n)=>te(ge([{type:"bytes32"},{type:"bytes32"}],[o,n]));function re(o,n,e,a,r,H){let w=ne(o,C(6n)),P=m=>ne(C(BigInt(m)),C(BigInt(w)+4n)),y=te(ge([{type:"bytes32"},{type:"uint8"}],[e,a])),c=te(Ce(["address","int24","int24","bytes32"],[n,r,H,y])),u=ne(c,C(BigInt(w)+6n));return[w,C(BigInt(w)+1n),C(BigInt(w)+2n),C(BigInt(P(r))+1n),C(BigInt(P(r))+2n),C(BigInt(P(H))+1n),C(BigInt(P(H))+2n),u,C(BigInt(u)+1n),C(BigInt(u)+2n)]}function Q(o,n,e,a,r,H){return BigInt.asUintN(256,a<r?n-e:a>=H?e-n:o-n-e)}function J(o,n,e){if(o<0n||o>=1n<<128n||[n,e].some(a=>a<0n||a>=Re))throw new i("Hookr fee inputs are outside the verified v4 layout.");return o*BigInt.asUintN(256,n-e)/ve}function ie(o){let n=N(o),e={currency0:b(n.currency0),currency1:b(n.currency1),fee:Number(g(n.fee,24)),tickSpacing:Number(g(n.tickSpacing,24)),hooks:b(n.hooks)};if(BigInt(e.currency0)>=BigInt(e.currency1)||e.fee!==8388608||e.hooks!==T||e.tickSpacing<1||e.tickSpacing>32767)throw new i("Hookr family PoolKey is not a supported Root dynamic-fee pool.");return e}async function Te(o,n,e,a){let r=await X(o,a),H={},w=new Set,P=(t,k=[])=>B(o,e.launcher,U(e.launcher===Ae(G.launcherV1)?"launcherV1":"launcher"),t,k,r.number),y=async(t,k)=>{try{return await k()}catch(S){return H[t]=S instanceof i?S.message:`Hookr ${t} read failed at block ${r.number}. Retry the named-block read; no zero or empty result is implied.`,null}},c={chainId:4663,blockNumber:r.number.toString(),blockHash:r.hash,position:e,owner:null,ownedByWallet:null,poolId:null,poolKey:null,range:null,liquidity:null,tokens:null,principal:null,uncollectedLpFees:null,collectedLpFees:null,claimableCoreCredits:null,poolPendingRecapture:null,inRange:null,gateStatus:null,locks:null},u=async()=>(await se(o,r),{...c,readStatus:{status:Object.keys(H).length?"partial":"complete",reasons:H},warnings:["collectedLpFees is null: no complete collection-history reconstruction is available in this step.","LP fees can include donations already released into v4 fee growth. Pending recapture is pool-level, unallocated and excluded from LP fees.","Principal is current withdrawable token inventory before fees, gas or price changes; it is not the original deposit value."]});if(await y("pins",async()=>(await K(o,r.number,[e.launcher,T,O],w),!0))===null)return u();let m=await y("owner",async()=>{let t=b(await P("familyOwner",[e.familyId]));if(t===ke)throw new i("Hookr family does not exist at this block. Check its Launcher and family ID.");return t});if(m===null)return u();c.owner=m,c.ownedByWallet=m===n;let R=await y("position",async()=>{let[t,k,S]=await Promise.all([P("memberCount",[e.familyId]),P("position",[e.familyId,Number(e.member)]),P("poolManager")]);if(S!==O||g(t,8)>8n||BigInt(e.member)>=g(t,8))throw new i("Hookr family member or PoolManager is invalid.");let h=N(k),d=ie(h.key);if(typeof h.tickLower!="number"||typeof h.tickUpper!="number")throw new i("Hookr position range is incomplete.");W(h.tickLower,h.tickUpper,d.tickSpacing);let s=g(h.liquidity,128),L=D(d);if(await P("poolFamily",[L])!==e.familyId)throw new i("Hookr pool does not belong to this family.");return{key:d,id:L,tickLower:h.tickLower,tickUpper:h.tickUpper,liquidity:s}});if(R===null)return u();let{key:l,id:p,tickLower:A,tickUpper:I,liquidity:v}=R;c.poolKey=l,c.poolId=p,c.range={tickLower:A,tickUpper:I},c.liquidity=v.toString();let[f,q,F]=await Promise.all([y("tokens",()=>Promise.all([_(o,l.currency0,r.number),_(o,l.currency1,r.number)])),y("feeGrowth",async()=>{let t=re(p,e.launcher,e.familyId,Number(e.member),A,I),k=await B(o,O,Ue,"extsload",[t],r.number),S=M(k,10).map(Be=>BigInt(V(Be))),[h,d,s,L,Y,x,j,Pe,Ie,Se]=S,ce=h&(1n<<160n)-1n,z=Number(BigInt.asIntN(24,h>>160n));if(ce===0n||z<-887272||z>887272||Pe!==v)throw new i("Hookr PoolManager position is uninitialized or differs from the Launcher liquidity. No principal or fee amount is inferred.");let He=Q(d,L,x,z,A,I),xe=Q(s,Y,j,z,A,I);return{sqrtPriceX96:ce,tick:z,fee0:J(v,He,Ie),fee1:J(v,xe,Se)}}),y("poolConfig",async()=>{let t=N(await B(o,T,U("rootV1"),"poolConfig",[p],r.number));if(b(t.liquidityOwner)!==e.launcher||![l.currency0,l.currency1].includes(b(t.subject))||![l.currency0,l.currency1].includes(b(t.quote))||t.subject===t.quote)throw new i("Hookr pool configuration differs from this family position.");let k=b(t.rules),S=E(k);return await K(o,r.number,[k],w),{pc:t,core:k,role:S}})]);if(c.tokens=f,q&&(c.inRange=q.tick>=A&&q.tick<I,f)){let t=le({liquidity:v,tickLower:A,tickUpper:I,sqrtPriceX96:q.sqrtPriceX96});c.principal=[{token:f[0],amount:t.amount0.toString()},{token:f[1],amount:t.amount1.toString()}],c.uncollectedLpFees=[{token:f[0],amount:q.fee0.toString()},{token:f[1],amount:q.fee1.toString()}]}if(F){let t=(s,L=[])=>B(o,F.core,U("rulesV1"),s,L,r.number),[k,S,h,d]=await Promise.all([y("gateStatus",async()=>{let s=b(F.pc.advisory);return s!==ke&&await K(o,r.number,[s],w),fe(o,r.number,p,e.launcher,s)}),y("locks",async()=>be(o,{position:e,block:r,poolId:p,core:F.core,role:F.role})),y("claimableCoreCredits",async()=>{if(!f)throw new i("Read token metadata before displaying core credits.");let s=await t("poolAccruedCurrencies",[p]);if(!Array.isArray(s)||s.length>32||s.some(x=>x!==l.currency0&&x!==l.currency1))throw new i("Core accrual includes unmeasured currencies; read the core directly before collecting.");let[L,Y]=await Promise.all([Promise.all([l.currency0,l.currency1].map(x=>t("poolAccrued",[p,x]))),Promise.all([l.currency0,l.currency1].map(x=>B(o,F.core,U(F.role),"claimable",[x,n],r.number)))]);return{core:F.core,familyOwnerAccrual:L.map((x,j)=>({token:f[j],amount:g(x).toString()})),walletCredits:Y.map((x,j)=>({token:f[j],amount:g(x).toString()})),walletCreditsScope:"Core-wide wallet credits, not attributed to this position. Do not add them to LP fees."}}),y("poolPendingRecapture",async()=>{if(!f)throw new i("Read token metadata before displaying pending recapture.");let s=M(await t("pendingDonation",[p]),5).map(L=>g(L));return{due:[{token:f[0],amount:s[0].toString()},{token:f[1],amount:s[1].toString()}],fresh:[{token:f[0],amount:s[2].toString()},{token:f[1],amount:s[3].toString()}],freshChildBlock:s[4].toString(),scope:"pool",allocatedToPosition:!1}})]);c.gateStatus=k,c.locks=S,c.claimableCoreCredits=h,c.poolPendingRecapture=d}return u()}function Je(o){return[{name:"hookr_lp_position",inputSchema:$({position:qe,...de},["position"]),execute:async(n,e)=>{oe(n,["position","blockNumber"],["position"]);let a=Ne(n.position);if(o.network==="testnet")throw new i("Hookr LP reads are configured only on mainnet, chain 4663.");try{return await Te(o.clientFor(4663),e,a,pe(n))}catch(r){throw r instanceof i?r:new i("Hookr position block is unavailable. Retry the complete named-block read; no zero position or fee is implied.")}}}]}var he=o=>U(o.launcher===we(G.launcherV1)?"launcherV1":"launcher");function ze(o){let n=Ke(Oe([{type:"bytes32"},{type:"bytes32"}],[o,"0x3c0d3d8cba92527b3a48aa783c8734a4e170057eb16401c9df8a7c8a6588b900"]));return ae(BigInt(n)+5n,{size:32})}async function Me(o,n){try{let e="0x0000000000000000000000000000000000000a11",a=await o.request({method:"eth_call",params:[{to:e,data:"0x"},ae(n.number),{[e]:{code:"0x4360005260206000f3"}}]});return BigInt(V(a))}catch{throw new i("Hookr parent-block clock is unavailable. Retry with an RPC supporting named-block eth_call state overrides; child-chain height cannot establish lock expiry.")}}async function io(o,n,e){let a=await X(o);await K(o,a.number,[e.launcher,T,O]);let r=(d,s=[])=>B(o,e.launcher,he(e),d,s,a.number),[H,w,P,y]=await Promise.all([r("familyOwner",[e.familyId]),r("memberCount",[e.familyId]),r("position",[e.familyId,Number(e.member)]),r("poolManager")]),c=b(H);if(c===je||c!==n)throw new i("Only the current Hookr family owner can add, collect or remove this position. Use its signing wallet.");if(y!==O||g(w,8)<1n||g(w,8)>8n||BigInt(e.member)>=g(w,8))throw new i("Hookr family member or PoolManager differs from the reviewed deployment.");let u=N(P),m=ie(u.key),R=g(u.liquidity,128);if(typeof u.tickLower!="number"||typeof u.tickUpper!="number")throw new i("Hookr family range is unavailable.");let l=u.tickLower,p=u.tickUpper;W(l,p,m.tickSpacing);let A=D(m);if(await r("poolFamily",[A])!==e.familyId)throw new i("Hookr pool does not belong to this Launcher family.");let I=N(await B(o,T,U("rootV1"),"poolConfig",[A],a.number)),v=b(I.rules),f=E(v);if(b(I.liquidityOwner)!==e.launcher||![m.currency0,m.currency1].includes(b(I.subject))||![m.currency0,m.currency1].includes(b(I.quote))||I.subject===I.quote)throw new i("Hookr pool configuration differs from this family key.");await K(o,a.number,[v]);let[q,F]=await Promise.all([Promise.all([m.currency0,m.currency1].map(d=>_(o,d,a.number))),B(o,O,Ve(["function extsload(bytes32[] slots) view returns (bytes32[])"]),"extsload",[re(A,e.launcher,e.familyId,Number(e.member),l,p)],a.number)]),t=M(F,10).map(d=>BigInt(V(d))),k=t[0]&(1n<<160n)-1n,S=Number(BigInt.asIntN(24,t[0]>>160n));if(!k||S<-887272||S>887272||t[7]!==R)throw new i("Hookr PoolManager state differs from the family position. Retry the full read.");let h=[0,1].map(d=>J(R,Q(t[1+d],t[3+d],t[5+d],S,l,p),t[8+d]));return{position:e,block:a,owner:c,key:m,poolId:A,liquidity:R,tickLower:l,tickUpper:p,sqrtPriceX96:k,fees:h,tokens:q,pc:I,core:v,role:f}}async function be(o,n){let{position:e,block:a,poolId:r,core:H,role:w}=n,[P,y,c,u]=await Promise.all([B(o,e.launcher,he(e),"principalLockedUntil",[e.familyId],a.number),B(o,H,U(w),"removalLockedUntil",[r],a.number),o.getStorageAt({address:T,slot:ze(r),blockNumber:a.number}),Me(o,a)]),m=BigInt(V(c));if(we(ae(m&(1n<<160n)-1n,{size:20}))!==e.launcher)throw new i("Hookr frozen Root lock storage does not match the family owner contract.");let R=m>>160n&(1n<<40n)-1n,l=g(P),p=g(y);return{clock:"parent-block",parentBlock:u.toString(),familyUntilParentBlock:l.toString(),poolRulesUntilParentBlock:p.toString(),rootUntilParentBlock:R.toString(),currentlyLocked:u<l||u<p||u<R,feesCollectableDuringPrincipalLocks:!0}}export{he as a,ze as b,Me as c,io as d,be as e,qe as f,Ne as g,re as h,Q as i,J as j,ie as k,Te as l,Je as m};
@@ -1 +1 @@
1
- import{i as R,s as g}from"./XPFVT2EA.js";import{a as w}from"./5YS5V2LK.js";import{isDeepStrictEqual as b}from"node:util";import{isAddress as x}from"viem";var O=2592e3,v=1n<<128n,m=new Set(["order","offer","link","consent"]),y=new Set(["order","offer","consent"]),E=new Set(["order","offer","link"]),I=3600,S=1e11;function l(e){return new w(`Local signing guard: ${e}; nothing was signed.`)}var V=e=>m.has(e.class);function T(e,r){let t=new Map,n=(s,a,o)=>{let u=e[s];if(!u||o>8)throw l("typed-data types changed");for(let c of u){let f=c.type.replace(/(\[[0-9]*\])+$/,""),i=`${a}${c.name}${c.type===f?"":"[]"}`;e[f]?n(f,`${i}.`,o+1):t.set(i,c.type)}};return n(r,"",0),t}function N(e,r){let t=new Set,n=s=>{if(!(t.has(s)||!e[s])){t.add(s);for(let a of e[s])n(a.type.replace(/(\[[0-9]*\])+$/,""))}};return n(r),t}function A(e=[]){let r=new Set(e.map(n=>n.toLowerCase())),t=(n,s)=>{if(!(s>12)){if(typeof n=="string"){x(n,{strict:!1})&&r.add(n.toLowerCase());return}if(n&&typeof n=="object")for(let a of Object.values(n))t(a,s+1)}};return t(R,0),t(g,0),r}function j(e,r=A()){let t=[],n=(i,d)=>t.push(`${i} ${e.id}: ${d}`),s=Object.entries(e.fields),a=i=>s.filter(([,d])=>d.role===i),o=i=>s.filter(([,d])=>d.role==="derived"&&d.yields?.includes(i)).length;["order","cancel","link","offer","consent","auth","relayed"].includes(e.class)||n("R5","unknown signature class; link-accept is a display role only"),e.expiryBinding&&!["signed","program-link","auth-window","cancel-only"].includes(e.expiryBinding)&&n("R5","unknown expiry binding"),(!e.id||!/^[a-z0-9]+(?:[.-][a-z0-9]+)+$/.test(e.id))&&n("ID","id must be dotted lower-case"),(!e.tools.length||new Set(e.tools).size!==e.tools.length)&&n("ID","tools must be a non-empty unique list");let u=e.network==="testnet"?g.testnet.chainId:g.mainnet.chainId;if(e.encoding==="eip712"){let i=e.domain;i?(Object.hasOwn(i,"salt")&&n("R1","domain must not carry a salt"),i.name||n("R1","domain name is missing"),!i.version&&e.class!=="relayed"&&n("R1","domain version is missing"),i.chainId!==u&&n("R1",`domain chain must be ${u}`),i.verifyingContract?r.has(i.verifyingContract.toLowerCase())||n("R1","verifying contract is not a pinned address"):e.class!=="cancel"&&e.class!=="auth"&&n("R1","verifying contract is missing")):n("R1","EIP-712 spec has no domain")}else e.domain&&n("R1","only EIP-712 specs carry a domain");if(e.encoding==="eip191-packed-hash"){let i=a("pinned").map(([,d])=>d.value);i.some(d=>d===u||d===String(u))||n("R1","packed layout must pin the chain id"),i.some(d=>typeof d=="string"&&r.has(d.toLowerCase()))||n("R1","packed layout must pin the verifying contract")}let c=new Map,f=e.class==="relayed"&&!Object.keys(e.types).length;if(e.encoding==="eip712"&&!f){Object.hasOwn(e.types,"EIP712Domain")&&n("R2","types must never carry EIP712Domain");try{c=T(e.types,e.primaryType);let i=N(e.types,e.primaryType);for(let d of Object.keys(e.types))i.has(d)||n("R2",`type ${d} is not reachable from ${e.primaryType}`)}catch{n("R2",`types do not resolve from ${e.primaryType}`)}for(let i of c.keys())Object.hasOwn(e.fields,i)||n("R3",`message path ${i} has no role`);for(let[i]of s)c.has(i)||n("R3",`declared field ${i} is not in the typed struct`)}else e.encoding!=="eip712"&&Object.keys(e.types).length&&n("R2","only EIP-712 specs carry types");for(let[i,d]of s)(!d.meaning||d.meaning.length>160)&&n("R3",`field ${i} needs a plain-English meaning`);(e.class==="order"||e.class==="offer")&&!s.some(([,i])=>i.role==="amount"&&i.side==="out")&&!o("amount-out")&&n("R4",`${e.class} must show the most that can leave`);for(let[i,d]of s){if(d.role==="amount"||d.role==="fee"){let h=d.token;(x(h,{strict:!1})?r.has(h.toLowerCase()):e.fields[h]?.role==="token")||n("R4",`amount ${i} does not name a token field or a pinned token`)}c.get(i)==="bytes"&&d.role!=="pinned"&&d.role!=="derived"&&n("R4",`bytes field ${i} must be pinned or derived`)}if(e.maxLifetimeSeconds>0&&e.maxLifetimeSeconds<=O||n("R5","maxLifetimeSeconds must be within 30 days"),y.has(e.class)){let i=a("expiry").length+o("expiry");i!==1&&n("R5",`${e.class} needs exactly one expiry (found ${i})`),e.expiry&&n("R5","API-only expiry is not a signed expiry"),e.expiryBinding&&e.expiryBinding!=="signed"&&n("R5",`${e.class} requires signed expiry`)}if(e.expiryBinding==="program-link"&&e.class!=="link"&&n("R5","only link can use program-link"),e.class==="link"&&e.expiryBinding!=="program-link"&&a("expiry").length+o("expiry")!==1&&n("R5","link needs signed expiry or program-link binding"),e.expiryBinding==="auth-window"){let i=e.authWindow;(e.class!=="auth"||!i||!c.has(i.field)||!Number.isSafeInteger(i.maxAgeSeconds)||i.maxAgeSeconds<=0||i.maxAgeSeconds>e.maxLifetimeSeconds||!Number.isSafeInteger(i.maxFutureSeconds)||i.maxFutureSeconds<0||i.maxFutureSeconds>e.maxLifetimeSeconds)&&n("R5","auth-window needs a signed timestamp and pinned acceptance window")}else e.authWindow&&n("R5","authWindow requires auth-window binding");return e.expiryBinding==="cancel-only"&&(e.class!=="cancel"||!a("nonce").length&&!o("nonce")&&!e.revoke?.staysExecutableUntilExpiry)&&n("R5","cancel-only needs a single-use nonce or targeted non-revoking hide"),(e.class==="auth"||e.class==="cancel")&&(s.some(([,i])=>i.role==="amount"&&i.side==="out")||o("amount-out"))&&n("R4","auth and cancel cannot grant spending authority"),E.has(e.class)&&!(e.revoke?.onchainTool||e.revoke?.offchainSpec)&&!(e.revoke?.none&&e.maxLifetimeSeconds<=I)&&n("R6",`${e.class} needs a revocation path (only a one-shot approval of at most one hour may declare none)`),e.submit.by==="addon"&&(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(e.submit.host)||!/^\/[A-Za-z0-9/_.-]*$/.test(e.submit.path))&&n("R9","add-on submission needs a bare HTTPS host and a fixed path"),e.submit.by==="server-continuation"&&!e.submit.reason&&n("R9","server-continuation needs its recorded reason"),e.submit.by==="transaction"&&e.class!=="relayed"&&e.class!=="consent"&&n("R9","only relayed and consent signatures are consumed by a transaction"),(!/^[A-Za-z0-9 .'-]{1,40}$/.test(e.program)||!/^[A-Za-z0-9 .'-]{1,60}$/.test(e.purpose))&&n("R10","program and purpose must be short constant text"),m.has(e.class)&&!e.requireHuman&&!e.humanException&&n("C13",`${e.class} must require a human`),!m.has(e.class)&&e.humanException&&n("C13","only a value class can name a human exception"),e.relayedPaths&&e.class!=="relayed"&&n("ID","only relayed specs accept caller signatures"),e.enabled===!1&&!e.disabledReason&&n("ID","a disabled spec states why"),t}function z(e,r=A()){let t=e.filter(a=>a.enabled!==!1).flatMap(a=>j(a,r)),n=new Set,s=new Set;for(let a of e){n.has(a.id)&&t.push(`ID ${a.id}: duplicate spec id`),n.add(a.id);let o=C(a);s.has(o)&&t.push(`ID ${a.id}: another spec already covers ${o}`),s.add(o)}return t}function C(e){return`${e.network??"mainnet"}:${e.encoding}:${(e.domain?.verifyingContract??"-").toLowerCase()}:${e.primaryType}`}function k(e,r,t,n,s){let a=r.replace(/(\[[0-9]*\])+$/,"");if(a!==r){if(!Array.isArray(t))throw l(`message field ${n||r} is not declared`);for(let i of t)k(e,r.replace(/\[[0-9]*\]$/,""),i,`${n}[]`,s+1);return}let o=e[a];if(!o)return;if(s>8||!t||typeof t!="object"||Array.isArray(t))throw l(`message field ${n||r} is not declared`);let u=Object.keys(t),c=o.map(i=>i.name);if(u.find(i=>!c.includes(i))!==void 0)throw l(`an undeclared message field${n?` under ${n}`:""} is present`);for(let i of o){if(!Object.hasOwn(t,i.name))throw l(`message field ${n?`${n}.`:""}${i.name} is missing`);k(e,i.type,t[i.name],`${n?`${n}.`:""}${i.name}`,s+1)}}function W(e,r){if(e.encoding!=="eip712"||!e.domain)throw l("Oak has no signing contract for this request");if(!r||typeof r!="object"||!r.domain||typeof r.domain!="object")throw l("domain, chain or verifying contract is not the pinned one");let t=Object.fromEntries(Object.entries(e.domain).filter(([,n])=>n!==void 0));if(!b(Object.keys(r.domain).sort(),Object.keys(t).sort())||!b({...r.domain},t))throw l("domain, chain or verifying contract is not the pinned one");if(!r.types||typeof r.types!="object"||Object.hasOwn(r.types,"EIP712Domain")||!b(r.types,e.types)||r.primaryType!==e.primaryType)throw l("typed-data types changed");k(e.types,e.primaryType,r.message,"",0)}function p(e,r){let t=e;for(let n of r.split(".")){if(n.endsWith("[]")||!t||typeof t!="object"||Array.isArray(t))return;t=t[n]}return t}var $=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="bigint"?String(e):void 0;function D(e,r){let t={},n=s=>x(s,{strict:!1})?s:$(p(r,s));for(let[s,a]of Object.entries(e.fields)){let o=$(p(r,s));if(o!==void 0)switch(a.role){case"signer":t.signer=o;break;case"account":t.account=o;break;case"recipient":t.recipient=o;break;case"delegate":t.delegate=o;break;case"counterparty":t.counterparty=o;break;case"token":a.side==="out"?t.tokenOut=o:t.tokenIn=o;break;case"amount":a.side==="out"?(t.amountOut=o,t.tokenOut??=n(a.token)):(t.minAmountIn=o,t.tokenIn??=n(a.token));break;case"fee":(t.fees??=[]).push({token:n(a.token)??a.token,value:o});break;case"expiry":t.expiry=/^[0-9]+$/.test(o)?Number(o):Number.NaN;break;case"nonce":t.nonce=o;break;default:break}}return t}function L(e,r,t){let n=Math.min(e.maxLifetimeSeconds,O),s=y.has(e.class)||e.humanException?60:1;if(!Number.isSafeInteger(t)||t<0||!Number.isFinite(n)||n<=0||r===void 0||!Number.isSafeInteger(r)||r<=0||r>=S||r<t+s||r>t+n)throw l(`expiry is missing, past or beyond ${n>=86400?`${Math.floor(n/86400)} days`:`${Math.ceil(n/60)} minutes`}`)}function U(e,r,t,n){if(e.enabled===!1)throw l("Oak has no signing contract for this request");if(!Number.isSafeInteger(t)||t<0||t>=S)throw l("signing time is unavailable");if(e.expiryBinding==="auth-window"){let o=e.authWindow,u=o&&p(r,o.field),c=typeof u=="number"?u:typeof u=="string"&&/^[0-9]+$/.test(u)?Number(u):NaN;if(e.class!=="auth"||!o||!Number.isSafeInteger(c)||c<=0||c>=S||c<t-o.maxAgeSeconds||c>t+o.maxFutureSeconds)throw l("authentication time is outside the pinned window");return c+o.maxAgeSeconds}if(e.expiryBinding==="cancel-only"){if(e.class!=="cancel")throw l("Oak has no signing contract for this request");return n}if(e.expiryBinding==="program-link")throw l("program link authority is not configured");if(y.has(e.class)&&(e.expiry||e.expiryBinding&&e.expiryBinding!=="signed"))throw l("order expiry must be signed");let s=D(e,r).expiry??n,a=Object.values(e.fields).some(o=>o.role==="expiry"||o.role==="derived"&&o.yields?.includes("expiry"));if(y.has(e.class)&&!a)throw l("order expiry must be signed");return(a||m.has(e.class))&&L(e,s,t),s}function H(e){if(e===void 0||!/^[0-9]{1,78}$/.test(e))throw l("open-ended or out-of-range amount");let r=BigInt(e);if(r<=0n||r>=v)throw l("open-ended or out-of-range amount");return r}function J(e,r){return Object.entries(e.fields).map(([t,n])=>{let s=t.includes("[]")?"(each item, listed below)":p(r,t),a=typeof s=="object"&&s!==null?JSON.stringify(s):String(s);a.length>200&&(a=`${a.slice(0,200)}\u2026`);let o=JSON.stringify(a).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g,u=>`\\u${u.charCodeAt(0).toString(16).padStart(4,"0")}`);return`${t} = ${o} - ${n.meaning}`})}export{O as a,v as b,m as c,l as d,V as e,T as f,A as g,j as h,z as i,C as j,W as k,p as l,D as m,L as n,U as o,H as p,J as q};
1
+ import{i as R,s as g}from"./G6HCV67X.js";import{a as w}from"./5YS5V2LK.js";import{isDeepStrictEqual as b}from"node:util";import{isAddress as x}from"viem";var O=2592e3,v=1n<<128n,m=new Set(["order","offer","link","consent"]),y=new Set(["order","offer","consent"]),E=new Set(["order","offer","link"]),I=3600,S=1e11;function l(e){return new w(`Local signing guard: ${e}; nothing was signed.`)}var V=e=>m.has(e.class);function T(e,r){let t=new Map,n=(s,a,o)=>{let u=e[s];if(!u||o>8)throw l("typed-data types changed");for(let c of u){let f=c.type.replace(/(\[[0-9]*\])+$/,""),i=`${a}${c.name}${c.type===f?"":"[]"}`;e[f]?n(f,`${i}.`,o+1):t.set(i,c.type)}};return n(r,"",0),t}function N(e,r){let t=new Set,n=s=>{if(!(t.has(s)||!e[s])){t.add(s);for(let a of e[s])n(a.type.replace(/(\[[0-9]*\])+$/,""))}};return n(r),t}function A(e=[]){let r=new Set(e.map(n=>n.toLowerCase())),t=(n,s)=>{if(!(s>12)){if(typeof n=="string"){x(n,{strict:!1})&&r.add(n.toLowerCase());return}if(n&&typeof n=="object")for(let a of Object.values(n))t(a,s+1)}};return t(R,0),t(g,0),r}function j(e,r=A()){let t=[],n=(i,d)=>t.push(`${i} ${e.id}: ${d}`),s=Object.entries(e.fields),a=i=>s.filter(([,d])=>d.role===i),o=i=>s.filter(([,d])=>d.role==="derived"&&d.yields?.includes(i)).length;["order","cancel","link","offer","consent","auth","relayed"].includes(e.class)||n("R5","unknown signature class; link-accept is a display role only"),e.expiryBinding&&!["signed","program-link","auth-window","cancel-only"].includes(e.expiryBinding)&&n("R5","unknown expiry binding"),(!e.id||!/^[a-z0-9]+(?:[.-][a-z0-9]+)+$/.test(e.id))&&n("ID","id must be dotted lower-case"),(!e.tools.length||new Set(e.tools).size!==e.tools.length)&&n("ID","tools must be a non-empty unique list");let u=e.network==="testnet"?g.testnet.chainId:g.mainnet.chainId;if(e.encoding==="eip712"){let i=e.domain;i?(Object.hasOwn(i,"salt")&&n("R1","domain must not carry a salt"),i.name||n("R1","domain name is missing"),!i.version&&e.class!=="relayed"&&n("R1","domain version is missing"),i.chainId!==u&&n("R1",`domain chain must be ${u}`),i.verifyingContract?r.has(i.verifyingContract.toLowerCase())||n("R1","verifying contract is not a pinned address"):e.class!=="cancel"&&e.class!=="auth"&&n("R1","verifying contract is missing")):n("R1","EIP-712 spec has no domain")}else e.domain&&n("R1","only EIP-712 specs carry a domain");if(e.encoding==="eip191-packed-hash"){let i=a("pinned").map(([,d])=>d.value);i.some(d=>d===u||d===String(u))||n("R1","packed layout must pin the chain id"),i.some(d=>typeof d=="string"&&r.has(d.toLowerCase()))||n("R1","packed layout must pin the verifying contract")}let c=new Map,f=e.class==="relayed"&&!Object.keys(e.types).length;if(e.encoding==="eip712"&&!f){Object.hasOwn(e.types,"EIP712Domain")&&n("R2","types must never carry EIP712Domain");try{c=T(e.types,e.primaryType);let i=N(e.types,e.primaryType);for(let d of Object.keys(e.types))i.has(d)||n("R2",`type ${d} is not reachable from ${e.primaryType}`)}catch{n("R2",`types do not resolve from ${e.primaryType}`)}for(let i of c.keys())Object.hasOwn(e.fields,i)||n("R3",`message path ${i} has no role`);for(let[i]of s)c.has(i)||n("R3",`declared field ${i} is not in the typed struct`)}else e.encoding!=="eip712"&&Object.keys(e.types).length&&n("R2","only EIP-712 specs carry types");for(let[i,d]of s)(!d.meaning||d.meaning.length>160)&&n("R3",`field ${i} needs a plain-English meaning`);(e.class==="order"||e.class==="offer")&&!s.some(([,i])=>i.role==="amount"&&i.side==="out")&&!o("amount-out")&&n("R4",`${e.class} must show the most that can leave`);for(let[i,d]of s){if(d.role==="amount"||d.role==="fee"){let h=d.token;(x(h,{strict:!1})?r.has(h.toLowerCase()):e.fields[h]?.role==="token")||n("R4",`amount ${i} does not name a token field or a pinned token`)}c.get(i)==="bytes"&&d.role!=="pinned"&&d.role!=="derived"&&n("R4",`bytes field ${i} must be pinned or derived`)}if(e.maxLifetimeSeconds>0&&e.maxLifetimeSeconds<=O||n("R5","maxLifetimeSeconds must be within 30 days"),y.has(e.class)){let i=a("expiry").length+o("expiry");i!==1&&n("R5",`${e.class} needs exactly one expiry (found ${i})`),e.expiry&&n("R5","API-only expiry is not a signed expiry"),e.expiryBinding&&e.expiryBinding!=="signed"&&n("R5",`${e.class} requires signed expiry`)}if(e.expiryBinding==="program-link"&&e.class!=="link"&&n("R5","only link can use program-link"),e.class==="link"&&e.expiryBinding!=="program-link"&&a("expiry").length+o("expiry")!==1&&n("R5","link needs signed expiry or program-link binding"),e.expiryBinding==="auth-window"){let i=e.authWindow;(e.class!=="auth"||!i||!c.has(i.field)||!Number.isSafeInteger(i.maxAgeSeconds)||i.maxAgeSeconds<=0||i.maxAgeSeconds>e.maxLifetimeSeconds||!Number.isSafeInteger(i.maxFutureSeconds)||i.maxFutureSeconds<0||i.maxFutureSeconds>e.maxLifetimeSeconds)&&n("R5","auth-window needs a signed timestamp and pinned acceptance window")}else e.authWindow&&n("R5","authWindow requires auth-window binding");return e.expiryBinding==="cancel-only"&&(e.class!=="cancel"||!a("nonce").length&&!o("nonce")&&!e.revoke?.staysExecutableUntilExpiry)&&n("R5","cancel-only needs a single-use nonce or targeted non-revoking hide"),(e.class==="auth"||e.class==="cancel")&&(s.some(([,i])=>i.role==="amount"&&i.side==="out")||o("amount-out"))&&n("R4","auth and cancel cannot grant spending authority"),E.has(e.class)&&!(e.revoke?.onchainTool||e.revoke?.offchainSpec)&&!(e.revoke?.none&&e.maxLifetimeSeconds<=I)&&n("R6",`${e.class} needs a revocation path (only a one-shot approval of at most one hour may declare none)`),e.submit.by==="addon"&&(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(e.submit.host)||!/^\/[A-Za-z0-9/_.-]*$/.test(e.submit.path))&&n("R9","add-on submission needs a bare HTTPS host and a fixed path"),e.submit.by==="server-continuation"&&!e.submit.reason&&n("R9","server-continuation needs its recorded reason"),e.submit.by==="transaction"&&e.class!=="relayed"&&e.class!=="consent"&&n("R9","only relayed and consent signatures are consumed by a transaction"),(!/^[A-Za-z0-9 .'-]{1,40}$/.test(e.program)||!/^[A-Za-z0-9 .'-]{1,60}$/.test(e.purpose))&&n("R10","program and purpose must be short constant text"),m.has(e.class)&&!e.requireHuman&&!e.humanException&&n("C13",`${e.class} must require a human`),!m.has(e.class)&&e.humanException&&n("C13","only a value class can name a human exception"),e.relayedPaths&&e.class!=="relayed"&&n("ID","only relayed specs accept caller signatures"),e.enabled===!1&&!e.disabledReason&&n("ID","a disabled spec states why"),t}function z(e,r=A()){let t=e.filter(a=>a.enabled!==!1).flatMap(a=>j(a,r)),n=new Set,s=new Set;for(let a of e){n.has(a.id)&&t.push(`ID ${a.id}: duplicate spec id`),n.add(a.id);let o=C(a);s.has(o)&&t.push(`ID ${a.id}: another spec already covers ${o}`),s.add(o)}return t}function C(e){return`${e.network??"mainnet"}:${e.encoding}:${(e.domain?.verifyingContract??"-").toLowerCase()}:${e.primaryType}`}function k(e,r,t,n,s){let a=r.replace(/(\[[0-9]*\])+$/,"");if(a!==r){if(!Array.isArray(t))throw l(`message field ${n||r} is not declared`);for(let i of t)k(e,r.replace(/\[[0-9]*\]$/,""),i,`${n}[]`,s+1);return}let o=e[a];if(!o)return;if(s>8||!t||typeof t!="object"||Array.isArray(t))throw l(`message field ${n||r} is not declared`);let u=Object.keys(t),c=o.map(i=>i.name);if(u.find(i=>!c.includes(i))!==void 0)throw l(`an undeclared message field${n?` under ${n}`:""} is present`);for(let i of o){if(!Object.hasOwn(t,i.name))throw l(`message field ${n?`${n}.`:""}${i.name} is missing`);k(e,i.type,t[i.name],`${n?`${n}.`:""}${i.name}`,s+1)}}function W(e,r){if(e.encoding!=="eip712"||!e.domain)throw l("Oak has no signing contract for this request");if(!r||typeof r!="object"||!r.domain||typeof r.domain!="object")throw l("domain, chain or verifying contract is not the pinned one");let t=Object.fromEntries(Object.entries(e.domain).filter(([,n])=>n!==void 0));if(!b(Object.keys(r.domain).sort(),Object.keys(t).sort())||!b({...r.domain},t))throw l("domain, chain or verifying contract is not the pinned one");if(!r.types||typeof r.types!="object"||Object.hasOwn(r.types,"EIP712Domain")||!b(r.types,e.types)||r.primaryType!==e.primaryType)throw l("typed-data types changed");k(e.types,e.primaryType,r.message,"",0)}function p(e,r){let t=e;for(let n of r.split(".")){if(n.endsWith("[]")||!t||typeof t!="object"||Array.isArray(t))return;t=t[n]}return t}var $=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="bigint"?String(e):void 0;function D(e,r){let t={},n=s=>x(s,{strict:!1})?s:$(p(r,s));for(let[s,a]of Object.entries(e.fields)){let o=$(p(r,s));if(o!==void 0)switch(a.role){case"signer":t.signer=o;break;case"account":t.account=o;break;case"recipient":t.recipient=o;break;case"delegate":t.delegate=o;break;case"counterparty":t.counterparty=o;break;case"token":a.side==="out"?t.tokenOut=o:t.tokenIn=o;break;case"amount":a.side==="out"?(t.amountOut=o,t.tokenOut??=n(a.token)):(t.minAmountIn=o,t.tokenIn??=n(a.token));break;case"fee":(t.fees??=[]).push({token:n(a.token)??a.token,value:o});break;case"expiry":t.expiry=/^[0-9]+$/.test(o)?Number(o):Number.NaN;break;case"nonce":t.nonce=o;break;default:break}}return t}function L(e,r,t){let n=Math.min(e.maxLifetimeSeconds,O),s=y.has(e.class)||e.humanException?60:1;if(!Number.isSafeInteger(t)||t<0||!Number.isFinite(n)||n<=0||r===void 0||!Number.isSafeInteger(r)||r<=0||r>=S||r<t+s||r>t+n)throw l(`expiry is missing, past or beyond ${n>=86400?`${Math.floor(n/86400)} days`:`${Math.ceil(n/60)} minutes`}`)}function U(e,r,t,n){if(e.enabled===!1)throw l("Oak has no signing contract for this request");if(!Number.isSafeInteger(t)||t<0||t>=S)throw l("signing time is unavailable");if(e.expiryBinding==="auth-window"){let o=e.authWindow,u=o&&p(r,o.field),c=typeof u=="number"?u:typeof u=="string"&&/^[0-9]+$/.test(u)?Number(u):NaN;if(e.class!=="auth"||!o||!Number.isSafeInteger(c)||c<=0||c>=S||c<t-o.maxAgeSeconds||c>t+o.maxFutureSeconds)throw l("authentication time is outside the pinned window");return c+o.maxAgeSeconds}if(e.expiryBinding==="cancel-only"){if(e.class!=="cancel")throw l("Oak has no signing contract for this request");return n}if(e.expiryBinding==="program-link")throw l("program link authority is not configured");if(y.has(e.class)&&(e.expiry||e.expiryBinding&&e.expiryBinding!=="signed"))throw l("order expiry must be signed");let s=D(e,r).expiry??n,a=Object.values(e.fields).some(o=>o.role==="expiry"||o.role==="derived"&&o.yields?.includes("expiry"));if(y.has(e.class)&&!a)throw l("order expiry must be signed");return(a||m.has(e.class))&&L(e,s,t),s}function H(e){if(e===void 0||!/^[0-9]{1,78}$/.test(e))throw l("open-ended or out-of-range amount");let r=BigInt(e);if(r<=0n||r>=v)throw l("open-ended or out-of-range amount");return r}function J(e,r){return Object.entries(e.fields).map(([t,n])=>{let s=t.includes("[]")?"(each item, listed below)":p(r,t),a=typeof s=="object"&&s!==null?JSON.stringify(s):String(s);a.length>200&&(a=`${a.slice(0,200)}\u2026`);let o=JSON.stringify(a).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g,u=>`\\u${u.charCodeAt(0).toString(16).padStart(4,"0")}`);return`${t} = ${o} - ${n.meaning}`})}export{O as a,v as b,m as c,l as d,V as e,T as f,A as g,j as h,z as i,C as j,W as k,p as l,D as m,L as n,U as o,H as p,J as q};