@oakagentkit/core 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/build/dist/api/deployments.d.ts +26 -0
  2. package/build/dist/api/deployments.js +1 -0
  3. package/build/dist/api/history.js +1 -1
  4. package/build/dist/api/modules/beefy/clm.js +1 -1
  5. package/build/dist/api/modules/beefy/guard.js +1 -1
  6. package/build/dist/api/modules/beefy/index.js +1 -1
  7. package/build/dist/api/modules/beefy/liquidity.js +1 -1
  8. package/build/dist/api/modules/clanker/index.js +1 -1
  9. package/build/dist/api/modules/grove/index.js +1 -1
  10. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  11. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  12. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  13. package/build/dist/api/modules/hoodlock/index.js +1 -1
  14. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  15. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  16. package/build/dist/api/modules/hoodlock/public.js +1 -1
  17. package/build/dist/api/modules/hookr/actions.js +1 -1
  18. package/build/dist/api/modules/hookr/addons.js +1 -1
  19. package/build/dist/api/modules/hookr/contracts.js +1 -1
  20. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  21. package/build/dist/api/modules/hookr/discovery.js +1 -1
  22. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  23. package/build/dist/api/modules/hookr/index.js +1 -1
  24. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  25. package/build/dist/api/modules/hookr/relay.js +1 -1
  26. package/build/dist/api/modules/kyberswap/index.js +1 -1
  27. package/build/dist/api/modules/kyberswap/source-pools.d.ts +22 -3
  28. package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
  29. package/build/dist/api/modules/longbow/administration.js +1 -1
  30. package/build/dist/api/modules/longbow/fixed.js +1 -1
  31. package/build/dist/api/modules/longbow/index.js +1 -1
  32. package/build/dist/api/modules/meridian/index.js +1 -1
  33. package/build/dist/api/modules/meridian/rfq.js +1 -1
  34. package/build/dist/api/modules/morpho/bundles.js +1 -1
  35. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  36. package/build/dist/api/modules/morpho/index.js +1 -1
  37. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  38. package/build/dist/api/modules/morpho/midnight.js +1 -1
  39. package/build/dist/api/modules/morpho/protocol.js +1 -1
  40. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  41. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  42. package/build/dist/api/modules/netnet/card-read.js +1 -1
  43. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  44. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  45. package/build/dist/api/modules/netnet/financial.js +1 -1
  46. package/build/dist/api/modules/netnet/index.js +1 -1
  47. package/build/dist/api/modules/orbio/index.js +1 -1
  48. package/build/dist/api/modules/pons/claim.js +1 -1
  49. package/build/dist/api/modules/pons/index.js +1 -1
  50. package/build/dist/api/modules/pons/launch-status.js +1 -1
  51. package/build/dist/api/modules/pons/reads.js +1 -1
  52. package/build/dist/api/modules/pons/trade.js +1 -1
  53. package/build/dist/api/modules/poolstrade/index.js +1 -1
  54. package/build/dist/api/modules/priors/index.js +1 -1
  55. package/build/dist/api/modules/relay/discovery.js +1 -1
  56. package/build/dist/api/modules/relay/inbound.js +1 -1
  57. package/build/dist/api/modules/relay/index.js +1 -1
  58. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  59. package/build/dist/api/modules/steakhouse/index.js +1 -1
  60. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  61. package/build/dist/api/modules/steakhouse/management.js +1 -1
  62. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  63. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  64. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  65. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  66. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  67. package/build/dist/api/modules/tickerspring/index.js +1 -1
  68. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  69. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  70. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  71. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  72. package/build/dist/api/modules/tickerspring/research.js +1 -1
  73. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  74. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  75. package/build/dist/api/modules/uniswap/auction.js +1 -1
  76. package/build/dist/api/modules/uniswap/batch.js +1 -1
  77. package/build/dist/api/modules/uniswap/common.js +1 -1
  78. package/build/dist/api/modules/uniswap/fees.js +1 -1
  79. package/build/dist/api/modules/uniswap/index.js +1 -1
  80. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  81. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  82. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  83. package/build/dist/api/modules/uniswap/pools.js +1 -1
  84. package/build/dist/api/modules/uniswap/position.js +1 -1
  85. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  86. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  87. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  88. package/build/dist/api/modules/uniswap/trade.js +1 -1
  89. package/build/dist/api/modules/uniswap/v2.js +1 -1
  90. package/build/dist/api/modules/uniswap/v3.js +1 -1
  91. package/build/dist/api/modules/uniswap/v4.js +1 -1
  92. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  93. package/build/dist/api/modules/velora/claims.js +1 -1
  94. package/build/dist/api/modules/velora/index.js +1 -1
  95. package/build/dist/api/prices.js +1 -1
  96. package/build/dist/api/routes.d.ts +2 -0
  97. package/build/dist/api/routes.js +1 -1
  98. package/build/dist/api/send.js +1 -1
  99. package/build/dist/api/signing-registry.js +1 -1
  100. package/build/dist/api/simulate.js +1 -1
  101. package/build/dist/api/swap.js +1 -1
  102. package/build/dist/api/tokens.js +1 -1
  103. package/build/dist/chunks/{QOY4AANB.js → 2SNQWKHA.js} +1 -1
  104. package/build/dist/chunks/{FYTF2QMS.js → 3ACEWCKZ.js} +1 -1
  105. package/build/dist/chunks/{HZUWK5B2.js → 46ZA2R5L.js} +1 -1
  106. package/build/dist/chunks/{W6G2QGYF.js → 4IPW5WZ4.js} +1 -1
  107. package/build/dist/chunks/{JRZLKIYB.js → 55NX776C.js} +1 -1
  108. package/build/dist/chunks/{2EGFALNH.js → 5FTSKYQH.js} +1 -1
  109. package/build/dist/chunks/{OJP7Y4AM.js → 5HW6JKME.js} +1 -1
  110. package/build/dist/chunks/{ZL3KVABO.js → 5VXNQFYJ.js} +1 -1
  111. package/build/dist/chunks/{ITIIHCZK.js → 64AF7ECA.js} +1 -1
  112. package/build/dist/chunks/{FLXID6I3.js → 6LLOTPH2.js} +1 -1
  113. package/build/dist/chunks/{CXMC3T6B.js → 6PU2CMQZ.js} +1 -1
  114. package/build/dist/chunks/{E2IVNGLC.js → 7BTELNNI.js} +1 -1
  115. package/build/dist/chunks/{C5LR6F4B.js → 7T4BYFD4.js} +1 -1
  116. package/build/dist/chunks/{6SB3FB3P.js → 7Z5IM2QZ.js} +1 -1
  117. package/build/dist/chunks/{JOMK32QW.js → A25P24G2.js} +1 -1
  118. package/build/dist/chunks/{FL3EF72E.js → ANQ43XJA.js} +1 -1
  119. package/build/dist/chunks/{B72Q2EQ2.js → BFVLBENV.js} +1 -1
  120. package/build/dist/chunks/{QH3AL3UN.js → BV3AHLH5.js} +1 -1
  121. package/build/dist/chunks/{EKGHKEKV.js → BXN3MDS4.js} +1 -1
  122. package/build/dist/chunks/CAU44UWP.js +1 -0
  123. package/build/dist/chunks/{HACP2Q6D.js → D6VP3N27.js} +2 -2
  124. package/build/dist/chunks/{37QNUNED.js → DLIOZCEG.js} +1 -1
  125. package/build/dist/chunks/EA6IYKIB.js +1 -0
  126. package/build/dist/chunks/{SYZ55RCX.js → EYYUWFUR.js} +1 -1
  127. package/build/dist/chunks/{HF2AGJZC.js → FSPNOVKB.js} +1 -1
  128. package/build/dist/chunks/G4PDM3MX.js +1 -0
  129. package/build/dist/chunks/{ZPNGV34U.js → GHDDVBPK.js} +1 -1
  130. package/build/dist/chunks/{OK3TQFXZ.js → GSI5COTD.js} +1 -1
  131. package/build/dist/chunks/{CAYBSVA6.js → HRG2VVPY.js} +1 -1
  132. package/build/dist/chunks/{MWWYIFXJ.js → ITV52TIE.js} +1 -1
  133. package/build/dist/chunks/{4CDR7F4I.js → IUXOUKQN.js} +1 -1
  134. package/build/dist/chunks/{5H3MQWH7.js → JC4SYMBV.js} +1 -1
  135. package/build/dist/chunks/{KEPQXFHU.js → JREVERSC.js} +1 -1
  136. package/build/dist/chunks/{NUWL6TJM.js → K463HFGC.js} +1 -1
  137. package/build/dist/chunks/{VCWDJQDE.js → KQFDLDHL.js} +1 -1
  138. package/build/dist/chunks/{LFKSXD3S.js → LI7FYINH.js} +1 -1
  139. package/build/dist/chunks/{4X6JEMSF.js → N6RL3SUZ.js} +1 -1
  140. package/build/dist/chunks/{E7ASOYQI.js → NBRMUFJP.js} +1 -1
  141. package/build/dist/chunks/{UEYFMXV3.js → NIOBE2LK.js} +1 -1
  142. package/build/dist/chunks/NMFVXBTL.js +1 -0
  143. package/build/dist/chunks/{REGJY5RC.js → NO57NGRV.js} +1 -1
  144. package/build/dist/chunks/{SEW7UP5U.js → O5SU2I3G.js} +1 -1
  145. package/build/dist/chunks/{P6ELT4ZV.js → PJ65ZOQ7.js} +1 -1
  146. package/build/dist/chunks/{B7V7AA5A.js → QCD33HMD.js} +1 -1
  147. package/build/dist/chunks/{SS7U3CMZ.js → QQWF6A4P.js} +1 -1
  148. package/build/dist/chunks/{NNZ4SZZ4.js → QZM7CWZW.js} +1 -1
  149. package/build/dist/chunks/{HYIEQG4X.js → QZTUMSQY.js} +1 -1
  150. package/build/dist/chunks/{JVTVOK6P.js → R7D256HG.js} +1 -1
  151. package/build/dist/chunks/{Z4LJ2GTX.js → RTBOMWCB.js} +1 -1
  152. package/build/dist/chunks/{EHVPRQHS.js → SDICP7BT.js} +1 -1
  153. package/build/dist/chunks/{L2MTPRU7.js → T3NPRRTY.js} +1 -1
  154. package/build/dist/chunks/{BQLLTY4L.js → TNRDCBGO.js} +1 -1
  155. package/build/dist/chunks/{IKP3Z3RX.js → U3FMCX3L.js} +1 -1
  156. package/build/dist/chunks/{WHT45EFX.js → UIIJWIR6.js} +1 -1
  157. package/build/dist/chunks/{K2LWX3PZ.js → UMK564HS.js} +1 -1
  158. package/build/dist/chunks/{AIWZGIZ6.js → UPPYXY74.js} +1 -1
  159. package/build/dist/chunks/{XCFA73P2.js → VJ3W2V3B.js} +1 -1
  160. package/build/dist/chunks/{RNEMTLQG.js → VY3P34PY.js} +1 -1
  161. package/build/dist/chunks/{2LM5C7FQ.js → WDGPCPQJ.js} +1 -1
  162. package/build/dist/chunks/{PHXWBC4O.js → XKRWJCYE.js} +1 -1
  163. package/build/dist/chunks/{E2Q5IA67.js → Y2IWPNEW.js} +1 -1
  164. package/build/dist/chunks/{YONRUWN7.js → ZCGVBK5K.js} +1 -1
  165. package/build/dist/chunks/{BBQVTEYB.js → ZGXNTWYG.js} +1 -1
  166. package/build/dist/chunks/{CS55ERS3.js → ZYR5LSVB.js} +1 -1
  167. package/package.json +1 -1
  168. package/build/dist/chunks/2O6A6WEX.js +0 -1
  169. package/build/dist/chunks/3Z3U4YPA.js +0 -1
  170. package/build/dist/chunks/EAEQOS7Y.js +0 -1
  171. package/build/dist/chunks/ZQI7B2Z7.js +0 -1
@@ -1 +1 @@
1
- import{b as pe,c as De}from"./SQ5BNSXR.js";import{c as Te,d as a,r as xe}from"./53N7PNJH.js";import{o as ce}from"./EAEQOS7Y.js";import{a as M}from"./XCFA73P2.js";import{a as ve}from"./6IM6A5VA.js";import{a as te}from"./UWOFA6GV.js";import{c as H,j as Ce}from"./73N3TOJL.js";import{a as ke}from"./RETS2ZEK.js";import{a as R,i as qe}from"./XPFVT2EA.js";import{a as e}from"./5YS5V2LK.js";import{decodeFunctionData as Ee,erc20Abi as Ne}from"viem";var je="https://api.relay.link",q="0x0000000000000000000000000000000000000000",Le=60,Se=30,n=qe[R].relay.depository.address.toLowerCase(),ne="0x59916da825d2d2ec1bf878d71c88826f6633ecca",Oe=new Map([[1,{chainId:"ethereum",depository:n}],[10,{chainId:"optimism",depository:n}],[25,{chainId:"cronos",depository:ne}],[56,{chainId:"bnb",depository:n}],[100,{chainId:"gnosis",depository:n}],[130,{chainId:"unichain",depository:n}],[137,{chainId:"polygon",depository:n}],[143,{chainId:"monad",depository:n}],[146,{chainId:"sonic",depository:n}],[169,{chainId:"manta",depository:n}],[196,{chainId:"xlayer",depository:n}],[288,{chainId:"boba",depository:n}],[324,{chainId:"zksync",depository:n}],[360,{chainId:"shape",depository:n}],[480,{chainId:"worldchain",depository:n}],[747,{chainId:"flow",depository:n}],[988,{chainId:"stable",depository:n}],[999,{chainId:"hyperevm",depository:n}],[1088,{chainId:"metis",depository:ne}],[1135,{chainId:"lisk",depository:n}],[1868,{chainId:"soneium",depository:n}],[2020,{chainId:"ronin",depository:n}],[2741,{chainId:"abstract",depository:n}],[2818,{chainId:"morph",depository:n}],[4217,{chainId:"tempo",depository:n}],[4326,{chainId:"megaeth",depository:n}],[5e3,{chainId:"mantle",depository:ne}],[5031,{chainId:"somnia",depository:n}],[5042,{chainId:"arc",depository:n}],[8453,{chainId:"base",depository:n}],[9745,{chainId:"plasma",depository:n}],[33139,{chainId:"apechain",depository:n}],[34443,{chainId:"mode",depository:n}],[42018,{chainId:"mythos",depository:n}],[42161,{chainId:"arbitrum",depository:n}],[42220,{chainId:"celo",depository:n}],[43114,{chainId:"avalanche",depository:n}],[48900,{chainId:"zircuit",depository:n}],[57073,{chainId:"ink",depository:n}],[59144,{chainId:"linea",depository:ne}],[60808,{chainId:"bob",depository:n}],[80094,{chainId:"berachain",depository:n}],[97477,{chainId:"doma",depository:n}],[98866,{chainId:"plume",depository:n}],[534352,{chainId:"scroll",depository:n}],[685689,{chainId:"gensyn",depository:n}],[747474,{chainId:"katana",depository:n}],[5064014,{chainId:"ethereal",depository:n}],[7777777,{chainId:"zora",depository:n}]]);function nt(t){return Oe.get(t)?.depository}function F(t){return Ce(t,"Provide a token or wallet address.")}function I(t){let o=F(t);return o===M?q:o}function f(t,o){return F(t)===F(o)}function l(t){if(typeof t!="string")throw new e("Provide a decimal base-unit amount string.");return ke(t),t}function oe(t){let o=l(t);if(BigInt(o)<=0n)throw new e("Provide a positive base-unit amount.");return o}function ze(t){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new e("Provide a positive integer origin chain ID.");return t}function Pe(t,o){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new e(`${o} is missing or invalid.`);return t}async function G(t,o,c,i,p){let r=a(c);if(r.chainId!==i||I(r.address)!==p||typeof r.symbol!="string"||!/^[A-Za-z0-9._-]{1,32}$/.test(r.symbol))throw new e("Relay quote token metadata does not match the requested chain and address.");if(p===q){if(r.decimals!==18)throw new e("Native token decimals must be 18.");return{address:M,chainId:i,symbol:r.symbol,decimals:18}}let g=`${i}:${p}`,m=o.get(g);if(m===void 0){let d=await t.clientFor(i).readContract({address:p,abi:Ne,functionName:"decimals"}),w=typeof d=="bigint"?Number(d):d;if(typeof w!="number"||!Number.isInteger(w)||w<0||w>255)throw new e("Could not read valid ERC-20 decimals() on-chain.");m=w,o.set(g,m)}return{address:p,chainId:i,symbol:r.symbol,decimals:m}}async function Ke(t,o,c,i,p,r,g){if(c.swap===void 0)return[];let m=a(c.swap),d=a(m.from);if(d.chainId!==p)throw new e("The swap prerequisite token must be on the origin chain.");let w=await G(t,o,d,p,I(d.address)),j=r===q?M:r;if(f(w.address,j))throw new e("The swap prerequisite must use a different input token.");let me=oe(m.amountIn),y=m.slippageBps;if(y!==void 0&&(typeof y!="number"||!Number.isInteger(y)||y<0||y>1e4))throw new e("Provide swap slippage in basis points from 0 to 10000.");let E=await t.quoteSwap({from:w.address,to:j,amountIn:me,...y===void 0?{}:{slippageBps:y}},i);if(BigInt(l(E.expiresAt))<=BigInt(Math.floor(Date.now()/1e3)))throw new e("The swap prerequisite quote expired. Request a fresh quote.");if(BigInt(l(E.minAmountOut))<BigInt(g))throw new e("The swap prerequisite minimum cannot cover the bridge amount.");let k=await t.buildSwap(E.quoteId,i);if(!("txs"in k)||!k.txs.length)throw new e("The swap prerequisite must return unsigned transactions.");if(k.txs.some(S=>S.chainId!==p))throw new e("The injected swap coordinator does not support this origin chain.");return k.txs.map(S=>t.unsignedTx(S))}async function Ue(t,o,c){ve(c);let i=ze(o.originChainId);if(i===R)throw new e("Inbound bridging requires an origin chain other than 4663.");let p=Oe.get(i);if(!p)throw new e("Relay inbound does not support this origin chain.");if(o.destinationChainId!==void 0&&o.destinationChainId!==R)throw new e("Inbound bridge destination must be chain 4663.");let r=I(o.originCurrency??M),g=I(o.destinationCurrency??M),m=F(o.recipient??c),d=oe(o.amount),w=o.minAmountOut===void 0?void 0:l(o.minAmountOut),j=o.slippageBps===void 0?pe:o.slippageBps;if(ce("0",j),await t.clientFor(i).getChainId()!==i)throw new e("The RPC chain does not match the inbound origin chain.");let y=new Map,E=await Ke(t,y,o,c,i,r,d),k,S=process.env.OAK_RELAY_API_KEY?.trim();if(!S)throw new e("Configure OAK_RELAY_API_KEY on the server: Relay quote/v2 requires a valid API key since October 2, 2026. Status and chain reads remain available without it.");try{let s=await t.http(`${je}/quote/v2`,{method:"POST",headers:{"content-type":"application/json","user-agent":"oak-core/0.1.0","x-api-key":S},body:JSON.stringify({user:c,recipient:m,originChainId:i,destinationChainId:R,originCurrency:r,destinationCurrency:g,amount:d,tradeType:"EXACT_INPUT",...r===q?{}:{explicitDeposit:!0}})});if(!s.ok)throw new Error("Relay HTTP failure.");k=await s.json()}catch{throw new e("Relay quote request failed. Please try again.")}let b=a(k);if(typeof b.requestId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(b.requestId))throw new e("Relay returned an invalid request ID.");let P=b.requestId,he=`/intents/status/v3?requestId=${P}`,L=a(b.details);if(!f(L.sender,c)||!f(L.recipient,m))throw new e("Relay quote sender or recipient does not match the request.");let ye=a(L.currencyIn),ie=a(L.currencyOut),N=await G(t,y,ye.currency,i,r),O=await G(t,y,ie.currency,R,g);if(l(ye.amount)!==d)throw new e("Relay quote input amount does not match the request.");let _=oe(ie.amount),C=oe(ie.minimumAmount);if(BigInt(C)>BigInt(_))throw new e("Relay quote minimum output exceeds the expected output.");if(w!==void 0){if(C!==w)throw new e("Relay order minimum must exactly match minAmountOut. Request a new quote.")}else{let s=ce(_,j);if(BigInt(C)<BigInt(s))throw De(_,C)}let le=a(a(b.fees).relayer),fe=a(le.currency),Q=await G(t,y,fe,i,I(fe.address)),we={token:Q,amount:l(le.amount)},Ie=a(L.refundCurrency),_e=a(Ie.currency),z=await G(t,y,_e,i,r),re=l(Ie.amount),K=a(a(b.protocol).v2);if(typeof K.orderId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(K.orderId))throw new e("Relay returned an invalid order ID.");let V=K.orderId.toLowerCase(),W=a(K.paymentDetails),$=F(W.depository);if(W.chainId!==p.chainId||$!==p.depository||I(W.currency)!==r||l(W.amount)!==d)throw new e("Relay payment details do not match the origin chain depository and input.");let J=a(K.orderData),v=a(J.output);if(v.chainId!=="robinhood"||!Array.isArray(v.calls)||v.calls.length!==0||!Array.isArray(v.payments)||v.payments.length!==1)throw new e("Relay order output does not match destination chain 4663.");let X=a(v.payments[0]);if(!f(X.recipient,m)||I(X.currency)!==g||l(X.minimumAmount)!==C||l(X.expectedAmount)!==_)throw new e("Relay order output payment does not match the quoted recipient and amounts.");let se=Pe(v.deadline,"Relay order output deadline");if(!Array.isArray(J.inputs)||!J.inputs.length)throw new e("Relay order has no inputs.");let Z=[],ae=[];for(let s of J.inputs){let u=a(s),x=a(u.payment);if(x.chainId!==p.chainId||I(x.currency)!==r||l(x.amount)!==d||!Array.isArray(u.refunds)||!u.refunds.length)throw new e("Relay order input does not match the quoted input.");for(let D of u.refunds){let h=a(D);if(!f(h.recipient,c))throw new e("Relay refund recipient does not match the agent wallet. Request a new quote.");if(Z.push(Pe(h.deadline,"Relay order refund deadline")),ae.push(l(h.minimumAmount)),!(h.chainId===p.chainId?f(h.recipient,c)&&I(h.currency)===r:h.chainId==="robinhood"&&I(h.currency)===g))throw new e("Relay order refund terms do not match the sender or recipient.")}}let ge=Math.min(se,...Z),U=0,be=()=>{let s=Math.floor(Date.now()/1e3),u=U||s+Le;if(ge-s<=Se)throw new e("Relay order deadline is expired or too soon to sign safely. Request a new quote.");if(U=Math.min(u,ge-Se),U<=s)throw new e("Relay quote expired before signing. Request a new quote.")};if(be(),!Array.isArray(b.steps)||!b.steps.length)throw new e("Relay returned no origin transactions.");let T=[];for(let s of b.steps){let u=a(s);if(u.kind!=="transaction"||u.requestId!==P||!Array.isArray(u.items)||!u.items.length)throw new e("Relay returned an unsupported origin step.");for(let x of u.items){let D=a(x),h=a(D.data),ue=a(D.check);if(D.status!=="incomplete"||h.chainId!==i||!f(h.from,c))throw new e("Relay transaction does not match the origin chain and sender.");if(ue.method!=="GET"||ue.endpoint!==he)throw new e("Relay status endpoint does not match the request ID.");T.push(t.unsignedTx({to:F(h.to),data:h.data,value:l(h.value),chainId:i,description:`Relay inbound deposit for request ${P}; destination chain 4663.`}))}}if(!T.length)throw new e("Relay returned no origin transactions.");if(r===q&&T.length!==1)throw new e("Relay native deposit must be a single depositNative transaction.");if(r!==q&&T.length>2)throw new e("Relay ERC-20 deposit allows at most one exact-amount approval before depositErc20.");for(let s of T.slice(0,-1)){if(!s.data.toLowerCase().startsWith("0x095ea7b3"))throw new e("Relay returned an unsupported prerequisite transaction.");let u=Ee({abi:Ne,data:s.data});if(u.functionName!=="approve")throw new e("Relay returned an invalid approval.");let[x,D]=u.args;if(r===q||!f(s.to,r)||!f(x,$)||D!==BigInt(d)||s.value!=="0")throw new e("Relay approval must authorize the exact input amount for the origin depository.");s.description=`Approve exactly ${t.formatAmount(d,N.decimals)} ${N.symbol} (${d} base units of ${r}) for ${$} on chain ${i}.`}let B=T[T.length-1],Y=r===q,ee=Y?"depositNative":"depositErc20",Ae=Y?"depositNative(address,bytes32)":"depositErc20(address,address,uint256,bytes32)";if(!f(B.to,$)||B.value!==(Y?d:"0")||!(Y?/^0x[0-9a-fA-F]{136}$/:/^0x[0-9a-fA-F]{264}$/).test(B.data))throw new e(`Relay deposit transaction does not target the origin depository with ${ee} calldata.`);let A;try{A=Ee({abi:Te,data:B.data})}catch{throw new e(`Relay deposit transaction must call ${Ae}.`)}if(A.functionName!==ee)throw new e(`Relay deposit transaction must call ${Ae}.`);let Be=A.args[0],Me=A.functionName==="depositErc20"?A.args[3]:A.args[1];if(A.functionName==="depositErc20"&&(!f(A.args[1],r)||A.args[2]!==BigInt(d)))throw new e("Relay depositErc20 token or amount does not match the quoted input.");if(!f(Be,c)||Me.toLowerCase()!==V)throw new e(`Relay ${ee} depositor or orderId does not match the wallet and quoted protocol.v2.orderId.`);B.description=`Relay inbound ${ee} for order ${V} (request ${P}); destination chain 4663.`;let de=Y?[]:await xe(t,r,$,d,i,c);for(let[s,u]of de.entries())u.description=de.length===2&&s===0?`Reset the existing ${N.symbol} allowance for ${$} on chain ${i} to zero.`:`Approve exactly ${t.formatAmount(d,N.decimals)} ${N.symbol} (${d} base units of ${r}) for ${$} on chain ${i}.`;let $e=[...E,...de,B],Re=await t.preview($e,c);be();let Fe=Re.changes.map(s=>{let u=s.amount.startsWith("-");return`${u?"-":""}${t.formatAmount(u?s.amount.slice(1):s.amount,s.token.decimals)} ${s.token.symbol} (${s.token.address}, chain ${s.token.chainId})`});return{txs:$e,preview:Re,requestId:P,orderId:V,depository:$,originChainId:i,destinationChainId:R,recipient:m,amountIn:{token:N,amount:d},amountOut:{token:O,amount:_},minAmountOut:C,relayerFee:we,refundCurrency:{token:z,amount:re,minimumAmounts:ae},orderDeadline:String(se),refundDeadlines:Z.map(String),expiresAt:String(U),status:"pending",statusEndpoint:he,summary:`${E.length?"Swap prerequisite first, then ":""}Relay inbound from chain ${i} to chain 4663 for ${m}; expected ${t.formatAmount(_,O.decimals)} ${O.symbol}, minimum ${t.formatAmount(C,O.decimals)} ${O.symbol} (${O.address}). Quoted relay fee ${t.formatAmount(we.amount,Q.decimals)} ${Q.symbol} (${Q.address}, chain ${i}); output is net of quoted fees. Order ${V} (request ${P}); output deadline ${se}, refund deadlines ${Z.join(", ")}, quote expires ${U}. Refund terms: details.refundCurrency quotes ${t.formatAmount(re,z.decimals)} ${z.symbol} (${re} base units) on chain ${z.chainId} (${z.address}), but protocol.v2 order refund floor is ${ae.join(", ")} base units. ${Fe.join("; ")}. Unsigned origin transactions only; destination fulfillment remains pending. Track with relay_status; timeout or refund is not fulfillment.`}}var ot=t=>({tools:[{name:"relay_bridge_in",inputSchema:{type:"object",additionalProperties:!1,required:["originChainId","amount"],properties:{originChainId:{type:"integer",minimum:1},destinationChainId:{const:R},originCurrency:H,destinationCurrency:H,amount:te(),minAmountOut:te(),slippageBps:{type:"integer",minimum:0,maximum:9999,default:pe},recipient:H,swap:{type:"object",additionalProperties:!1,required:["from","amountIn"],properties:{from:{type:"object",additionalProperties:!1,required:["address","chainId","symbol","decimals"],properties:{address:H,chainId:{type:"integer",minimum:1},symbol:{type:"string"},decimals:{type:"integer",minimum:0,maximum:255}}},amountIn:te(),slippageBps:{type:"integer",minimum:0,maximum:1e4}}}}},async execute(o,c){try{return await Ue(t,o,c)}catch(i){throw new e(t.plainError(i))}}}]});export{nt as a,ot as b};
1
+ import{b as pe,c as De}from"./SQ5BNSXR.js";import{c as Te,d as a,r as xe}from"./53N7PNJH.js";import{o as ce}from"./CAU44UWP.js";import{a as M}from"./VJ3W2V3B.js";import{a as ve}from"./6IM6A5VA.js";import{a as te}from"./UWOFA6GV.js";import{c as H,j as Ce}from"./73N3TOJL.js";import{a as ke}from"./RETS2ZEK.js";import{a as R,i as qe}from"./XPFVT2EA.js";import{a as e}from"./5YS5V2LK.js";import{decodeFunctionData as Ee,erc20Abi as Ne}from"viem";var je="https://api.relay.link",q="0x0000000000000000000000000000000000000000",Le=60,Se=30,n=qe[R].relay.depository.address.toLowerCase(),ne="0x59916da825d2d2ec1bf878d71c88826f6633ecca",Oe=new Map([[1,{chainId:"ethereum",depository:n}],[10,{chainId:"optimism",depository:n}],[25,{chainId:"cronos",depository:ne}],[56,{chainId:"bnb",depository:n}],[100,{chainId:"gnosis",depository:n}],[130,{chainId:"unichain",depository:n}],[137,{chainId:"polygon",depository:n}],[143,{chainId:"monad",depository:n}],[146,{chainId:"sonic",depository:n}],[169,{chainId:"manta",depository:n}],[196,{chainId:"xlayer",depository:n}],[288,{chainId:"boba",depository:n}],[324,{chainId:"zksync",depository:n}],[360,{chainId:"shape",depository:n}],[480,{chainId:"worldchain",depository:n}],[747,{chainId:"flow",depository:n}],[988,{chainId:"stable",depository:n}],[999,{chainId:"hyperevm",depository:n}],[1088,{chainId:"metis",depository:ne}],[1135,{chainId:"lisk",depository:n}],[1868,{chainId:"soneium",depository:n}],[2020,{chainId:"ronin",depository:n}],[2741,{chainId:"abstract",depository:n}],[2818,{chainId:"morph",depository:n}],[4217,{chainId:"tempo",depository:n}],[4326,{chainId:"megaeth",depository:n}],[5e3,{chainId:"mantle",depository:ne}],[5031,{chainId:"somnia",depository:n}],[5042,{chainId:"arc",depository:n}],[8453,{chainId:"base",depository:n}],[9745,{chainId:"plasma",depository:n}],[33139,{chainId:"apechain",depository:n}],[34443,{chainId:"mode",depository:n}],[42018,{chainId:"mythos",depository:n}],[42161,{chainId:"arbitrum",depository:n}],[42220,{chainId:"celo",depository:n}],[43114,{chainId:"avalanche",depository:n}],[48900,{chainId:"zircuit",depository:n}],[57073,{chainId:"ink",depository:n}],[59144,{chainId:"linea",depository:ne}],[60808,{chainId:"bob",depository:n}],[80094,{chainId:"berachain",depository:n}],[97477,{chainId:"doma",depository:n}],[98866,{chainId:"plume",depository:n}],[534352,{chainId:"scroll",depository:n}],[685689,{chainId:"gensyn",depository:n}],[747474,{chainId:"katana",depository:n}],[5064014,{chainId:"ethereal",depository:n}],[7777777,{chainId:"zora",depository:n}]]);function nt(t){return Oe.get(t)?.depository}function F(t){return Ce(t,"Provide a token or wallet address.")}function I(t){let o=F(t);return o===M?q:o}function f(t,o){return F(t)===F(o)}function l(t){if(typeof t!="string")throw new e("Provide a decimal base-unit amount string.");return ke(t),t}function oe(t){let o=l(t);if(BigInt(o)<=0n)throw new e("Provide a positive base-unit amount.");return o}function ze(t){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new e("Provide a positive integer origin chain ID.");return t}function Pe(t,o){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new e(`${o} is missing or invalid.`);return t}async function G(t,o,c,i,p){let r=a(c);if(r.chainId!==i||I(r.address)!==p||typeof r.symbol!="string"||!/^[A-Za-z0-9._-]{1,32}$/.test(r.symbol))throw new e("Relay quote token metadata does not match the requested chain and address.");if(p===q){if(r.decimals!==18)throw new e("Native token decimals must be 18.");return{address:M,chainId:i,symbol:r.symbol,decimals:18}}let g=`${i}:${p}`,m=o.get(g);if(m===void 0){let d=await t.clientFor(i).readContract({address:p,abi:Ne,functionName:"decimals"}),w=typeof d=="bigint"?Number(d):d;if(typeof w!="number"||!Number.isInteger(w)||w<0||w>255)throw new e("Could not read valid ERC-20 decimals() on-chain.");m=w,o.set(g,m)}return{address:p,chainId:i,symbol:r.symbol,decimals:m}}async function Ke(t,o,c,i,p,r,g){if(c.swap===void 0)return[];let m=a(c.swap),d=a(m.from);if(d.chainId!==p)throw new e("The swap prerequisite token must be on the origin chain.");let w=await G(t,o,d,p,I(d.address)),j=r===q?M:r;if(f(w.address,j))throw new e("The swap prerequisite must use a different input token.");let me=oe(m.amountIn),y=m.slippageBps;if(y!==void 0&&(typeof y!="number"||!Number.isInteger(y)||y<0||y>1e4))throw new e("Provide swap slippage in basis points from 0 to 10000.");let E=await t.quoteSwap({from:w.address,to:j,amountIn:me,...y===void 0?{}:{slippageBps:y}},i);if(BigInt(l(E.expiresAt))<=BigInt(Math.floor(Date.now()/1e3)))throw new e("The swap prerequisite quote expired. Request a fresh quote.");if(BigInt(l(E.minAmountOut))<BigInt(g))throw new e("The swap prerequisite minimum cannot cover the bridge amount.");let k=await t.buildSwap(E.quoteId,i);if(!("txs"in k)||!k.txs.length)throw new e("The swap prerequisite must return unsigned transactions.");if(k.txs.some(S=>S.chainId!==p))throw new e("The injected swap coordinator does not support this origin chain.");return k.txs.map(S=>t.unsignedTx(S))}async function Ue(t,o,c){ve(c);let i=ze(o.originChainId);if(i===R)throw new e("Inbound bridging requires an origin chain other than 4663.");let p=Oe.get(i);if(!p)throw new e("Relay inbound does not support this origin chain.");if(o.destinationChainId!==void 0&&o.destinationChainId!==R)throw new e("Inbound bridge destination must be chain 4663.");let r=I(o.originCurrency??M),g=I(o.destinationCurrency??M),m=F(o.recipient??c),d=oe(o.amount),w=o.minAmountOut===void 0?void 0:l(o.minAmountOut),j=o.slippageBps===void 0?pe:o.slippageBps;if(ce("0",j),await t.clientFor(i).getChainId()!==i)throw new e("The RPC chain does not match the inbound origin chain.");let y=new Map,E=await Ke(t,y,o,c,i,r,d),k,S=process.env.OAK_RELAY_API_KEY?.trim();if(!S)throw new e("Configure OAK_RELAY_API_KEY on the server: Relay quote/v2 requires a valid API key since October 2, 2026. Status and chain reads remain available without it.");try{let s=await t.http(`${je}/quote/v2`,{method:"POST",headers:{"content-type":"application/json","user-agent":"oak-core/0.1.0","x-api-key":S},body:JSON.stringify({user:c,recipient:m,originChainId:i,destinationChainId:R,originCurrency:r,destinationCurrency:g,amount:d,tradeType:"EXACT_INPUT",...r===q?{}:{explicitDeposit:!0}})});if(!s.ok)throw new Error("Relay HTTP failure.");k=await s.json()}catch{throw new e("Relay quote request failed. Please try again.")}let b=a(k);if(typeof b.requestId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(b.requestId))throw new e("Relay returned an invalid request ID.");let P=b.requestId,he=`/intents/status/v3?requestId=${P}`,L=a(b.details);if(!f(L.sender,c)||!f(L.recipient,m))throw new e("Relay quote sender or recipient does not match the request.");let ye=a(L.currencyIn),ie=a(L.currencyOut),N=await G(t,y,ye.currency,i,r),O=await G(t,y,ie.currency,R,g);if(l(ye.amount)!==d)throw new e("Relay quote input amount does not match the request.");let _=oe(ie.amount),C=oe(ie.minimumAmount);if(BigInt(C)>BigInt(_))throw new e("Relay quote minimum output exceeds the expected output.");if(w!==void 0){if(C!==w)throw new e("Relay order minimum must exactly match minAmountOut. Request a new quote.")}else{let s=ce(_,j);if(BigInt(C)<BigInt(s))throw De(_,C)}let le=a(a(b.fees).relayer),fe=a(le.currency),Q=await G(t,y,fe,i,I(fe.address)),we={token:Q,amount:l(le.amount)},Ie=a(L.refundCurrency),_e=a(Ie.currency),z=await G(t,y,_e,i,r),re=l(Ie.amount),K=a(a(b.protocol).v2);if(typeof K.orderId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(K.orderId))throw new e("Relay returned an invalid order ID.");let V=K.orderId.toLowerCase(),W=a(K.paymentDetails),$=F(W.depository);if(W.chainId!==p.chainId||$!==p.depository||I(W.currency)!==r||l(W.amount)!==d)throw new e("Relay payment details do not match the origin chain depository and input.");let J=a(K.orderData),v=a(J.output);if(v.chainId!=="robinhood"||!Array.isArray(v.calls)||v.calls.length!==0||!Array.isArray(v.payments)||v.payments.length!==1)throw new e("Relay order output does not match destination chain 4663.");let X=a(v.payments[0]);if(!f(X.recipient,m)||I(X.currency)!==g||l(X.minimumAmount)!==C||l(X.expectedAmount)!==_)throw new e("Relay order output payment does not match the quoted recipient and amounts.");let se=Pe(v.deadline,"Relay order output deadline");if(!Array.isArray(J.inputs)||!J.inputs.length)throw new e("Relay order has no inputs.");let Z=[],ae=[];for(let s of J.inputs){let u=a(s),x=a(u.payment);if(x.chainId!==p.chainId||I(x.currency)!==r||l(x.amount)!==d||!Array.isArray(u.refunds)||!u.refunds.length)throw new e("Relay order input does not match the quoted input.");for(let D of u.refunds){let h=a(D);if(!f(h.recipient,c))throw new e("Relay refund recipient does not match the agent wallet. Request a new quote.");if(Z.push(Pe(h.deadline,"Relay order refund deadline")),ae.push(l(h.minimumAmount)),!(h.chainId===p.chainId?f(h.recipient,c)&&I(h.currency)===r:h.chainId==="robinhood"&&I(h.currency)===g))throw new e("Relay order refund terms do not match the sender or recipient.")}}let ge=Math.min(se,...Z),U=0,be=()=>{let s=Math.floor(Date.now()/1e3),u=U||s+Le;if(ge-s<=Se)throw new e("Relay order deadline is expired or too soon to sign safely. Request a new quote.");if(U=Math.min(u,ge-Se),U<=s)throw new e("Relay quote expired before signing. Request a new quote.")};if(be(),!Array.isArray(b.steps)||!b.steps.length)throw new e("Relay returned no origin transactions.");let T=[];for(let s of b.steps){let u=a(s);if(u.kind!=="transaction"||u.requestId!==P||!Array.isArray(u.items)||!u.items.length)throw new e("Relay returned an unsupported origin step.");for(let x of u.items){let D=a(x),h=a(D.data),ue=a(D.check);if(D.status!=="incomplete"||h.chainId!==i||!f(h.from,c))throw new e("Relay transaction does not match the origin chain and sender.");if(ue.method!=="GET"||ue.endpoint!==he)throw new e("Relay status endpoint does not match the request ID.");T.push(t.unsignedTx({to:F(h.to),data:h.data,value:l(h.value),chainId:i,description:`Relay inbound deposit for request ${P}; destination chain 4663.`}))}}if(!T.length)throw new e("Relay returned no origin transactions.");if(r===q&&T.length!==1)throw new e("Relay native deposit must be a single depositNative transaction.");if(r!==q&&T.length>2)throw new e("Relay ERC-20 deposit allows at most one exact-amount approval before depositErc20.");for(let s of T.slice(0,-1)){if(!s.data.toLowerCase().startsWith("0x095ea7b3"))throw new e("Relay returned an unsupported prerequisite transaction.");let u=Ee({abi:Ne,data:s.data});if(u.functionName!=="approve")throw new e("Relay returned an invalid approval.");let[x,D]=u.args;if(r===q||!f(s.to,r)||!f(x,$)||D!==BigInt(d)||s.value!=="0")throw new e("Relay approval must authorize the exact input amount for the origin depository.");s.description=`Approve exactly ${t.formatAmount(d,N.decimals)} ${N.symbol} (${d} base units of ${r}) for ${$} on chain ${i}.`}let B=T[T.length-1],Y=r===q,ee=Y?"depositNative":"depositErc20",Ae=Y?"depositNative(address,bytes32)":"depositErc20(address,address,uint256,bytes32)";if(!f(B.to,$)||B.value!==(Y?d:"0")||!(Y?/^0x[0-9a-fA-F]{136}$/:/^0x[0-9a-fA-F]{264}$/).test(B.data))throw new e(`Relay deposit transaction does not target the origin depository with ${ee} calldata.`);let A;try{A=Ee({abi:Te,data:B.data})}catch{throw new e(`Relay deposit transaction must call ${Ae}.`)}if(A.functionName!==ee)throw new e(`Relay deposit transaction must call ${Ae}.`);let Be=A.args[0],Me=A.functionName==="depositErc20"?A.args[3]:A.args[1];if(A.functionName==="depositErc20"&&(!f(A.args[1],r)||A.args[2]!==BigInt(d)))throw new e("Relay depositErc20 token or amount does not match the quoted input.");if(!f(Be,c)||Me.toLowerCase()!==V)throw new e(`Relay ${ee} depositor or orderId does not match the wallet and quoted protocol.v2.orderId.`);B.description=`Relay inbound ${ee} for order ${V} (request ${P}); destination chain 4663.`;let de=Y?[]:await xe(t,r,$,d,i,c);for(let[s,u]of de.entries())u.description=de.length===2&&s===0?`Reset the existing ${N.symbol} allowance for ${$} on chain ${i} to zero.`:`Approve exactly ${t.formatAmount(d,N.decimals)} ${N.symbol} (${d} base units of ${r}) for ${$} on chain ${i}.`;let $e=[...E,...de,B],Re=await t.preview($e,c);be();let Fe=Re.changes.map(s=>{let u=s.amount.startsWith("-");return`${u?"-":""}${t.formatAmount(u?s.amount.slice(1):s.amount,s.token.decimals)} ${s.token.symbol} (${s.token.address}, chain ${s.token.chainId})`});return{txs:$e,preview:Re,requestId:P,orderId:V,depository:$,originChainId:i,destinationChainId:R,recipient:m,amountIn:{token:N,amount:d},amountOut:{token:O,amount:_},minAmountOut:C,relayerFee:we,refundCurrency:{token:z,amount:re,minimumAmounts:ae},orderDeadline:String(se),refundDeadlines:Z.map(String),expiresAt:String(U),status:"pending",statusEndpoint:he,summary:`${E.length?"Swap prerequisite first, then ":""}Relay inbound from chain ${i} to chain 4663 for ${m}; expected ${t.formatAmount(_,O.decimals)} ${O.symbol}, minimum ${t.formatAmount(C,O.decimals)} ${O.symbol} (${O.address}). Quoted relay fee ${t.formatAmount(we.amount,Q.decimals)} ${Q.symbol} (${Q.address}, chain ${i}); output is net of quoted fees. Order ${V} (request ${P}); output deadline ${se}, refund deadlines ${Z.join(", ")}, quote expires ${U}. Refund terms: details.refundCurrency quotes ${t.formatAmount(re,z.decimals)} ${z.symbol} (${re} base units) on chain ${z.chainId} (${z.address}), but protocol.v2 order refund floor is ${ae.join(", ")} base units. ${Fe.join("; ")}. Unsigned origin transactions only; destination fulfillment remains pending. Track with relay_status; timeout or refund is not fulfillment.`}}var ot=t=>({tools:[{name:"relay_bridge_in",inputSchema:{type:"object",additionalProperties:!1,required:["originChainId","amount"],properties:{originChainId:{type:"integer",minimum:1},destinationChainId:{const:R},originCurrency:H,destinationCurrency:H,amount:te(),minAmountOut:te(),slippageBps:{type:"integer",minimum:0,maximum:9999,default:pe},recipient:H,swap:{type:"object",additionalProperties:!1,required:["from","amountIn"],properties:{from:{type:"object",additionalProperties:!1,required:["address","chainId","symbol","decimals"],properties:{address:H,chainId:{type:"integer",minimum:1},symbol:{type:"string"},decimals:{type:"integer",minimum:0,maximum:255}}},amountIn:te(),slippageBps:{type:"integer",minimum:0,maximum:1e4}}}}},async execute(o,c){try{return await Ue(t,o,c)}catch(i){throw new e(t.plainError(i))}}}]});export{nt as a,ot as b};
@@ -1 +1 @@
1
- import{b as gt}from"./H6ED3RHF.js";import{b as ft}from"./74BPMUAG.js";import{b as ut}from"./SQH7A4O3.js";import{c as ct}from"./OJMYESQU.js";import{b as mt}from"./NHCRJC5X.js";import{c as pt}from"./OW7GOYKA.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"./EAEQOS7Y.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{c as pt}from"./OW7GOYKA.js";import{b as gt}from"./H6ED3RHF.js";import{b as ft}from"./74BPMUAG.js";import{b as ut}from"./SQH7A4O3.js";import{c as ct}from"./OJMYESQU.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 +1 @@
1
- import{a as h}from"./JOMK32QW.js";import{c as p}from"./73N3TOJL.js";import{a as l}from"./XPFVT2EA.js";import{a}from"./5YS5V2LK.js";import{getAddress as v}from"viem";var f={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},w=[["hookr_release",{},[],"Read verified release contracts, block and recapture lane."],["hookr_blocks",{},[],"Read all Hook Blocks and their current availability."],["hookr_kings",{poolId:f},[],"Read King of the Pool rounds, leaders, pots and endings."],["hookr_claims",{poolId:f},[],"Read the signing wallet's prizes, royalties, recapture and PoolManager claims."],["hookr_revenue_tokens",{limit:{type:"integer",minimum:1,maximum:50},cursor:{type:"string",pattern:"^(v1|v1:[1-9][0-9]{0,19}|v2:[1-9][0-9]{0,19})$"}},[],"Read revenue tokens, tokenizer provenance, streams and income, page by page."],["hookr_revenue_token",{token:p},["token"],"Read a revenue token, stream endings, income, drops and the signing wallet's claims."],["hookr_hook",{address:p},["address"],"Read shared or owned hook provenance, ownership, allowed blocks, opening and pools."]],H=[...w.map(d=>d[0]),"hookr_contracts","hookr_read","hookr_revenue_read","hookr_addon_read","hookr_api_read"];function j(d){return[...w.map(([t,c,s,o])=>({name:t,inputSchema:{type:"object",description:o,properties:c,required:s,additionalProperties:!1},execute:async(r,g)=>{if(Object.keys(r).some(n=>!Object.hasOwn(c,n))||s.some(n=>r[n]===void 0))throw new a(`Provide the documented arguments for ${t}.`);let k={};for(let[n,i]of Object.entries(r)){let u=c[n];if(u.type==="integer"){if(typeof i!="number"||!Number.isInteger(i)||i<Number(u.minimum)||i>Number(u.maximum))throw new a("Hookr revenue page limit must be an integer from 1 to 50.")}else if(typeof i!="string"||!new RegExp(String(u.pattern)).test(i))throw new a(`Provide a valid Hookr ${n}.`);k[n]=n==="token"||n==="address"?v(String(i)):i}return(t==="hookr_claims"||t==="hookr_revenue_token")&&(k.account=g),{...await h(d,t,k),chainId:l,source:"https://hookr.fun/api/mcp"}}})),y(d)]}var m={catalog:"/api/hooks/catalog",stats:"/api/protocol-stats",poolApr:"/api/pool-apr",revenueTokens:"/api/revenue-tokens",revenueIncome:"/api/revenue-tokens/income"};function y(d){return{name:"hookr_api_read",inputSchema:{type:"object",description:"Read Hookr public catalog, protocol stats, pool APR, revenue directory/income, or one token's doors/mark. Marks are project metadata, not investment or security endorsements.",properties:{resource:{type:"string",enum:[...Object.keys(m),"revenueDoors","revenueMark"]},token:p},required:["resource"],additionalProperties:!1},execute:async e=>{if(Object.keys(e).some(o=>!["resource","token"].includes(o))||typeof e.resource!="string")throw new a("Choose a documented Hookr public resource.");let t=["revenueDoors","revenueMark"].includes(e.resource);if(!t&&e.token!==void 0||t&&typeof e.token!="string")throw new a("Only the revenueDoors and revenueMark resources take a token address.");let c;if(t){let o;try{o=v(String(e.token))}catch{throw new a("Provide a valid revenue token address.")}c=`/api/revenue-tokens/${o}/${e.resource==="revenueDoors"?"doors":"mark"}`}else{if(!Object.hasOwn(m,e.resource))throw new a("Choose a documented Hookr public resource.");c=m[e.resource]}let s=`https://hookr.fun${c}`;try{let o=await d.http(s,{method:"GET",redirect:"error",signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error("Unavailable");if(e.resource==="revenueMark"){if(!o.headers.get("content-type")?.includes("image/svg+xml"))throw new Error("Invalid mark");return{chainId:l,source:s,imageUrl:s,pngUrl:`${s}.png`,note:"Official SVG mark URL; SVG code is not executed or returned. The PNG URL has not been fetched."}}let r=await o.json();if(!r||typeof r!="object"||"error"in r||"status"in r&&r.status==="unavailable")throw new Error("Unavailable");return{chainId:l,source:s,data:r}}catch{throw new a("Hookr public resource is unavailable. Retry later; no empty or zero result is implied.")}}}}export{H as a,j as b,y as c};
1
+ import{a as h}from"./A25P24G2.js";import{c as p}from"./73N3TOJL.js";import{a as l}from"./XPFVT2EA.js";import{a}from"./5YS5V2LK.js";import{getAddress as v}from"viem";var f={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},w=[["hookr_release",{},[],"Read verified release contracts, block and recapture lane."],["hookr_blocks",{},[],"Read all Hook Blocks and their current availability."],["hookr_kings",{poolId:f},[],"Read King of the Pool rounds, leaders, pots and endings."],["hookr_claims",{poolId:f},[],"Read the signing wallet's prizes, royalties, recapture and PoolManager claims."],["hookr_revenue_tokens",{limit:{type:"integer",minimum:1,maximum:50},cursor:{type:"string",pattern:"^(v1|v1:[1-9][0-9]{0,19}|v2:[1-9][0-9]{0,19})$"}},[],"Read revenue tokens, tokenizer provenance, streams and income, page by page."],["hookr_revenue_token",{token:p},["token"],"Read a revenue token, stream endings, income, drops and the signing wallet's claims."],["hookr_hook",{address:p},["address"],"Read shared or owned hook provenance, ownership, allowed blocks, opening and pools."]],H=[...w.map(d=>d[0]),"hookr_contracts","hookr_read","hookr_revenue_read","hookr_addon_read","hookr_api_read"];function j(d){return[...w.map(([t,c,s,o])=>({name:t,inputSchema:{type:"object",description:o,properties:c,required:s,additionalProperties:!1},execute:async(r,g)=>{if(Object.keys(r).some(n=>!Object.hasOwn(c,n))||s.some(n=>r[n]===void 0))throw new a(`Provide the documented arguments for ${t}.`);let k={};for(let[n,i]of Object.entries(r)){let u=c[n];if(u.type==="integer"){if(typeof i!="number"||!Number.isInteger(i)||i<Number(u.minimum)||i>Number(u.maximum))throw new a("Hookr revenue page limit must be an integer from 1 to 50.")}else if(typeof i!="string"||!new RegExp(String(u.pattern)).test(i))throw new a(`Provide a valid Hookr ${n}.`);k[n]=n==="token"||n==="address"?v(String(i)):i}return(t==="hookr_claims"||t==="hookr_revenue_token")&&(k.account=g),{...await h(d,t,k),chainId:l,source:"https://hookr.fun/api/mcp"}}})),y(d)]}var m={catalog:"/api/hooks/catalog",stats:"/api/protocol-stats",poolApr:"/api/pool-apr",revenueTokens:"/api/revenue-tokens",revenueIncome:"/api/revenue-tokens/income"};function y(d){return{name:"hookr_api_read",inputSchema:{type:"object",description:"Read Hookr public catalog, protocol stats, pool APR, revenue directory/income, or one token's doors/mark. Marks are project metadata, not investment or security endorsements.",properties:{resource:{type:"string",enum:[...Object.keys(m),"revenueDoors","revenueMark"]},token:p},required:["resource"],additionalProperties:!1},execute:async e=>{if(Object.keys(e).some(o=>!["resource","token"].includes(o))||typeof e.resource!="string")throw new a("Choose a documented Hookr public resource.");let t=["revenueDoors","revenueMark"].includes(e.resource);if(!t&&e.token!==void 0||t&&typeof e.token!="string")throw new a("Only the revenueDoors and revenueMark resources take a token address.");let c;if(t){let o;try{o=v(String(e.token))}catch{throw new a("Provide a valid revenue token address.")}c=`/api/revenue-tokens/${o}/${e.resource==="revenueDoors"?"doors":"mark"}`}else{if(!Object.hasOwn(m,e.resource))throw new a("Choose a documented Hookr public resource.");c=m[e.resource]}let s=`https://hookr.fun${c}`;try{let o=await d.http(s,{method:"GET",redirect:"error",signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error("Unavailable");if(e.resource==="revenueMark"){if(!o.headers.get("content-type")?.includes("image/svg+xml"))throw new Error("Invalid mark");return{chainId:l,source:s,imageUrl:s,pngUrl:`${s}.png`,note:"Official SVG mark URL; SVG code is not executed or returned. The PNG URL has not been fetched."}}let r=await o.json();if(!r||typeof r!="object"||"error"in r||"status"in r&&r.status==="unavailable")throw new Error("Unavailable");return{chainId:l,source:s,data:r}}catch{throw new a("Hookr public resource is unavailable. Retry later; no empty or zero result is implied.")}}}}export{H as a,j as b,y as c};
@@ -1 +1 @@
1
- import{b as xe,o as ae}from"./EAEQOS7Y.js";import{a as re}from"./XCFA73P2.js";import{b as Ie}from"./AXYOJBX6.js";import{a as ke}from"./UWOFA6GV.js";import{e as W,g as p,i as ye,n as be}from"./73N3TOJL.js";import{a as x,i as we}from"./XPFVT2EA.js";import{a as Te}from"./EG6M6SSO.js";import{a}from"./5YS5V2LK.js";import{decodeErrorResult as Oe,decodeEventLog as ie,encodeAbiParameters as D,encodeFunctionData as N,erc20Abi as Q,parseAbi as Ne,parseAbiParameters as M,toHex as Ae,zeroAddress as C}from"viem";var h=we[x].poolsTrade,J=h.liquidityLauncher.address,S=h.uerc20BeneficiaryVault.address,ce=h.universalRouter.address,ne=10n**27n,q=(1n<<128n)-1n,ve=`0x${"00".repeat(32)}`,H=63127652n,de=100000n,oe=10000000n,Le=2000n,ue={address:re,symbol:"ETH",decimals:18,chainId:x},m=Ne(["function multicall(bytes[] data) payable returns (bytes[])","function createToken(address factory,string name,string symbol,uint8 decimals,uint128 initialSupply,address recipient,bytes tokenData) payable returns (address)","function distributeToken(address token,(address strategy,uint128 amount,bytes configData) distribution,bytes32 salt) payable","function distributeWithNative(address strategy,bytes configData,bytes32 salt,uint256 nativeAmount) payable","function getGraffiti(address sender) view returns (bytes32)","function getUERC20Address(string name,string symbol,uint8 decimals,address recipient,bytes32 graffiti) view returns (address)","function execute(bytes commands,bytes[] inputs,uint256 deadline) payable","function collectFees(uint256[] ids)","function claim(uint256 id,uint256 minCurrency0Amount,uint256 minCurrency1Amount)","function amounts(uint256 id) view returns (uint128 eth,uint128 token)","function ownerOf(uint256 id) view returns (address)","function getApproved(uint256 id) view returns (address)","function approve(address spender,uint256 id)","function safeTransferFrom(address from,address to,uint256 id)","function approve(address token,address spender,uint160 amount,uint48 expiration)","error V4TooLittleReceived(uint256 minAmountOut,uint256 amountOut)"]),U=Ne(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)","event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"]),_=[h.instantLaunchStrategyFeesOn.address,h.instantLaunchStrategyFeesOff.address];function se(l){if(l.status!=="success")throw new a("The launch receipt did not succeed.");let c=[];for(let y of l.logs){let F=_.findIndex(O=>p(O,y.address));if(F===-1||y.topics[0]!=="0x3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4")continue;let j=ie({abi:U,eventName:"TokenLaunched",data:y.data,topics:[...y.topics]}),{token:T,poolId:Y,poolKey:R,feeSplitter:Z}=j.args,ee=F===0?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address;if(!p(Z,ee)||!p(R.currency0,C)||!p(R.currency1,T)||R.fee!==2500||R.tickSpacing!==25||!p(R.hooks,C))throw new a("The launch does not match the current native ETH strategy.");let P=l.logs.filter(O=>p(O.address,h.v4PositionManager.address)).flatMap(O=>{if(O.topics[0]!=="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")return[];let G=ie({abi:U,eventName:"Transfer",data:O.data,topics:[...O.topics]}).args;return p(G.from,C)&&p(G.to,_[F])?[G.tokenId]:[]});if(P.length!==1)throw new a("The launch receipt must identify one matching position mint.");c.push({token:T,poolId:Y,positionId:P[0].toString(),creatorFees:F===0})}return c}function B(l){return ye(l,"Provide a valid wallet or token address.")}function $(l,c,y=!1){return be(l,`${c} is outside its supported range.`,{notString:`${c} must be an integer string in base units.`,positive:!y})}function X(l,c,y=!1){if(y&&l===void 0)return"";if(typeof l!="string"||!y&&!l.trim()||l.length>4096)throw new a(`Provide a valid ${c}.`);return l}function le(l){if(typeof l!="string"||!/^0x[0-9a-fA-F]{64}$/.test(l))throw new a("Provide a valid launch transaction hash.");return l}function fe(l,c,y="minAmountOut"){let F=c.slippageBps??xe;if(typeof F!="number")throw new a("Slippage must be an integer in basis points.");let j=ae(l.toString(),F),T=c[y]===void 0?BigInt(j):$(c[y],y,l===0n);if(T>l||l>0n&&T===0n||T>q)throw new a("The minimum output must be positive and no larger than the simulated output.");return T}var Ee=l=>{let c=l.clientFor(x),y=(e,s,o,n)=>l.unsignedTx({to:e,data:s,value:o.toString(),chainId:x,description:n}),F=e=>{throw new a(l.plainError(e))};async function j(){if(await c.getChainId()!==x)throw new a("pools.trade requires Robinhood Chain 4663.")}async function T(e,s,o){let n=await l.preview(e,s),t=n.changes.map(({token:r,amount:d})=>{let i=d.startsWith("-");return`${i?"-":""}${l.formatAmount(i?d.slice(1):d,r.decimals)} ${r.symbol} (${r.address}, chain ${r.chainId})`});return{txs:e,summary:[o,n.summary,...t].join(" ")}}async function Y(){return(await c.getBlock()).timestamp+600n}function R(e,s,o,n,t,r){let d=[C,e,2500,25,C],i=[D(M("((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"),[[d,s,o,n,0n,"0x"]]),D(M("address,uint256"),[s?C:e,o]),D(M("address,address,uint256"),[s?e:C,t,0n])],f=[D(M("bytes,bytes[]"),["0x060c0e",i])];return{inputs:f,encoded:D(M("bytes,bytes[],uint256"),["0x10",f,r])}}async function Z(e,s){let o=await c.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:s,gas:Ae(Te),to:i.to,data:i.data,value:Ae(BigInt(i.value))}))}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(o)||o.length!==1||!W(o[0])||!Array.isArray(o[0].calls)||o[0].calls.length!==e.length)throw new a("The output simulation returned a malformed response.");let n=o[0].calls;if(!n.slice(0,-1).every(i=>W(i)&&i.status==="0x1"&&!i.error))throw new a("A prerequisite failed during the output simulation.");let t=n.at(-1);if(!W(t)||t.status!=="0x0")throw new a("The output simulation did not return the expected minimum-output control.");let r=typeof t.returnData=="string"&&t.returnData!=="0x"?t.returnData:W(t.error)?t.error.data:void 0;if(typeof r!="string"||!/^0x[0-9a-fA-F]+$/.test(r))throw new a("The output simulation did not report an expected amount.");let d=Oe({abi:m,data:r});if(d.errorName!=="V4TooLittleReceived"||d.args[0]!==q||d.args[1]<=0n||d.args[1]>=q)throw new a("The output simulation did not report a valid amount.");return d.args[1]}async function ee(e,s,o,n=()=>!0){let t=await c.getBlockNumber(),r=t<H?0n:(t-H)/oe+1n,d=1n,i=(u=1n)=>{if(d+=u,d>Le)throw new a("Pools.trade scan exceeds the 2000-request limit. Use launchTx for a specific launch; positions coverage is incomplete.")};i(r*BigInt(_.length+(e&&!o?1:0)));let f=new Map,w=new Set;for(let u=H;u<=t&&n();u+=oe){let b=u+oe-1n>t?t:u+oe-1n,v=(await Promise.all(_.map(k=>c.getLogs({address:k,event:U[0],...s?{args:{token:s}}:{},fromBlock:u,toBlock:b,strict:!0})))).flat(),L=[...new Set(v.map(k=>k.transactionHash))].filter(k=>!k||!f.has(k));for(let k=0;k<L.length&&n();k+=8)await Promise.all(L.slice(k,k+8).map(async E=>{if(!E)throw new a("A launch log is missing its transaction hash.");i();let V=await c.getTransactionReceipt({hash:E});f.set(E,V),n()&&await o?.(V)}));if(!n())break;if(e&&!o){let k=await c.getLogs({address:S,event:U[1],args:{to:e},fromBlock:u,toBlock:b,strict:!0});for(let E of k){let V=ie({abi:U,eventName:"Transfer",data:E.data,topics:E.topics}).args;w.add(V.tokenId.toString())}}}return{receipts:[...f.values()],feeIds:w}}async function P(e){let o=(e.launchTx!==void 0?[await c.getTransactionReceipt({hash:le(e.launchTx)})]:(await ee(void 0,e.token===void 0?void 0:B(e.token))).receipts).flatMap(se).filter(n=>e.positionId!==void 0?n.positionId===$(e.positionId,"positionId").toString():p(n.token,B(e.token)));if(o.length!==1)throw new a("No unique current-strategy launch was found. Older strategy generations are unsupported.");return o[0]}async function O(e,s){if(typeof e.creatorFees!="boolean")throw new a("creatorFees must be an explicit boolean; the choice is permanent.");if(e.pair!==void 0&&!p(B(e.pair),C)&&!p(B(e.pair),re))throw new a("Only the native ETH pair is supported.");if(e.decimals!==void 0&&e.decimals!==18)throw new a("Instant Launch requires 18 decimals.");if(e.supply!==void 0&&$(e.supply,"supply")!==ne)throw new a("Instant Launch requires a supply of one billion tokens.");let o=B(e.feeBeneficiary);if(p(o,C)||p(o,J))throw new a("The fee beneficiary must be a wallet other than the launcher or zero address.");let n=X(e.name,"name"),t=X(e.symbol,"symbol"),r=e.initialBuy===void 0?0n:$(e.initialBuy,"initialBuy",!0);if(r>q)throw new a("The initial buy exceeds uint128.");if(r===0n&&e.minAmountOut!==void 0)throw new a("A minimum output requires an initial buy.");let d=await c.readContract({address:J,abi:m,functionName:"getGraffiti",args:[s]}),i=B(await c.readContract({address:h.uerc20Factory.address,abi:m,functionName:"getUERC20Address",args:[n,t,18,J,d]})),f=await c.getCode({address:i});if(f&&f!=="0x")throw new a("This wallet already launched that name and symbol.");let w=D(M("(string,string,string,bytes)"),[[X(e.description,"description",!0),X(e.website,"website",!0),X(e.imageUri,"image URI",!0),"0x"]]),u=e.creatorFees?_[0]:_[1],b=[N({abi:m,functionName:"createToken",args:[h.uerc20Factory.address,n,t,18,ne,J,w]}),N({abi:m,functionName:"distributeToken",args:[i,{strategy:u,amount:ne,configData:D(M("address"),[o])},ve]})],v=await Y(),z=k=>{let E=[...b];if(r>0n){let V=D(M("(address,address,bytes)"),[[ce,s,R(i,!0,r,k,s,v).encoded]]);E.push(N({abi:m,functionName:"distributeWithNative",args:[h.universalRouterStrategyApp.address,V,ve,r]}))}return y(J,N({abi:m,functionName:"multicall",args:[E]}),r,`Atomic Instant Launch: creator fees ${e.creatorFees?"on":"off"} (permanent); beneficiary ${o}.`)},L=r>0n?fe(await Z([z(q)],s),e):0n;return T([z(L)],s,`Launch ${n} (${i}, chain 4663), supply 1000000000, decimals 18. Creator fees ${e.creatorFees?"on":"off"} are permanent; fee beneficiary ${o}. Creator ETH fees come from buys only (recorded 0.09996%); sells compound into locked liquidity. Initial-buy minimum ${L} token base units. Off-chain image/display unproven; no private metadata registration. No transaction sent.`)}async function G(e,s,o){let n=$(e.amountIn,"amountIn");if(n>q)throw new a("The trade amount exceeds uint128.");let t=B(e.token);await P(e);let r=await Y(),d=[];o||(await c.readContract({address:t,abi:Q,functionName:"allowance",args:[s,h.permit2.address]})<n&&d.push(l.approval(t,h.permit2.address,n.toString(),x)),d.push(y(h.permit2.address,N({abi:m,functionName:"approve",args:[t,ce,n,Number(r)]}),0n,`Permit the exact ${n} token base units until ${r}.`)));let i=u=>[...d,y(ce,N({abi:m,functionName:"execute",args:["0x10",R(t,o,n,u,s,r).inputs,r]}),o?n:0n,`${o?"Buy":"Sell"} ${t} with minimum output ${u}.`)],f=await Z(i(q),s),w=fe(f,e);return T(i(w),s,`${o?"Buy":"Sell"} token ${t} (chain 4663, 18 decimals), amountIn ${n}, minimum output ${w} ${o?"token":"ETH"} base units (18 decimals). Recorded swap fee 0.2899%; creator ETH fees from buys only, none from sells. No transaction sent.`)}async function pe(e,s,o){let n=await P(e),t=BigInt(n.positionId),r=n.creatorFees?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address,d=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[t]});if(!p(d,r))throw new a("The position is not locked in its current-strategy splitter.");if(!o)return T([y(r,N({abi:m,functionName:"collectFees",args:[[t]]}),0n,`Collect fees for position ${t}; permissionless.`)],s,"Collect fees for the entitled recipients; collection does not transfer creator fees to the collector. No transaction sent.");if(!n.creatorFees)throw new a("Creator fees are permanently disabled for this position.");let i=await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[t]});if(!p(i,s))throw new a("Only the current fee NFT holder is entitled to claim.");let f=await c.readContract({address:S,abi:m,functionName:"amounts",args:[t]}),w=fe(f[0],e,"minEth");if(f[1]!==0n)throw new a("The current buy-only creator fee configuration returned unexpected token fees.");return T([y(S,N({abi:m,functionName:"claim",args:[t,w,0n]}),0n,`Claim collected ETH fees for position ${t} to ${s}.`)],s,`Claim collected fees: ${f[0]} ETH base units (18 decimals), minimum ${w}. Uncollected fees require poolstrade_collect first. No transaction sent.`)}async function Se(e,s){let o=await P(e),n=B(e.to);if(p(n,C))throw new a("The token recipient cannot be the zero address.");let t=$(e.amount,"amount"),r=await te(o.token,await c.getBlockNumber());return T([y(r.address,N({abi:Q,functionName:"transfer",args:[n,t]}),0n,`Transfer exactly ${t} ${r.symbol} base units to ${n}.`)],s,`Transfer ${t} token base units (token ${r.address}, decimals ${r.decimals}, chain ${r.chainId}) to ${n}. No approval; no transaction sent.`)}async function Be(e,s){if(!Array.isArray(e.positionIds)||e.positionIds.length<1||e.positionIds.length>20||!Array.isArray(e.launchTxs)||e.launchTxs.length!==e.positionIds.length)throw new a("Provide 1 to 20 positionIds and one matching launchTxs entry for each.");let o=e.positionIds.map(d=>$(d,"positionId").toString());if(new Set(o).size!==o.length)throw new a("Each position ID must appear once.");let n=e.launchTxs.map(le),t=new Map;for(let[d,i]of o.entries()){let w=(await P({positionId:i,launchTx:n[d]})).creatorFees?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address,u=BigInt(i),b=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[u]});if(!p(b,w))throw new a("The position is not locked in its current-strategy splitter.");t.set(w,[...t.get(w)??[],u])}let r=[...t].map(([d,i])=>y(d,N({abi:m,functionName:"collectFees",args:[i]}),0n,`Collect fees for positions ${i.join(", ")}; permissionless.`));return T(r,s,"Collect fees in batches for the fixed entitled recipients. Collection does not pay the collector. No transaction sent.")}let K="Current native ETH Instant Launch strategies only. Crowd Launch and older deployments are not covered.";async function te(e,s){let[o,n]=await Promise.all([c.readContract({address:e,abi:Q,functionName:"symbol",blockNumber:s}),c.readContract({address:e,abi:Q,functionName:"decimals",blockNumber:s})]);if(typeof o!="string"||!o||o.length>256||n!==18)throw new a("The current launch token returned invalid metadata.");return{address:e,symbol:o,decimals:n,chainId:x}}async function me(e,s,o,n){let t=n??await te(e.token,o),r=await c.readContract({address:t.address,abi:Q,functionName:"balanceOf",args:[s],blockNumber:o});return{token:t,amount:r.toString(),humanAmount:l.formatAmount(r.toString(),t.decimals)}}async function Ce(e,s){let o=await P(e),n=await c.getBlockNumber();return{wallet:s,...await me(o,s,n),blockNumber:n.toString(),coverage:K}}async function $e(e,s){let o=le(e.launchTx),n=await c.getTransactionReceipt({hash:o}),t=se(n);if(e.token!==void 0&&(t=t.filter(i=>p(i.token,B(e.token)))),e.positionId!==void 0&&(t=t.filter(i=>i.positionId===$(e.positionId,"positionId").toString())),!t.length)throw new a("The receipt contains no matching current Instant Launch. Crowd Launch and older strategies are not covered.");let r=await c.getBlockNumber(),d=await Promise.all(t.map(async i=>{let f=i.creatorFees?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address,w=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:r});if(!p(w,f))throw new a("The position is not locked in its current-strategy splitter.");let u=i.creatorFees?{owner:await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:r}),approved:await c.readContract({address:S,abi:m,functionName:"getApproved",args:[BigInt(i.positionId)],blockNumber:r}),collected:await c.readContract({address:S,abi:m,functionName:"amounts",args:[BigInt(i.positionId)],blockNumber:r})}:void 0,b=await te(i.token,r);return{...i,token:b,custodian:w,holding:await me(i,s,r,b),...u?{feeEntitlement:{owner:u.owner,approved:u.approved,collected:[{token:ue,amount:u.collected[0].toString()},{token:b,amount:u.collected[1].toString()}],uncollectedFeesIncluded:!1}}:{}}}));return{launchTx:o,wallet:s,creator:n.from,blockNumber:r.toString(),launches:d,coverage:K}}async function Fe(e){let s=await c.getBlockNumber(),o=e.limit??20;if(typeof o!="number"||!Number.isInteger(o)||o<1||o>50)throw new a("limit must be an integer from 1 to 50.");let n=e.fromBlock===void 0?s>=H+de?s-de+1n:H:$(e.fromBlock,"fromBlock",!0),t=e.toBlock===void 0?s:$(e.toBlock,"toBlock",!0),r=0;if(e.cursor!==void 0){if(typeof e.cursor!="string"||!/^[0-9]{1,78}:[0-9]{1,78}:[0-9]{1,10}$/.test(e.cursor))throw new a("Provide the browse cursor exactly as returned.");let u=e.cursor.split(":"),b=BigInt(u[0]),v=BigInt(u[1]);if(e.fromBlock!==void 0&&n!==b||e.toBlock!==void 0&&t!==v)throw new a("The cursor does not match this block range.");n=b,t=v,r=Number(u[2])}if(s<H&&e.fromBlock===void 0&&e.toBlock===void 0&&e.cursor===void 0)return{launches:[],cursor:null,fromBlock:H.toString(),toBlock:s.toString(),coverage:K,predeployment:!0};if(n<H||t<n||t>s||t-n>=de)throw new a("Choose a deployed block range of at most 100000 blocks, ending no later than the current head.");let d=await c.getLogs({address:_,event:U[0],fromBlock:n,toBlock:t,strict:!0});if(d.some(u=>u.blockNumber===null||u.logIndex===null||!u.transactionHash))throw new a("The launch feed returned an incomplete log.");if(d.sort((u,b)=>u.blockNumber===b.blockNumber?b.logIndex-u.logIndex:u.blockNumber>b.blockNumber?-1:1),r>d.length)throw new a("The browse cursor is outside the launch feed.");let i=new Map,f=[];for(let u of d.slice(r,r+o)){let b=u.transactionHash,v=i.get(b);v||(v=await c.getTransactionReceipt({hash:b}),i.set(b,v));let z=ie({abi:U,eventName:"TokenLaunched",data:u.data,topics:u.topics}).args,L=se(v).filter(k=>p(k.token,z.token)&&p(k.poolId,z.poolId));if(L.length!==1)throw new a("The launch feed log does not match one verified receipt launch.");f.push({...L[0],launchTx:b,blockNumber:u.blockNumber.toString(),token:await te(L[0].token,t),creator:v.from})}let w=r+o;return{launches:f,cursor:w<d.length?`${n}:${t}:${w}`:null,fromBlock:n.toString(),toBlock:t.toString(),coverage:K,previousToBlock:n>H?(n-1n).toString():null,summary:"Newest launches first within this fixed block range. Empty does not establish absence outside the range or covered strategies."}}async function he(e,s,o){let n=await P(e);if(!n.creatorFees)throw new a("Creator fees are permanently disabled for this position.");let t=BigInt(n.positionId),r=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[t]});if(!p(r,h.feeSplitterFeesOn.address))throw new a("The position is not locked in its current-strategy splitter.");let d=await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[t]});if(!p(d,s))throw new a("Only the current fee NFT holder can change this entitlement.");let i=B(o?e.to:e.spender);if(p(i,S)||o&&p(i,C))throw new a("The fee NFT recipient cannot be the vault or zero address.");let f=o?N({abi:m,functionName:"safeTransferFrom",args:[s,i,t]}):N({abi:m,functionName:"approve",args:[i,t]});return T([y(S,f,0n,o?`Transfer fee NFT ${t} to ${i}, including accrued and future fees.`:`Approve ${i} for fee NFT ${t} only; zero address revokes approval.`)],s,o?`Transfer the entire fee entitlement for position ${t} to ${i}. This includes collected and future fees; locked LP remains in its splitter. No transaction sent.`:`Set the exact single-NFT approval for position ${t} to ${i}. This permits transfer of that fee entitlement; zero address revokes. No transaction sent.`)}async function Pe(){return{chainId:x,instant:{supported:!0,supply:ne.toString(),decimals:18,currency:ue,permanentCreatorFeeChoice:!0},crowd:{status:"BLOCKED",strategy:"0xbf1aB81f7d534b2CC0Da76fcf4d541322bB0e000",factory:"0x000000001F26a0044BaA66024e7b6599c61963F8",missing:"A verified Pools-specific auction configuration (BlockNumberish timing, reserve allocation, Q96 floor/tick, USD FDV conversion, issuance steps, locked LP plan) and a bytecode-matched factory-created auction ABI with success/refund fixtures. Generic CCA parameters are not a verified Pools Crowd Launch.",source:"https://github.com/Uniswap/sdks/blob/main/sdks/liquidity-launcher-sdk/src/addresses.ts"},coverage:K}}let g={type:"string"},I=ke(),ge={chainId:{type:"integer",const:x},slippageBps:{type:"integer",minimum:0,maximum:9999}};function A(e,s,o,n){return{name:`poolstrade_${e}`,inputSchema:{type:"object",additionalProperties:!1,properties:{...ge,...s},required:o},execute:async(t,r)=>{try{let d=new Set([...Object.keys(ge),...Object.keys(s)]);if(Object.keys(t).some(i=>!d.has(i)))throw new a("Unsupported input for this pools.trade tool.");if(t.chainId!==void 0&&t.chainId!==x)throw new a("pools.trade requires chain 4663.");if(B(r),t.slippageBps!==void 0){if(typeof t.slippageBps!="number")throw new a("Slippage must be an integer in basis points.");ae("10000",t.slippageBps)}return await j(),await n(t,r)}catch(d){F(d)}}}}return{tools:[A("launch",{name:g,symbol:g,creatorFees:{type:"boolean",description:"Permanent choice; must be explicit."},feeBeneficiary:g,pair:g,decimals:{type:"integer",const:18},supply:I,initialBuy:I,minAmountOut:I,description:g,website:g,imageUri:g},["name","symbol","creatorFees","feeBeneficiary"],O),...["buy","sell"].map(e=>A(e,{token:g,amountIn:I,minAmountOut:I,launchTx:g},["token","amountIn"],(s,o)=>G(s,o,e==="buy"))),A("collect",{positionId:I,launchTx:g},["positionId"],(e,s)=>pe(e,s,!1)),A("claim",{positionId:I,launchTx:g,minEth:I},["positionId"],(e,s)=>pe(e,s,!0)),A("browse",{fromBlock:I,toBlock:I,limit:{type:"integer",minimum:1,maximum:50},cursor:g},[],Fe),A("balance",{token:g,launchTx:g},["token"],Ce),A("status",{launchTx:g,token:g,positionId:I},["launchTx"],$e),A("launch_options",{},[],Pe),A("fee_transfer",{positionId:I,launchTx:g,to:g},["positionId","to"],(e,s)=>he(e,s,!0)),A("fee_approve",{positionId:I,launchTx:g,spender:g},["positionId","spender"],(e,s)=>he(e,s,!1)),A("transfer",{token:g,amount:I,to:g,launchTx:g},["token","amount","to"],Se),A("collect_many",{positionIds:{type:"array",items:I,minItems:1,maxItems:20},launchTxs:{type:"array",items:g,minItems:1,maxItems:20}},["positionIds","launchTxs"],Be)],positions:async e=>{B(e);let s=[],o=0,n=!0,t,r=i=>({module:"poolstrade",id:"poolstrade-discovery-incomplete",chainId:x,assets:[],incomplete:!0,description:`${i} Checked ${o} launch receipts. Readable holdings are retained. Check a known launch with poolstrade_status {"launchTx":"<hash>"} or its token holding with poolstrade_balance {"token":"<address>","launchTx":"<hash>"}. Crowd Launch and older deployments are outside this reader's coverage.`}),d=async()=>{await j(),n&&await ee(e,void 0,async i=>{o++;for(let f of se(i)){if(!n)return;let w=f.creatorFees&&p(await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[BigInt(f.positionId)]}),e);if(!n)return;if(!w&&!p(i.from,e))continue;let u=w?[{token:ue,amount:(await c.readContract({address:S,abi:m,functionName:"amounts",args:[BigInt(f.positionId)]}))[0].toString()}]:[];n&&s.push({module:"poolstrade",id:f.positionId,chainId:x,assets:u,description:`Current Instant Launch ${f.token} (18 decimals, supply 1000000000), pool ${f.poolId}; creator fees ${f.creatorFees?"on":"off"} (permanent). ${w?"Collected ETH fees only; uncollected fees excluded.":"Launch record; no fee entitlement held."} Liquidity is permanently locked.`})}},()=>n)};try{return await Promise.race([d().then(()=>!0),new Promise(f=>{t=setTimeout(()=>{n=!1,f(!1)},6e3)})])?s:[...s,r("Pools.trade global launch discovery reached its 6000 ms read budget; the historical scan is incomplete.")]}catch(i){return[...s,r(`Pools.trade discovery could not finish: ${l.plainError(i)}`)]}finally{n=!1,t!==void 0&&clearTimeout(t)}}}};function Ve(l){return Ie("poolstrade",[Ee(l)])}export{se as a,Ee as b,Ve as c};
1
+ import{b as xe,o as ae}from"./CAU44UWP.js";import{a as re}from"./VJ3W2V3B.js";import{b as Ie}from"./AXYOJBX6.js";import{a as Te}from"./EG6M6SSO.js";import{a as ke}from"./UWOFA6GV.js";import{e as W,g as p,i as ye,n as be}from"./73N3TOJL.js";import{a as x,i as we}from"./XPFVT2EA.js";import{a}from"./5YS5V2LK.js";import{decodeErrorResult as Oe,decodeEventLog as ie,encodeAbiParameters as D,encodeFunctionData as N,erc20Abi as Q,parseAbi as Ne,parseAbiParameters as M,toHex as Ae,zeroAddress as C}from"viem";var h=we[x].poolsTrade,J=h.liquidityLauncher.address,S=h.uerc20BeneficiaryVault.address,ce=h.universalRouter.address,ne=10n**27n,q=(1n<<128n)-1n,ve=`0x${"00".repeat(32)}`,H=63127652n,de=100000n,oe=10000000n,Le=2000n,ue={address:re,symbol:"ETH",decimals:18,chainId:x},m=Ne(["function multicall(bytes[] data) payable returns (bytes[])","function createToken(address factory,string name,string symbol,uint8 decimals,uint128 initialSupply,address recipient,bytes tokenData) payable returns (address)","function distributeToken(address token,(address strategy,uint128 amount,bytes configData) distribution,bytes32 salt) payable","function distributeWithNative(address strategy,bytes configData,bytes32 salt,uint256 nativeAmount) payable","function getGraffiti(address sender) view returns (bytes32)","function getUERC20Address(string name,string symbol,uint8 decimals,address recipient,bytes32 graffiti) view returns (address)","function execute(bytes commands,bytes[] inputs,uint256 deadline) payable","function collectFees(uint256[] ids)","function claim(uint256 id,uint256 minCurrency0Amount,uint256 minCurrency1Amount)","function amounts(uint256 id) view returns (uint128 eth,uint128 token)","function ownerOf(uint256 id) view returns (address)","function getApproved(uint256 id) view returns (address)","function approve(address spender,uint256 id)","function safeTransferFrom(address from,address to,uint256 id)","function approve(address token,address spender,uint160 amount,uint48 expiration)","error V4TooLittleReceived(uint256 minAmountOut,uint256 amountOut)"]),U=Ne(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)","event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"]),_=[h.instantLaunchStrategyFeesOn.address,h.instantLaunchStrategyFeesOff.address];function se(l){if(l.status!=="success")throw new a("The launch receipt did not succeed.");let c=[];for(let y of l.logs){let F=_.findIndex(O=>p(O,y.address));if(F===-1||y.topics[0]!=="0x3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4")continue;let j=ie({abi:U,eventName:"TokenLaunched",data:y.data,topics:[...y.topics]}),{token:T,poolId:Y,poolKey:R,feeSplitter:Z}=j.args,ee=F===0?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address;if(!p(Z,ee)||!p(R.currency0,C)||!p(R.currency1,T)||R.fee!==2500||R.tickSpacing!==25||!p(R.hooks,C))throw new a("The launch does not match the current native ETH strategy.");let P=l.logs.filter(O=>p(O.address,h.v4PositionManager.address)).flatMap(O=>{if(O.topics[0]!=="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")return[];let G=ie({abi:U,eventName:"Transfer",data:O.data,topics:[...O.topics]}).args;return p(G.from,C)&&p(G.to,_[F])?[G.tokenId]:[]});if(P.length!==1)throw new a("The launch receipt must identify one matching position mint.");c.push({token:T,poolId:Y,positionId:P[0].toString(),creatorFees:F===0})}return c}function B(l){return ye(l,"Provide a valid wallet or token address.")}function $(l,c,y=!1){return be(l,`${c} is outside its supported range.`,{notString:`${c} must be an integer string in base units.`,positive:!y})}function X(l,c,y=!1){if(y&&l===void 0)return"";if(typeof l!="string"||!y&&!l.trim()||l.length>4096)throw new a(`Provide a valid ${c}.`);return l}function le(l){if(typeof l!="string"||!/^0x[0-9a-fA-F]{64}$/.test(l))throw new a("Provide a valid launch transaction hash.");return l}function fe(l,c,y="minAmountOut"){let F=c.slippageBps??xe;if(typeof F!="number")throw new a("Slippage must be an integer in basis points.");let j=ae(l.toString(),F),T=c[y]===void 0?BigInt(j):$(c[y],y,l===0n);if(T>l||l>0n&&T===0n||T>q)throw new a("The minimum output must be positive and no larger than the simulated output.");return T}var Ee=l=>{let c=l.clientFor(x),y=(e,s,o,n)=>l.unsignedTx({to:e,data:s,value:o.toString(),chainId:x,description:n}),F=e=>{throw new a(l.plainError(e))};async function j(){if(await c.getChainId()!==x)throw new a("pools.trade requires Robinhood Chain 4663.")}async function T(e,s,o){let n=await l.preview(e,s),t=n.changes.map(({token:r,amount:d})=>{let i=d.startsWith("-");return`${i?"-":""}${l.formatAmount(i?d.slice(1):d,r.decimals)} ${r.symbol} (${r.address}, chain ${r.chainId})`});return{txs:e,summary:[o,n.summary,...t].join(" ")}}async function Y(){return(await c.getBlock()).timestamp+600n}function R(e,s,o,n,t,r){let d=[C,e,2500,25,C],i=[D(M("((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"),[[d,s,o,n,0n,"0x"]]),D(M("address,uint256"),[s?C:e,o]),D(M("address,address,uint256"),[s?e:C,t,0n])],f=[D(M("bytes,bytes[]"),["0x060c0e",i])];return{inputs:f,encoded:D(M("bytes,bytes[],uint256"),["0x10",f,r])}}async function Z(e,s){let o=await c.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:s,gas:Ae(Te),to:i.to,data:i.data,value:Ae(BigInt(i.value))}))}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(o)||o.length!==1||!W(o[0])||!Array.isArray(o[0].calls)||o[0].calls.length!==e.length)throw new a("The output simulation returned a malformed response.");let n=o[0].calls;if(!n.slice(0,-1).every(i=>W(i)&&i.status==="0x1"&&!i.error))throw new a("A prerequisite failed during the output simulation.");let t=n.at(-1);if(!W(t)||t.status!=="0x0")throw new a("The output simulation did not return the expected minimum-output control.");let r=typeof t.returnData=="string"&&t.returnData!=="0x"?t.returnData:W(t.error)?t.error.data:void 0;if(typeof r!="string"||!/^0x[0-9a-fA-F]+$/.test(r))throw new a("The output simulation did not report an expected amount.");let d=Oe({abi:m,data:r});if(d.errorName!=="V4TooLittleReceived"||d.args[0]!==q||d.args[1]<=0n||d.args[1]>=q)throw new a("The output simulation did not report a valid amount.");return d.args[1]}async function ee(e,s,o,n=()=>!0){let t=await c.getBlockNumber(),r=t<H?0n:(t-H)/oe+1n,d=1n,i=(u=1n)=>{if(d+=u,d>Le)throw new a("Pools.trade scan exceeds the 2000-request limit. Use launchTx for a specific launch; positions coverage is incomplete.")};i(r*BigInt(_.length+(e&&!o?1:0)));let f=new Map,w=new Set;for(let u=H;u<=t&&n();u+=oe){let b=u+oe-1n>t?t:u+oe-1n,v=(await Promise.all(_.map(k=>c.getLogs({address:k,event:U[0],...s?{args:{token:s}}:{},fromBlock:u,toBlock:b,strict:!0})))).flat(),L=[...new Set(v.map(k=>k.transactionHash))].filter(k=>!k||!f.has(k));for(let k=0;k<L.length&&n();k+=8)await Promise.all(L.slice(k,k+8).map(async E=>{if(!E)throw new a("A launch log is missing its transaction hash.");i();let V=await c.getTransactionReceipt({hash:E});f.set(E,V),n()&&await o?.(V)}));if(!n())break;if(e&&!o){let k=await c.getLogs({address:S,event:U[1],args:{to:e},fromBlock:u,toBlock:b,strict:!0});for(let E of k){let V=ie({abi:U,eventName:"Transfer",data:E.data,topics:E.topics}).args;w.add(V.tokenId.toString())}}}return{receipts:[...f.values()],feeIds:w}}async function P(e){let o=(e.launchTx!==void 0?[await c.getTransactionReceipt({hash:le(e.launchTx)})]:(await ee(void 0,e.token===void 0?void 0:B(e.token))).receipts).flatMap(se).filter(n=>e.positionId!==void 0?n.positionId===$(e.positionId,"positionId").toString():p(n.token,B(e.token)));if(o.length!==1)throw new a("No unique current-strategy launch was found. Older strategy generations are unsupported.");return o[0]}async function O(e,s){if(typeof e.creatorFees!="boolean")throw new a("creatorFees must be an explicit boolean; the choice is permanent.");if(e.pair!==void 0&&!p(B(e.pair),C)&&!p(B(e.pair),re))throw new a("Only the native ETH pair is supported.");if(e.decimals!==void 0&&e.decimals!==18)throw new a("Instant Launch requires 18 decimals.");if(e.supply!==void 0&&$(e.supply,"supply")!==ne)throw new a("Instant Launch requires a supply of one billion tokens.");let o=B(e.feeBeneficiary);if(p(o,C)||p(o,J))throw new a("The fee beneficiary must be a wallet other than the launcher or zero address.");let n=X(e.name,"name"),t=X(e.symbol,"symbol"),r=e.initialBuy===void 0?0n:$(e.initialBuy,"initialBuy",!0);if(r>q)throw new a("The initial buy exceeds uint128.");if(r===0n&&e.minAmountOut!==void 0)throw new a("A minimum output requires an initial buy.");let d=await c.readContract({address:J,abi:m,functionName:"getGraffiti",args:[s]}),i=B(await c.readContract({address:h.uerc20Factory.address,abi:m,functionName:"getUERC20Address",args:[n,t,18,J,d]})),f=await c.getCode({address:i});if(f&&f!=="0x")throw new a("This wallet already launched that name and symbol.");let w=D(M("(string,string,string,bytes)"),[[X(e.description,"description",!0),X(e.website,"website",!0),X(e.imageUri,"image URI",!0),"0x"]]),u=e.creatorFees?_[0]:_[1],b=[N({abi:m,functionName:"createToken",args:[h.uerc20Factory.address,n,t,18,ne,J,w]}),N({abi:m,functionName:"distributeToken",args:[i,{strategy:u,amount:ne,configData:D(M("address"),[o])},ve]})],v=await Y(),z=k=>{let E=[...b];if(r>0n){let V=D(M("(address,address,bytes)"),[[ce,s,R(i,!0,r,k,s,v).encoded]]);E.push(N({abi:m,functionName:"distributeWithNative",args:[h.universalRouterStrategyApp.address,V,ve,r]}))}return y(J,N({abi:m,functionName:"multicall",args:[E]}),r,`Atomic Instant Launch: creator fees ${e.creatorFees?"on":"off"} (permanent); beneficiary ${o}.`)},L=r>0n?fe(await Z([z(q)],s),e):0n;return T([z(L)],s,`Launch ${n} (${i}, chain 4663), supply 1000000000, decimals 18. Creator fees ${e.creatorFees?"on":"off"} are permanent; fee beneficiary ${o}. Creator ETH fees come from buys only (recorded 0.09996%); sells compound into locked liquidity. Initial-buy minimum ${L} token base units. Off-chain image/display unproven; no private metadata registration. No transaction sent.`)}async function G(e,s,o){let n=$(e.amountIn,"amountIn");if(n>q)throw new a("The trade amount exceeds uint128.");let t=B(e.token);await P(e);let r=await Y(),d=[];o||(await c.readContract({address:t,abi:Q,functionName:"allowance",args:[s,h.permit2.address]})<n&&d.push(l.approval(t,h.permit2.address,n.toString(),x)),d.push(y(h.permit2.address,N({abi:m,functionName:"approve",args:[t,ce,n,Number(r)]}),0n,`Permit the exact ${n} token base units until ${r}.`)));let i=u=>[...d,y(ce,N({abi:m,functionName:"execute",args:["0x10",R(t,o,n,u,s,r).inputs,r]}),o?n:0n,`${o?"Buy":"Sell"} ${t} with minimum output ${u}.`)],f=await Z(i(q),s),w=fe(f,e);return T(i(w),s,`${o?"Buy":"Sell"} token ${t} (chain 4663, 18 decimals), amountIn ${n}, minimum output ${w} ${o?"token":"ETH"} base units (18 decimals). Recorded swap fee 0.2899%; creator ETH fees from buys only, none from sells. No transaction sent.`)}async function pe(e,s,o){let n=await P(e),t=BigInt(n.positionId),r=n.creatorFees?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address,d=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[t]});if(!p(d,r))throw new a("The position is not locked in its current-strategy splitter.");if(!o)return T([y(r,N({abi:m,functionName:"collectFees",args:[[t]]}),0n,`Collect fees for position ${t}; permissionless.`)],s,"Collect fees for the entitled recipients; collection does not transfer creator fees to the collector. No transaction sent.");if(!n.creatorFees)throw new a("Creator fees are permanently disabled for this position.");let i=await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[t]});if(!p(i,s))throw new a("Only the current fee NFT holder is entitled to claim.");let f=await c.readContract({address:S,abi:m,functionName:"amounts",args:[t]}),w=fe(f[0],e,"minEth");if(f[1]!==0n)throw new a("The current buy-only creator fee configuration returned unexpected token fees.");return T([y(S,N({abi:m,functionName:"claim",args:[t,w,0n]}),0n,`Claim collected ETH fees for position ${t} to ${s}.`)],s,`Claim collected fees: ${f[0]} ETH base units (18 decimals), minimum ${w}. Uncollected fees require poolstrade_collect first. No transaction sent.`)}async function Se(e,s){let o=await P(e),n=B(e.to);if(p(n,C))throw new a("The token recipient cannot be the zero address.");let t=$(e.amount,"amount"),r=await te(o.token,await c.getBlockNumber());return T([y(r.address,N({abi:Q,functionName:"transfer",args:[n,t]}),0n,`Transfer exactly ${t} ${r.symbol} base units to ${n}.`)],s,`Transfer ${t} token base units (token ${r.address}, decimals ${r.decimals}, chain ${r.chainId}) to ${n}. No approval; no transaction sent.`)}async function Be(e,s){if(!Array.isArray(e.positionIds)||e.positionIds.length<1||e.positionIds.length>20||!Array.isArray(e.launchTxs)||e.launchTxs.length!==e.positionIds.length)throw new a("Provide 1 to 20 positionIds and one matching launchTxs entry for each.");let o=e.positionIds.map(d=>$(d,"positionId").toString());if(new Set(o).size!==o.length)throw new a("Each position ID must appear once.");let n=e.launchTxs.map(le),t=new Map;for(let[d,i]of o.entries()){let w=(await P({positionId:i,launchTx:n[d]})).creatorFees?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address,u=BigInt(i),b=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[u]});if(!p(b,w))throw new a("The position is not locked in its current-strategy splitter.");t.set(w,[...t.get(w)??[],u])}let r=[...t].map(([d,i])=>y(d,N({abi:m,functionName:"collectFees",args:[i]}),0n,`Collect fees for positions ${i.join(", ")}; permissionless.`));return T(r,s,"Collect fees in batches for the fixed entitled recipients. Collection does not pay the collector. No transaction sent.")}let K="Current native ETH Instant Launch strategies only. Crowd Launch and older deployments are not covered.";async function te(e,s){let[o,n]=await Promise.all([c.readContract({address:e,abi:Q,functionName:"symbol",blockNumber:s}),c.readContract({address:e,abi:Q,functionName:"decimals",blockNumber:s})]);if(typeof o!="string"||!o||o.length>256||n!==18)throw new a("The current launch token returned invalid metadata.");return{address:e,symbol:o,decimals:n,chainId:x}}async function me(e,s,o,n){let t=n??await te(e.token,o),r=await c.readContract({address:t.address,abi:Q,functionName:"balanceOf",args:[s],blockNumber:o});return{token:t,amount:r.toString(),humanAmount:l.formatAmount(r.toString(),t.decimals)}}async function Ce(e,s){let o=await P(e),n=await c.getBlockNumber();return{wallet:s,...await me(o,s,n),blockNumber:n.toString(),coverage:K}}async function $e(e,s){let o=le(e.launchTx),n=await c.getTransactionReceipt({hash:o}),t=se(n);if(e.token!==void 0&&(t=t.filter(i=>p(i.token,B(e.token)))),e.positionId!==void 0&&(t=t.filter(i=>i.positionId===$(e.positionId,"positionId").toString())),!t.length)throw new a("The receipt contains no matching current Instant Launch. Crowd Launch and older strategies are not covered.");let r=await c.getBlockNumber(),d=await Promise.all(t.map(async i=>{let f=i.creatorFees?h.feeSplitterFeesOn.address:h.feeSplitterFeesOff.address,w=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:r});if(!p(w,f))throw new a("The position is not locked in its current-strategy splitter.");let u=i.creatorFees?{owner:await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:r}),approved:await c.readContract({address:S,abi:m,functionName:"getApproved",args:[BigInt(i.positionId)],blockNumber:r}),collected:await c.readContract({address:S,abi:m,functionName:"amounts",args:[BigInt(i.positionId)],blockNumber:r})}:void 0,b=await te(i.token,r);return{...i,token:b,custodian:w,holding:await me(i,s,r,b),...u?{feeEntitlement:{owner:u.owner,approved:u.approved,collected:[{token:ue,amount:u.collected[0].toString()},{token:b,amount:u.collected[1].toString()}],uncollectedFeesIncluded:!1}}:{}}}));return{launchTx:o,wallet:s,creator:n.from,blockNumber:r.toString(),launches:d,coverage:K}}async function Fe(e){let s=await c.getBlockNumber(),o=e.limit??20;if(typeof o!="number"||!Number.isInteger(o)||o<1||o>50)throw new a("limit must be an integer from 1 to 50.");let n=e.fromBlock===void 0?s>=H+de?s-de+1n:H:$(e.fromBlock,"fromBlock",!0),t=e.toBlock===void 0?s:$(e.toBlock,"toBlock",!0),r=0;if(e.cursor!==void 0){if(typeof e.cursor!="string"||!/^[0-9]{1,78}:[0-9]{1,78}:[0-9]{1,10}$/.test(e.cursor))throw new a("Provide the browse cursor exactly as returned.");let u=e.cursor.split(":"),b=BigInt(u[0]),v=BigInt(u[1]);if(e.fromBlock!==void 0&&n!==b||e.toBlock!==void 0&&t!==v)throw new a("The cursor does not match this block range.");n=b,t=v,r=Number(u[2])}if(s<H&&e.fromBlock===void 0&&e.toBlock===void 0&&e.cursor===void 0)return{launches:[],cursor:null,fromBlock:H.toString(),toBlock:s.toString(),coverage:K,predeployment:!0};if(n<H||t<n||t>s||t-n>=de)throw new a("Choose a deployed block range of at most 100000 blocks, ending no later than the current head.");let d=await c.getLogs({address:_,event:U[0],fromBlock:n,toBlock:t,strict:!0});if(d.some(u=>u.blockNumber===null||u.logIndex===null||!u.transactionHash))throw new a("The launch feed returned an incomplete log.");if(d.sort((u,b)=>u.blockNumber===b.blockNumber?b.logIndex-u.logIndex:u.blockNumber>b.blockNumber?-1:1),r>d.length)throw new a("The browse cursor is outside the launch feed.");let i=new Map,f=[];for(let u of d.slice(r,r+o)){let b=u.transactionHash,v=i.get(b);v||(v=await c.getTransactionReceipt({hash:b}),i.set(b,v));let z=ie({abi:U,eventName:"TokenLaunched",data:u.data,topics:u.topics}).args,L=se(v).filter(k=>p(k.token,z.token)&&p(k.poolId,z.poolId));if(L.length!==1)throw new a("The launch feed log does not match one verified receipt launch.");f.push({...L[0],launchTx:b,blockNumber:u.blockNumber.toString(),token:await te(L[0].token,t),creator:v.from})}let w=r+o;return{launches:f,cursor:w<d.length?`${n}:${t}:${w}`:null,fromBlock:n.toString(),toBlock:t.toString(),coverage:K,previousToBlock:n>H?(n-1n).toString():null,summary:"Newest launches first within this fixed block range. Empty does not establish absence outside the range or covered strategies."}}async function he(e,s,o){let n=await P(e);if(!n.creatorFees)throw new a("Creator fees are permanently disabled for this position.");let t=BigInt(n.positionId),r=await c.readContract({address:h.v4PositionManager.address,abi:m,functionName:"ownerOf",args:[t]});if(!p(r,h.feeSplitterFeesOn.address))throw new a("The position is not locked in its current-strategy splitter.");let d=await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[t]});if(!p(d,s))throw new a("Only the current fee NFT holder can change this entitlement.");let i=B(o?e.to:e.spender);if(p(i,S)||o&&p(i,C))throw new a("The fee NFT recipient cannot be the vault or zero address.");let f=o?N({abi:m,functionName:"safeTransferFrom",args:[s,i,t]}):N({abi:m,functionName:"approve",args:[i,t]});return T([y(S,f,0n,o?`Transfer fee NFT ${t} to ${i}, including accrued and future fees.`:`Approve ${i} for fee NFT ${t} only; zero address revokes approval.`)],s,o?`Transfer the entire fee entitlement for position ${t} to ${i}. This includes collected and future fees; locked LP remains in its splitter. No transaction sent.`:`Set the exact single-NFT approval for position ${t} to ${i}. This permits transfer of that fee entitlement; zero address revokes. No transaction sent.`)}async function Pe(){return{chainId:x,instant:{supported:!0,supply:ne.toString(),decimals:18,currency:ue,permanentCreatorFeeChoice:!0},crowd:{status:"BLOCKED",strategy:"0xbf1aB81f7d534b2CC0Da76fcf4d541322bB0e000",factory:"0x000000001F26a0044BaA66024e7b6599c61963F8",missing:"A verified Pools-specific auction configuration (BlockNumberish timing, reserve allocation, Q96 floor/tick, USD FDV conversion, issuance steps, locked LP plan) and a bytecode-matched factory-created auction ABI with success/refund fixtures. Generic CCA parameters are not a verified Pools Crowd Launch.",source:"https://github.com/Uniswap/sdks/blob/main/sdks/liquidity-launcher-sdk/src/addresses.ts"},coverage:K}}let g={type:"string"},I=ke(),ge={chainId:{type:"integer",const:x},slippageBps:{type:"integer",minimum:0,maximum:9999}};function A(e,s,o,n){return{name:`poolstrade_${e}`,inputSchema:{type:"object",additionalProperties:!1,properties:{...ge,...s},required:o},execute:async(t,r)=>{try{let d=new Set([...Object.keys(ge),...Object.keys(s)]);if(Object.keys(t).some(i=>!d.has(i)))throw new a("Unsupported input for this pools.trade tool.");if(t.chainId!==void 0&&t.chainId!==x)throw new a("pools.trade requires chain 4663.");if(B(r),t.slippageBps!==void 0){if(typeof t.slippageBps!="number")throw new a("Slippage must be an integer in basis points.");ae("10000",t.slippageBps)}return await j(),await n(t,r)}catch(d){F(d)}}}}return{tools:[A("launch",{name:g,symbol:g,creatorFees:{type:"boolean",description:"Permanent choice; must be explicit."},feeBeneficiary:g,pair:g,decimals:{type:"integer",const:18},supply:I,initialBuy:I,minAmountOut:I,description:g,website:g,imageUri:g},["name","symbol","creatorFees","feeBeneficiary"],O),...["buy","sell"].map(e=>A(e,{token:g,amountIn:I,minAmountOut:I,launchTx:g},["token","amountIn"],(s,o)=>G(s,o,e==="buy"))),A("collect",{positionId:I,launchTx:g},["positionId"],(e,s)=>pe(e,s,!1)),A("claim",{positionId:I,launchTx:g,minEth:I},["positionId"],(e,s)=>pe(e,s,!0)),A("browse",{fromBlock:I,toBlock:I,limit:{type:"integer",minimum:1,maximum:50},cursor:g},[],Fe),A("balance",{token:g,launchTx:g},["token"],Ce),A("status",{launchTx:g,token:g,positionId:I},["launchTx"],$e),A("launch_options",{},[],Pe),A("fee_transfer",{positionId:I,launchTx:g,to:g},["positionId","to"],(e,s)=>he(e,s,!0)),A("fee_approve",{positionId:I,launchTx:g,spender:g},["positionId","spender"],(e,s)=>he(e,s,!1)),A("transfer",{token:g,amount:I,to:g,launchTx:g},["token","amount","to"],Se),A("collect_many",{positionIds:{type:"array",items:I,minItems:1,maxItems:20},launchTxs:{type:"array",items:g,minItems:1,maxItems:20}},["positionIds","launchTxs"],Be)],positions:async e=>{B(e);let s=[],o=0,n=!0,t,r=i=>({module:"poolstrade",id:"poolstrade-discovery-incomplete",chainId:x,assets:[],incomplete:!0,description:`${i} Checked ${o} launch receipts. Readable holdings are retained. Check a known launch with poolstrade_status {"launchTx":"<hash>"} or its token holding with poolstrade_balance {"token":"<address>","launchTx":"<hash>"}. Crowd Launch and older deployments are outside this reader's coverage.`}),d=async()=>{await j(),n&&await ee(e,void 0,async i=>{o++;for(let f of se(i)){if(!n)return;let w=f.creatorFees&&p(await c.readContract({address:S,abi:m,functionName:"ownerOf",args:[BigInt(f.positionId)]}),e);if(!n)return;if(!w&&!p(i.from,e))continue;let u=w?[{token:ue,amount:(await c.readContract({address:S,abi:m,functionName:"amounts",args:[BigInt(f.positionId)]}))[0].toString()}]:[];n&&s.push({module:"poolstrade",id:f.positionId,chainId:x,assets:u,description:`Current Instant Launch ${f.token} (18 decimals, supply 1000000000), pool ${f.poolId}; creator fees ${f.creatorFees?"on":"off"} (permanent). ${w?"Collected ETH fees only; uncollected fees excluded.":"Launch record; no fee entitlement held."} Liquidity is permanently locked.`})}},()=>n)};try{return await Promise.race([d().then(()=>!0),new Promise(f=>{t=setTimeout(()=>{n=!1,f(!1)},6e3)})])?s:[...s,r("Pools.trade global launch discovery reached its 6000 ms read budget; the historical scan is incomplete.")]}catch(i){return[...s,r(`Pools.trade discovery could not finish: ${l.plainError(i)}`)]}finally{n=!1,t!==void 0&&clearTimeout(t)}}}};function Ve(l){return Ie("poolstrade",[Ee(l)])}export{se as a,Ee as b,Ve as c};