@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,4 +1,4 @@
1
- import{a as ae}from"./3CCBUYUM.js";import{a as bt,d as wt,e as ht}from"./L24EOVLT.js";import{a as Ne}from"./7MR37STI.js";import{a as We,b as Be,d as pt}from"./EC5W3UZD.js";import{b as ut,c as mt,d as ft}from"./HZUWK5B2.js";import{d as ct,e as te}from"./EAEQOS7Y.js";import{a as dt}from"./XCFA73P2.js";import{b as lt}from"./AXYOJBX6.js";import{a as q}from"./6IM6A5VA.js";import{a as A,d as z}from"./UWOFA6GV.js";import{d as De,g as E,i as Ue}from"./73N3TOJL.js";import{a as Me}from"./RETS2ZEK.js";import{j as it}from"./IWALIX7Q.js";import{a as p,i as V}from"./XPFVT2EA.js";import{a as i,d as se}from"./5YS5V2LK.js";import{a as ze}from"./JXOEJPJ4.js";import{encodeFunctionData as me,erc20Abi as Ha,getAddress as Kt,parseAbi as st,zeroAddress as qa}from"viem";import{decodeAbiParameters as aa,encodeFunctionData as oa,getAddress as ie,parseAbiParameters as ra,zeroAddress as fe,zeroHash as It}from"viem";import{decodeAbiParameters as Xt,encodeFunctionData as Yt,erc20Abi as Jt,getAddress as St,parseAbi as Zt,parseAbiParameters as ea,zeroHash as kt}from"viem";var Ke=St("0xCE29862924756584BBD0D75CA1249d22007E2813"),At="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",ta="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",yt=Zt(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${At}[] marketParamsList,uint256 exitAssets,${ta} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var gt=(e,t)=>e<t?e:t;async function Za(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),d=e.clientFor(p),m=await pt(d,t,s),c=(S,B,Te,ee=[])=>d.readContract({address:S,abi:B,functionName:Te,args:ee,blockNumber:m.blockNumber}),[f,b,w,h]=await Promise.all([d.getBlock({blockNumber:m.blockNumber}),c(Ke,yt,"BLUE"),c(t,Jt,"balanceOf",[n]),c(t,We,"previewRedeem",[a])]);if(typeof b!="string"||St(b)!==U)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<f.timestamp||u>f.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Be(w))throw new i("maxShares exceeds the wallet share balance.");let y=gt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&W(S.id)),g=l-y,T=k[0]?.penalty??0n,I=g*10n**18n/(10n**18n+T);if(g>0n&&I===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(I===0n)break;let B=gt(S.supplied,I);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),I-=B}if(I>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Be(h))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let v=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],G=(await Promise.all(v.map(S=>c(t,We,"previewWithdraw",[S])))).reduce((S,B)=>S+Be(B),0n);if(G===0n||G>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>Xt(ea(At),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${G} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,P=Yt({abi:yt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:kt,s:kt},u]}),D=[e.approval(t,Ke,G.toString(),p),e.unsignedTx({to:Ke,data:P,value:"0",chainId:p,description:F})],$=await e.preview(D,n),j=-$.changes.filter(S=>S.token.chainId===p&&E(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(j<=0n||j>G)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:D,preview:$,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var pe=ie("0x53A1eB6589861F686af7c531211E35Aefe30210f"),xt=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],Qe={kind:0,data:"0x"},Oe={nonce:0n,deadline:0n,signature:{v:0,r:It,s:It}},na=ra("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),Tt=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:xt},marketId:{type:"string"},destinationMarketId:{type:"string"},assets:A(),collateralAssets:A(),shares:A(),maxRepayAssets:A(),maxLtv:A(),deadline:A(),allocations:{type:"array",maxItems:4,items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string"},sourceMarketId:{type:"string"},assets:A(),maxPenaltyAssets:A()}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(p);if(await n.getChainId()!==p||typeof r!="string"||!xt.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(P=>!l.includes(P)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,d]=await Promise.all([n.readContract({address:pe,abi:Ne,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:pe,abi:Ne,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(ie(u)!==U||ie(d)!==bt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async P=>{if(typeof P!="string"||!W(P))throw new i("Choose a verified Morpho market with a supported exit.");let D=await n.readContract({address:U,abi:O,functionName:"idToMarketParams",args:[P],blockNumber:a.number}),$={loanToken:ie(D[0]),collateralToken:ie(D[1]),oracle:ie(D[2]),irm:ie(D[3]),lltv:D[4]};if(!E(be({...$,lltv:String($.lltv)}),P))throw new i("Blue bundle market identity mismatch.");return $},c=await m(t.marketId),f=r==="migrateBorrowPosition"?await m(t.destinationMarketId):c;if(c.loanToken!==f.loanToken||c.collateralToken!==f.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:U,abi:O,functionName:"isAuthorized",args:[s,pe],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${pe}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),w=t.shares===void 0?0n:N(t.shares,!0),h=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>f.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(w===0n)||r==="supplyCollateralAndBorrow"&&h===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&w>0n||b===0n&&w===0n&&h===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],I=0n;for(let P of k){if(!P||typeof P!="object"||Array.isArray(P)||Object.keys(P).some(Ve=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Ve)))throw new i("Unsupported bundled allocation input.");let D=P,$=await wt(e,{vault:D.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has($.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add($.definition.vault.toLowerCase());let j=N(D.assets),S=N(D.maxPenaltyAssets,!0);if(!$.permission||j>=1n<<128n||j>$.headroom||$.penalty>10n**18n||$.asset.address!==f.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(j*$.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");I+=B;let Te=D.sourceMarketId===void 0,ee=Te?void 0:$.sources.find(Ve=>E(Ve.id,String(D.sourceMarketId)));if(Te?!$.canIdle||j>$.data.idle:!ee||!ee.canPull||j>ee.capacity||j>$.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:$.definition.vault,adapter:$.target.adapter,marketParams:$.params,sourceAdapter:ee?.adapter??fe,sourceMarketParams:ee?aa(na,ee.data)[0]:$.params,assets:j,penalty:$.penalty,fromIdle:Te})}let M,C,v,x=0n;if(r==="supply")M="blueBundlesV1Supply",v=c.loanToken,x=b,C=[c,b,Qe,0n,fe,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[c,b,w,Oe,T,0n,fe,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",v=c.collateralToken,x=h,I>=b&&I>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[c,h,b,y,Qe,Oe,T,0n,fe,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",v=c.loanToken,x=N(t.maxRepayAssets,!0),b>x||w>0n&&x===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[c,b,w,x,h,y,Qe,Oe,0n,fe,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[c,f,y,Oe,T,0n,fe,o];let G=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${I} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${x}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...v&&x?[e.approval(v,pe,x.toString(),p)]:[],e.unsignedTx({to:pe,data:oa({abi:Ne,functionName:M,args:C}),value:"0",chainId:p,description:G})],H=await e.preview(Z,s),F=new Map;for(let P of H.changes)if(BigInt(P.amount)<0n){let D=P.token.address.toLowerCase();F.set(D,(F.get(D)??0n)-BigInt(P.amount))}if([...F].some(([P,D])=>!v||P!==v.toLowerCase()||D>x))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:G}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Mt,decodeAbiParameters as sa,encodeAbiParameters as $t,encodeFunctionData as Xe,erc20Abi as Pt,getAddress as K,keccak256 as Je,zeroAddress as we,zeroHash as ia}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),la=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),Ze=ae.find(e=>e.name==="take"),vt=[Ze.inputs[0]],da=[Ze.inputs[0].components[0]];function Ct(e){let t=Je(Mt(["0x600b380380600b5f395ff3",$t(da,[e])]));return Je(Mt(["0xff",e.midnight,ia,t]))}var le=10n**18n,Lt=(e,t)=>(e+(t-1n)/2n)/t;function Dt(e){if(e<0n)return 10n**36n/Dt(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*le),l=n*r/(3n*le);return le+r+n+l<<s}function ca(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Lt(Lt(10n**36n,le+Dt(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function Ge(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function Ye(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ua=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ut=e=>{async function t(n,l){let a=Ge(n,32),o=e.clientFor(p);if(await o.getChainId()!==p)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),d=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await d("toMarket",[a]);if(m.chainId!==BigInt(p)||K(m.midnight)!==Y||!E(Ct(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![V[p].tokens.USDG.address,V[p].tokens.WETH.address].some(k=>E(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[f,b,w,h]=await Promise.all([d("position",[a,l]),d("updatePositionView",[m,a,l]),d("marketState",[a]),d("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Pt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Pt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:p}};return{id:a,rpc:o,block:u,market:m,read:d,token:y,loan:await y(m.loanToken),position:Ye(f,6),updated:Ye(b,3),state:Ye(w,13),healthy:h}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,d)=>{try{if(q(d),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,d)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string"}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,c)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(c)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],d=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,c)=>[m,K(String(d[c]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:p,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ua(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string"},units:A(),maxAssets:A(),minAssets:A()},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=Ge(n.offer),[o]=sa(vt,a);if(!E($t(vt,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Ct(o.market),l),d=N(n.units),m=N(n.maxAssets,!0),c=N(n.minAssets,!0),f=Ge(n.ratifierData);if(d>=1n<<128n||E(o.maker,l)||o.callback!==we||o.callbackData!=="0x"||!la.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==we||!o.buy&&o.receiverIfMakerIsSeller===we)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&d>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),w=ca(o.tick);if(b>w&&o.buy)throw new i("Settlement fee exceeds the offer price.");let h=o.buy?w-b:w,y=h+b,k=P=>o.buy?P/le:(P+le-1n)/le,g=k(d*y),T=k(d*h);if(o.buy?T<c||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let I=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||I+(o.maxAssets?o.buy?g:T:d)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[Ze.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],v=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,f,l],blockNumber:u.block.number});if(M!==!0||v!==Je(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let x=Xe({abi:ae,functionName:"take",args:[o,f,d,l,o.buy?l:we,we,"0x"]}),G=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${d} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),p)],e.unsignedTx({to:Y,data:x,value:"0",chainId:p,description:G})],H=await r(Z,l,G),F=H.preview.changes.filter(P=>P.token.chainId===p&&E(P.token.address,u.loan.address)).reduce((P,D)=>P+BigInt(D.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string"},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"]},amount:A(),collateralIndex:{type:"integer",minimum:0,maximum:127}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,d,m=a.loan,c=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(c=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,c,l]}else{if(c=N(n.amount),c>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let w=BigInt(String(n.collateralIndex)),h=await a.token(a.market.collateralParams[Number(w)].token);if(m=h,o==="withdrawCollateral"&&c>await a.read("collateral",[a.id,l,w]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,w,c,l]:[a.market,w,c,l,l],o==="supplyCollateral"&&(d=h)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&c>a.position[4]||o==="withdraw"&&(c>a.updated[0]||c>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,c,l,we,"0x"]:[a.market,c,l,l],o==="repay"&&(d=a.loan)}}let f=`Midnight ${o}: ${c} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...d?[e.approval(d.address,Y,c.toString(),p)]:[],e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:String(o),args:u}),value:"0",chainId:p,description:f})];return r(b,l,f)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"]},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(f=>f.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let d=e.clientFor(p);if(await d.getChainId()!==p)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((f,b)=>{let w=n.values[b];if(f.type==="bool"){if(typeof w!="boolean")throw new i("Use boolean management values.");return w}if(f.type==="address")return Ue(w,"Use explicit management addresses.",De);if(f.type==="bytes32")return Ge(w,32);if(/^uint/.test(f.type)){let h=N(w,!0);if(h>=1n<<BigInt(f.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return h}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!E(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let f=await d.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof f!="string"||K(f)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let c=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:o,args:m}),value:"0",chainId:p,description:c})],l,c)})]}};import{decodeAbiParameters as oe,encodeAbiParameters as ma,encodeFunctionData as R,erc20Abi as et,getAddress as L,isAddress as Re,keccak256 as fa,parseAbi as Ee,parseAbiParameters as J}from"viem";var Pe="morpho",pa="https://api.morpho.org/graphql",U=L(V[p].morpho.morpho_blue.address),ba=L(V[p].morpho.adaptive_curve_irm.address),wa=L(V[p].morpho.USDG.address),de=L(V[p].morpho.WETH.address),ha=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],ka={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},tt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],ya=new Map(tt.map(e=>[e.marketId.toLowerCase(),e]));function W(e){return ya.get(e.toLowerCase())}function ot(e){let t=W(e);return t?{actions:"enabled",label:t.label,source:ka[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var Bt=20,ve=120n,_e=1000000n,He=1n,he=10n**18n,ga=10n**36n,Et=(1n<<128n)-1n,Sa=(1n<<256n)-1n,X=Ee(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),Aa=Ee(["function price() view returns (uint256)"]),Ia=Ee(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_t=Ee(["function deposit() payable"]);function ce(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ce(e,t){return e===0n?0n:(e+t-1n)/t}function xa(e,t,s){return e*(s+_e)/(t+He)}function Ta(e,t,s){return Ce(e*(s+_e),t+He)}function rt(e,t,s){return e*(t+He)/(s+_e)}function ne(e,t,s){return Ce(e*(t+He),s+_e)}function ke(e,t,s){return e*t/ga*s/he}function Ma(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function ye(e,t){let s=[],r={};for(let n of t.changes){let l=Ma(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Ht(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function qe(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Re(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Me(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=he)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function be(e){let t=qe(e),s=ma(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return fa(s)}function at(e){let t=e.toLowerCase();return t===dt.toLowerCase()||t===ct.toLowerCase()||t===te.toLowerCase()}function ge(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function re(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function qt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=p){if(q(t),at(t))return{...ut,chainId:s};let r=L(t),n=r.toLowerCase();if(s===p){if(n===wa.toLowerCase())return mt;if(n===de.toLowerCase())return ft}let[l,a]=await Promise.all([re(e,r,R({abi:et,functionName:"symbol"})),re(e,r,R({abi:et,functionName:"decimals"}))]),[o]=oe(J("string"),l),[u]=oe(J("uint8"),a);return{address:r,symbol:qt(o),decimals:Number(u),chainId:s}}async function Ft(e,t){let s=await re(e,U,R({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=oe(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function jt(e,t){let s=await re(e,U,R({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=oe(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Se(e,t,s){let r=await re(e,U,R({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=oe(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Fe(e,t){let s=await re(e,L(t),R({abi:Aa,functionName:"price"})),[r]=oe(J("uint256"),s);return r}async function Pa(e,t,s){if(t.irm===te)return 0n;let r=await re(e,L(t.irm),R({abi:Ia,functionName:"borrowRateView",args:[t,s]})),[n]=oe(J("uint256"),r);return n}function je(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ce(n*n,2n*he),a=Ce(l*n,3n*he);return e.totalBorrowAssets+Ce(e.totalBorrowAssets*(n+l+a),he)}async function Le(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Pa(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:je(s,l,o),accruedThrough:o,rate:l}}async function Vt(e,t,s){let r=await re(e,L(t),R({abi:et,functionName:"balanceOf",args:[L(s)]})),[n]=oe(J("uint256"),r);return n}async function ue(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?qe(n):void 0,a=l?be(l):void 0,o=r!==void 0?Ht(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!W(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[d,m]=await Promise.all([Ft(e,u),jt(e,u)]);if(d.loanToken===te||d.collateralToken===te||d.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${p}.`);let c=be(d);if(c.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${c}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===d.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===d.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===d.oracle.toLowerCase()&&l.irm.toLowerCase()===d.irm.toLowerCase()&&l.lltv===d.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:d,marketState:m}}function Ae(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Me(t);if(s<=0n||s>Et)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function Ie(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function va(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p),{marketId:a,marketParams:o}=await ue(l,t,!0),u=await Q(l,o.collateralToken,p),d=o.collateralToken.toLowerCase()===de.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,c=z("wrapNative",t.wrapNative)===!0||m!==void 0&&at(m);if(m&&!at(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(c&&!d)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let f=Ae(t),b=f.toString(),w=e.formatAmount(b,u.decimals),h=[];c&&h.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:b,description:`Wrap ${w} ETH into WETH at ${de}.`})),h.push(e.approval(o.collateralToken,U,b,p)),h.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supplyCollateral",args:[o,f,n,"0x"]}),value:"0",description:`Supply ${w} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply_collateral",chainId:p,marketId:a,marketParams:ce(o),collateralToken:u,assets:b,formattedAssets:w,onBehalf:n,txs:h,summary:`${c?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ca(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.loanToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=Ae(t),h=w.toString(),y=e.formatAmount(h,m.decimals),k=d.totalSupplyAssets>d.totalBorrowAssets?d.totalSupplyAssets-d.totalBorrowAssets:0n;if(w>k)throw new i(`Insufficient market liquidity: requested ${h} base units, available ${k.toString()} base units.`);let g=ke(c.collateral,f,u.lltv),T=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(c.collateral===0n||T+w>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+w).toString()} exceeds max borrow ${g.toString()} base units.`);let I=Ta(w,b.totalBorrowAssets,d.totalBorrowShares),C=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"borrow",args:[u,w,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${h} base units) from Morpho market ${o}.`})],v=await e.preview(C,r),{formattedChanges:x,formattedNetOutflows:G}=ye(e,v);return{action:"morpho_borrow",chainId:p,marketId:o,marketParams:ce(u),loanToken:m,assets:h,formattedAssets:y,borrowShares:I.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:v,formattedChanges:x,formattedNetOutflows:G}}async function La(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p);if(t.shares!==void 0){let x=Me(t.shares);if(x<=0n||x===Sa||x>Et)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(z("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await ue(l,t,!0),[d,m,c]=await Promise.all([Q(l,o.loanToken,p),Se(l,a,n),Vt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let f=0n,b=0n;if(z("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let x=Me(t.shares);if(x>m.borrowShares)throw new i(`Repay shares (${x.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=x}else f=Ae(t);let w=b>0n?await Le(l,o,u,ve):void 0,h=b>0n?ne(b,w.totalBorrowAssets,u.totalBorrowShares):f;if(c<h)throw new i(`Insufficient loan token balance for repayment: wallet holds ${c.toString()} base units, but ${h.toString()} base units are required (including accrued interest).`);let y=h.toString(),k=e.formatAmount(y,d.decimals),g=e.approval(o.loanToken,U,y,p),T=e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"repay",args:[o,f,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${d.symbol}) on Morpho market ${a}.`:`Repay ${k} ${d.symbol} (${f.toString()} base units) on Morpho market ${a}.`}),I=[g,T],M=await e.preview(I,r),{formattedChanges:C,formattedNetOutflows:v}=ye(e,M);return{action:"morpho_repay",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,repayAssets:f.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:ve.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:I,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${d.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${ve} seconds.`:`Repay ${k} ${d.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:v}}async function $a(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.collateralToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=z("withdrawAll",t.withdrawAll)===!0?c.collateral:Ae(t);if(w<=0n||w>c.collateral)throw new i(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${c.collateral.toString()} base units.`);if(c.borrowShares>0n){let C=c.collateral-w,v=ke(C,f,u.lltv),x=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(x>v)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${v.toString()} would fall below current debt ${x.toString()} base units.`)}let h=w.toString(),y=e.formatAmount(h,m.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdrawCollateral",args:[u,w,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${h} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw_collateral",chainId:p,marketId:o,marketParams:ce(u),collateralToken:m,assets:h,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function Da(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),{marketId:l,marketParams:a,marketState:o}=await ue(n,t,!0),u=z("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==de.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let d=Ae(t),m=d.toString(),[c,f]=await Promise.all([Q(n,a.loanToken,p),u?Promise.resolve(d):Vt(n,a.loanToken,r)]);if(f<d)throw new i(`Insufficient ${c.symbol} balance to lend: wallet holds ${f.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,c.decimals),w=[];u&&w.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${de}.`})),w.push(e.approval(a.loanToken,U,m,p)),w.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supply",args:[a,d,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${c.symbol} (${m} base units) to Morpho market ${l}.`}));let h=xa(d,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply",chainId:p,marketId:l,marketParams:ce(a),loanToken:c,assets:m,formattedAssets:b,supplySharesEstimated:h.toString(),onBehalf:r,oak:ot(l),txs:w,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${c.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ua(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),l=z("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await ue(n,t,!0),[d,m]=await Promise.all([Q(n,o.loanToken,p),Se(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${d.symbol} on Morpho market ${a}.`);let c=rt(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),f=l?0n:Ae(t),b=l?m.supplyShares:0n;if(!l&&f>c)throw new i(`Withdrawal exceeds the lent balance: requested ${f.toString()} base units, position holds about ${c.toString()}. Use withdrawAll for a full exit.`);let w=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,h=l?c:f;if(h>w)throw new i(`Insufficient market liquidity: withdrawing ${h.toString()} base units needs idle assets, but only ${w.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(h.toString(),d.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdraw",args:[o,f,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${d.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${d.symbol} (${f.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,withdrawAssets:f.toString(),withdrawShares:b.toString(),estimatedAssets:h.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${d.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${d.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function zt(e,t,s){let r=await e.http(pa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function Wt(e){let t=`query Markets($chainId: Int!) {
1
+ import{a as ae}from"./3CCBUYUM.js";import{a as bt,d as wt,e as ht}from"./L24EOVLT.js";import{a as Ne}from"./7MR37STI.js";import{a as We,b as Be,d as pt}from"./EC5W3UZD.js";import{b as ut,c as mt,d as ft}from"./46ZA2R5L.js";import{d as ct,e as te}from"./CAU44UWP.js";import{a as dt}from"./VJ3W2V3B.js";import{b as lt}from"./AXYOJBX6.js";import{a as q}from"./6IM6A5VA.js";import{a as A,d as z}from"./UWOFA6GV.js";import{d as De,g as E,i as Ue}from"./73N3TOJL.js";import{a as Me}from"./RETS2ZEK.js";import{j as it}from"./IWALIX7Q.js";import{a as p,i as V}from"./XPFVT2EA.js";import{a as i,d as se}from"./5YS5V2LK.js";import{a as ze}from"./JXOEJPJ4.js";import{encodeFunctionData as me,erc20Abi as Ha,getAddress as Kt,parseAbi as st,zeroAddress as qa}from"viem";import{decodeAbiParameters as aa,encodeFunctionData as oa,getAddress as ie,parseAbiParameters as ra,zeroAddress as fe,zeroHash as It}from"viem";import{decodeAbiParameters as Xt,encodeFunctionData as Yt,erc20Abi as Jt,getAddress as St,parseAbi as Zt,parseAbiParameters as ea,zeroHash as kt}from"viem";var Ke=St("0xCE29862924756584BBD0D75CA1249d22007E2813"),At="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",ta="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",yt=Zt(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${At}[] marketParamsList,uint256 exitAssets,${ta} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var gt=(e,t)=>e<t?e:t;async function Za(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),d=e.clientFor(p),m=await pt(d,t,s),c=(S,B,Te,ee=[])=>d.readContract({address:S,abi:B,functionName:Te,args:ee,blockNumber:m.blockNumber}),[f,b,w,h]=await Promise.all([d.getBlock({blockNumber:m.blockNumber}),c(Ke,yt,"BLUE"),c(t,Jt,"balanceOf",[n]),c(t,We,"previewRedeem",[a])]);if(typeof b!="string"||St(b)!==U)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<f.timestamp||u>f.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Be(w))throw new i("maxShares exceeds the wallet share balance.");let y=gt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&W(S.id)),g=l-y,T=k[0]?.penalty??0n,I=g*10n**18n/(10n**18n+T);if(g>0n&&I===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(I===0n)break;let B=gt(S.supplied,I);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),I-=B}if(I>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Be(h))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let v=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],G=(await Promise.all(v.map(S=>c(t,We,"previewWithdraw",[S])))).reduce((S,B)=>S+Be(B),0n);if(G===0n||G>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>Xt(ea(At),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${G} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,P=Yt({abi:yt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:kt,s:kt},u]}),D=[e.approval(t,Ke,G.toString(),p),e.unsignedTx({to:Ke,data:P,value:"0",chainId:p,description:F})],$=await e.preview(D,n),j=-$.changes.filter(S=>S.token.chainId===p&&E(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(j<=0n||j>G)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:D,preview:$,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var pe=ie("0x53A1eB6589861F686af7c531211E35Aefe30210f"),xt=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],Qe={kind:0,data:"0x"},Oe={nonce:0n,deadline:0n,signature:{v:0,r:It,s:It}},na=ra("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),Tt=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:xt},marketId:{type:"string"},destinationMarketId:{type:"string"},assets:A(),collateralAssets:A(),shares:A(),maxRepayAssets:A(),maxLtv:A(),deadline:A(),allocations:{type:"array",maxItems:4,items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string"},sourceMarketId:{type:"string"},assets:A(),maxPenaltyAssets:A()}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(p);if(await n.getChainId()!==p||typeof r!="string"||!xt.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(P=>!l.includes(P)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,d]=await Promise.all([n.readContract({address:pe,abi:Ne,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:pe,abi:Ne,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(ie(u)!==U||ie(d)!==bt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async P=>{if(typeof P!="string"||!W(P))throw new i("Choose a verified Morpho market with a supported exit.");let D=await n.readContract({address:U,abi:O,functionName:"idToMarketParams",args:[P],blockNumber:a.number}),$={loanToken:ie(D[0]),collateralToken:ie(D[1]),oracle:ie(D[2]),irm:ie(D[3]),lltv:D[4]};if(!E(be({...$,lltv:String($.lltv)}),P))throw new i("Blue bundle market identity mismatch.");return $},c=await m(t.marketId),f=r==="migrateBorrowPosition"?await m(t.destinationMarketId):c;if(c.loanToken!==f.loanToken||c.collateralToken!==f.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:U,abi:O,functionName:"isAuthorized",args:[s,pe],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${pe}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),w=t.shares===void 0?0n:N(t.shares,!0),h=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>f.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(w===0n)||r==="supplyCollateralAndBorrow"&&h===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&w>0n||b===0n&&w===0n&&h===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],I=0n;for(let P of k){if(!P||typeof P!="object"||Array.isArray(P)||Object.keys(P).some(Ve=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Ve)))throw new i("Unsupported bundled allocation input.");let D=P,$=await wt(e,{vault:D.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has($.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add($.definition.vault.toLowerCase());let j=N(D.assets),S=N(D.maxPenaltyAssets,!0);if(!$.permission||j>=1n<<128n||j>$.headroom||$.penalty>10n**18n||$.asset.address!==f.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(j*$.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");I+=B;let Te=D.sourceMarketId===void 0,ee=Te?void 0:$.sources.find(Ve=>E(Ve.id,String(D.sourceMarketId)));if(Te?!$.canIdle||j>$.data.idle:!ee||!ee.canPull||j>ee.capacity||j>$.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:$.definition.vault,adapter:$.target.adapter,marketParams:$.params,sourceAdapter:ee?.adapter??fe,sourceMarketParams:ee?aa(na,ee.data)[0]:$.params,assets:j,penalty:$.penalty,fromIdle:Te})}let M,C,v,x=0n;if(r==="supply")M="blueBundlesV1Supply",v=c.loanToken,x=b,C=[c,b,Qe,0n,fe,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[c,b,w,Oe,T,0n,fe,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",v=c.collateralToken,x=h,I>=b&&I>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[c,h,b,y,Qe,Oe,T,0n,fe,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",v=c.loanToken,x=N(t.maxRepayAssets,!0),b>x||w>0n&&x===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[c,b,w,x,h,y,Qe,Oe,0n,fe,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[c,f,y,Oe,T,0n,fe,o];let G=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${I} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${x}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...v&&x?[e.approval(v,pe,x.toString(),p)]:[],e.unsignedTx({to:pe,data:oa({abi:Ne,functionName:M,args:C}),value:"0",chainId:p,description:G})],H=await e.preview(Z,s),F=new Map;for(let P of H.changes)if(BigInt(P.amount)<0n){let D=P.token.address.toLowerCase();F.set(D,(F.get(D)??0n)-BigInt(P.amount))}if([...F].some(([P,D])=>!v||P!==v.toLowerCase()||D>x))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:G}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Mt,decodeAbiParameters as sa,encodeAbiParameters as $t,encodeFunctionData as Xe,erc20Abi as Pt,getAddress as K,keccak256 as Je,zeroAddress as we,zeroHash as ia}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),la=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),Ze=ae.find(e=>e.name==="take"),vt=[Ze.inputs[0]],da=[Ze.inputs[0].components[0]];function Ct(e){let t=Je(Mt(["0x600b380380600b5f395ff3",$t(da,[e])]));return Je(Mt(["0xff",e.midnight,ia,t]))}var le=10n**18n,Lt=(e,t)=>(e+(t-1n)/2n)/t;function Dt(e){if(e<0n)return 10n**36n/Dt(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*le),l=n*r/(3n*le);return le+r+n+l<<s}function ca(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Lt(Lt(10n**36n,le+Dt(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function Ge(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function Ye(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ua=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ut=e=>{async function t(n,l){let a=Ge(n,32),o=e.clientFor(p);if(await o.getChainId()!==p)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),d=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await d("toMarket",[a]);if(m.chainId!==BigInt(p)||K(m.midnight)!==Y||!E(Ct(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![V[p].tokens.USDG.address,V[p].tokens.WETH.address].some(k=>E(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[f,b,w,h]=await Promise.all([d("position",[a,l]),d("updatePositionView",[m,a,l]),d("marketState",[a]),d("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Pt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Pt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:p}};return{id:a,rpc:o,block:u,market:m,read:d,token:y,loan:await y(m.loanToken),position:Ye(f,6),updated:Ye(b,3),state:Ye(w,13),healthy:h}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,d)=>{try{if(q(d),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,d)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string"}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,c)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(c)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],d=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,c)=>[m,K(String(d[c]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:p,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ua(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string"},units:A(),maxAssets:A(),minAssets:A()},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=Ge(n.offer),[o]=sa(vt,a);if(!E($t(vt,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Ct(o.market),l),d=N(n.units),m=N(n.maxAssets,!0),c=N(n.minAssets,!0),f=Ge(n.ratifierData);if(d>=1n<<128n||E(o.maker,l)||o.callback!==we||o.callbackData!=="0x"||!la.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==we||!o.buy&&o.receiverIfMakerIsSeller===we)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&d>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),w=ca(o.tick);if(b>w&&o.buy)throw new i("Settlement fee exceeds the offer price.");let h=o.buy?w-b:w,y=h+b,k=P=>o.buy?P/le:(P+le-1n)/le,g=k(d*y),T=k(d*h);if(o.buy?T<c||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let I=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||I+(o.maxAssets?o.buy?g:T:d)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[Ze.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],v=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,f,l],blockNumber:u.block.number});if(M!==!0||v!==Je(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let x=Xe({abi:ae,functionName:"take",args:[o,f,d,l,o.buy?l:we,we,"0x"]}),G=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${d} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),p)],e.unsignedTx({to:Y,data:x,value:"0",chainId:p,description:G})],H=await r(Z,l,G),F=H.preview.changes.filter(P=>P.token.chainId===p&&E(P.token.address,u.loan.address)).reduce((P,D)=>P+BigInt(D.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string"},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"]},amount:A(),collateralIndex:{type:"integer",minimum:0,maximum:127}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,d,m=a.loan,c=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(c=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,c,l]}else{if(c=N(n.amount),c>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let w=BigInt(String(n.collateralIndex)),h=await a.token(a.market.collateralParams[Number(w)].token);if(m=h,o==="withdrawCollateral"&&c>await a.read("collateral",[a.id,l,w]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,w,c,l]:[a.market,w,c,l,l],o==="supplyCollateral"&&(d=h)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&c>a.position[4]||o==="withdraw"&&(c>a.updated[0]||c>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,c,l,we,"0x"]:[a.market,c,l,l],o==="repay"&&(d=a.loan)}}let f=`Midnight ${o}: ${c} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...d?[e.approval(d.address,Y,c.toString(),p)]:[],e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:String(o),args:u}),value:"0",chainId:p,description:f})];return r(b,l,f)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"]},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(f=>f.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let d=e.clientFor(p);if(await d.getChainId()!==p)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((f,b)=>{let w=n.values[b];if(f.type==="bool"){if(typeof w!="boolean")throw new i("Use boolean management values.");return w}if(f.type==="address")return Ue(w,"Use explicit management addresses.",De);if(f.type==="bytes32")return Ge(w,32);if(/^uint/.test(f.type)){let h=N(w,!0);if(h>=1n<<BigInt(f.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return h}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!E(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let f=await d.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof f!="string"||K(f)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let c=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:o,args:m}),value:"0",chainId:p,description:c})],l,c)})]}};import{decodeAbiParameters as oe,encodeAbiParameters as ma,encodeFunctionData as R,erc20Abi as et,getAddress as L,isAddress as Re,keccak256 as fa,parseAbi as Ee,parseAbiParameters as J}from"viem";var Pe="morpho",pa="https://api.morpho.org/graphql",U=L(V[p].morpho.morpho_blue.address),ba=L(V[p].morpho.adaptive_curve_irm.address),wa=L(V[p].morpho.USDG.address),de=L(V[p].morpho.WETH.address),ha=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],ka={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},tt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],ya=new Map(tt.map(e=>[e.marketId.toLowerCase(),e]));function W(e){return ya.get(e.toLowerCase())}function ot(e){let t=W(e);return t?{actions:"enabled",label:t.label,source:ka[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var Bt=20,ve=120n,_e=1000000n,He=1n,he=10n**18n,ga=10n**36n,Et=(1n<<128n)-1n,Sa=(1n<<256n)-1n,X=Ee(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),Aa=Ee(["function price() view returns (uint256)"]),Ia=Ee(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_t=Ee(["function deposit() payable"]);function ce(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ce(e,t){return e===0n?0n:(e+t-1n)/t}function xa(e,t,s){return e*(s+_e)/(t+He)}function Ta(e,t,s){return Ce(e*(s+_e),t+He)}function rt(e,t,s){return e*(t+He)/(s+_e)}function ne(e,t,s){return Ce(e*(t+He),s+_e)}function ke(e,t,s){return e*t/ga*s/he}function Ma(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function ye(e,t){let s=[],r={};for(let n of t.changes){let l=Ma(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Ht(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function qe(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Re(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Me(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=he)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function be(e){let t=qe(e),s=ma(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return fa(s)}function at(e){let t=e.toLowerCase();return t===dt.toLowerCase()||t===ct.toLowerCase()||t===te.toLowerCase()}function ge(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function re(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function qt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=p){if(q(t),at(t))return{...ut,chainId:s};let r=L(t),n=r.toLowerCase();if(s===p){if(n===wa.toLowerCase())return mt;if(n===de.toLowerCase())return ft}let[l,a]=await Promise.all([re(e,r,R({abi:et,functionName:"symbol"})),re(e,r,R({abi:et,functionName:"decimals"}))]),[o]=oe(J("string"),l),[u]=oe(J("uint8"),a);return{address:r,symbol:qt(o),decimals:Number(u),chainId:s}}async function Ft(e,t){let s=await re(e,U,R({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=oe(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function jt(e,t){let s=await re(e,U,R({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=oe(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Se(e,t,s){let r=await re(e,U,R({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=oe(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Fe(e,t){let s=await re(e,L(t),R({abi:Aa,functionName:"price"})),[r]=oe(J("uint256"),s);return r}async function Pa(e,t,s){if(t.irm===te)return 0n;let r=await re(e,L(t.irm),R({abi:Ia,functionName:"borrowRateView",args:[t,s]})),[n]=oe(J("uint256"),r);return n}function je(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ce(n*n,2n*he),a=Ce(l*n,3n*he);return e.totalBorrowAssets+Ce(e.totalBorrowAssets*(n+l+a),he)}async function Le(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Pa(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:je(s,l,o),accruedThrough:o,rate:l}}async function Vt(e,t,s){let r=await re(e,L(t),R({abi:et,functionName:"balanceOf",args:[L(s)]})),[n]=oe(J("uint256"),r);return n}async function ue(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?qe(n):void 0,a=l?be(l):void 0,o=r!==void 0?Ht(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!W(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[d,m]=await Promise.all([Ft(e,u),jt(e,u)]);if(d.loanToken===te||d.collateralToken===te||d.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${p}.`);let c=be(d);if(c.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${c}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===d.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===d.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===d.oracle.toLowerCase()&&l.irm.toLowerCase()===d.irm.toLowerCase()&&l.lltv===d.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:d,marketState:m}}function Ae(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Me(t);if(s<=0n||s>Et)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function Ie(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function va(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p),{marketId:a,marketParams:o}=await ue(l,t,!0),u=await Q(l,o.collateralToken,p),d=o.collateralToken.toLowerCase()===de.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,c=z("wrapNative",t.wrapNative)===!0||m!==void 0&&at(m);if(m&&!at(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(c&&!d)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let f=Ae(t),b=f.toString(),w=e.formatAmount(b,u.decimals),h=[];c&&h.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:b,description:`Wrap ${w} ETH into WETH at ${de}.`})),h.push(e.approval(o.collateralToken,U,b,p)),h.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supplyCollateral",args:[o,f,n,"0x"]}),value:"0",description:`Supply ${w} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply_collateral",chainId:p,marketId:a,marketParams:ce(o),collateralToken:u,assets:b,formattedAssets:w,onBehalf:n,txs:h,summary:`${c?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ca(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.loanToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=Ae(t),h=w.toString(),y=e.formatAmount(h,m.decimals),k=d.totalSupplyAssets>d.totalBorrowAssets?d.totalSupplyAssets-d.totalBorrowAssets:0n;if(w>k)throw new i(`Insufficient market liquidity: requested ${h} base units, available ${k.toString()} base units.`);let g=ke(c.collateral,f,u.lltv),T=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(c.collateral===0n||T+w>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+w).toString()} exceeds max borrow ${g.toString()} base units.`);let I=Ta(w,b.totalBorrowAssets,d.totalBorrowShares),C=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"borrow",args:[u,w,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${h} base units) from Morpho market ${o}.`})],v=await e.preview(C,r),{formattedChanges:x,formattedNetOutflows:G}=ye(e,v);return{action:"morpho_borrow",chainId:p,marketId:o,marketParams:ce(u),loanToken:m,assets:h,formattedAssets:y,borrowShares:I.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:v,formattedChanges:x,formattedNetOutflows:G}}async function La(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p);if(t.shares!==void 0){let x=Me(t.shares);if(x<=0n||x===Sa||x>Et)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(z("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await ue(l,t,!0),[d,m,c]=await Promise.all([Q(l,o.loanToken,p),Se(l,a,n),Vt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let f=0n,b=0n;if(z("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let x=Me(t.shares);if(x>m.borrowShares)throw new i(`Repay shares (${x.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=x}else f=Ae(t);let w=b>0n?await Le(l,o,u,ve):void 0,h=b>0n?ne(b,w.totalBorrowAssets,u.totalBorrowShares):f;if(c<h)throw new i(`Insufficient loan token balance for repayment: wallet holds ${c.toString()} base units, but ${h.toString()} base units are required (including accrued interest).`);let y=h.toString(),k=e.formatAmount(y,d.decimals),g=e.approval(o.loanToken,U,y,p),T=e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"repay",args:[o,f,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${d.symbol}) on Morpho market ${a}.`:`Repay ${k} ${d.symbol} (${f.toString()} base units) on Morpho market ${a}.`}),I=[g,T],M=await e.preview(I,r),{formattedChanges:C,formattedNetOutflows:v}=ye(e,M);return{action:"morpho_repay",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,repayAssets:f.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:ve.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:I,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${d.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${ve} seconds.`:`Repay ${k} ${d.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:v}}async function $a(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.collateralToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=z("withdrawAll",t.withdrawAll)===!0?c.collateral:Ae(t);if(w<=0n||w>c.collateral)throw new i(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${c.collateral.toString()} base units.`);if(c.borrowShares>0n){let C=c.collateral-w,v=ke(C,f,u.lltv),x=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(x>v)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${v.toString()} would fall below current debt ${x.toString()} base units.`)}let h=w.toString(),y=e.formatAmount(h,m.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdrawCollateral",args:[u,w,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${h} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw_collateral",chainId:p,marketId:o,marketParams:ce(u),collateralToken:m,assets:h,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function Da(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),{marketId:l,marketParams:a,marketState:o}=await ue(n,t,!0),u=z("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==de.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let d=Ae(t),m=d.toString(),[c,f]=await Promise.all([Q(n,a.loanToken,p),u?Promise.resolve(d):Vt(n,a.loanToken,r)]);if(f<d)throw new i(`Insufficient ${c.symbol} balance to lend: wallet holds ${f.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,c.decimals),w=[];u&&w.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${de}.`})),w.push(e.approval(a.loanToken,U,m,p)),w.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supply",args:[a,d,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${c.symbol} (${m} base units) to Morpho market ${l}.`}));let h=xa(d,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply",chainId:p,marketId:l,marketParams:ce(a),loanToken:c,assets:m,formattedAssets:b,supplySharesEstimated:h.toString(),onBehalf:r,oak:ot(l),txs:w,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${c.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ua(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),l=z("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await ue(n,t,!0),[d,m]=await Promise.all([Q(n,o.loanToken,p),Se(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${d.symbol} on Morpho market ${a}.`);let c=rt(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),f=l?0n:Ae(t),b=l?m.supplyShares:0n;if(!l&&f>c)throw new i(`Withdrawal exceeds the lent balance: requested ${f.toString()} base units, position holds about ${c.toString()}. Use withdrawAll for a full exit.`);let w=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,h=l?c:f;if(h>w)throw new i(`Insufficient market liquidity: withdrawing ${h.toString()} base units needs idle assets, but only ${w.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(h.toString(),d.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdraw",args:[o,f,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${d.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${d.symbol} (${f.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,withdrawAssets:f.toString(),withdrawShares:b.toString(),estimatedAssets:h.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${d.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${d.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function zt(e,t,s){let r=await e.http(pa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function Wt(e){let t=`query Markets($chainId: Int!) {
2
2
  markets(first: 1000, where: { chainId_in: [$chainId] }) {
3
3
  items {
4
4
  marketId chain { id } lltv listed
@@ -1 +1 @@
1
- import{b as Q}from"./JRZLKIYB.js";import{a as O,b as J,d as V}from"./65QFM4JU.js";import{a as X}from"./CEQNXF6A.js";import{a as E}from"./QYKXWBZC.js";import{K as y}from"./5H3MQWH7.js";import{c as S}from"./HZUWK5B2.js";import{a as H}from"./6IM6A5VA.js";import{a as N}from"./UWOFA6GV.js";import{d as G,g as U,i as K}from"./73N3TOJL.js";import{a as b}from"./XPFVT2EA.js";import{a as e}from"./5YS5V2LK.js";import{encodeFunctionData as Z,erc20Abi as Y,getAddress as W,parseAbi as ee,zeroAddress as te}from"viem";var v={address:W("0xCeF73866b088766DeD46Ba71d9Bd7591B5e931d2"),symbol:"tNET",decimals:9,chainId:b},_={pair_oracle:["checkpoint"],futures:["open","close","marginCall","accrueCarry","sweepCarrySkim"],underwriting:["subscribe","redeem"],prize:["enter","enterWithNet","exit","exitToUsdg","lockTranche","earlyUnlock","pokeRebase"]},fe=x=>({tools:[{name:"netnet_desk_action",inputSchema:{type:"object",additionalProperties:!1,required:["program","operation"],properties:{program:{type:"string",enum:Object.keys(_)},operation:{type:"string",enum:[...new Set(Object.values(_).flat())]},amount:N(),minAmountOut:N(),maxPayment:N(),sizeUsdWad:N(),isLong:{type:"boolean"},account:{type:"string"},referrer:{type:"string"},trancheIndex:N(),lockDraws:{enum:["7","30"]},maxPenaltyAssets:N()}},execute:async(t,l)=>{try{if(H(l),typeof t.program!="string"||!Object.hasOwn(_,t.program)||typeof t.operation!="string"||!_[t.program].includes(t.operation))throw new e("Choose a supported finite NetNet desk operation.");let p=t.program,r=t.operation,P=E[p],q=X[p],T=x.clientFor(b);if(await T.getChainId()!==b)throw new e("NetNet desk actions require chain 4663.");let C=await T.getBlock(),z=new Set(["program","operation"]),m=(n,s=[])=>T.readContract({address:P.address,abi:q,functionName:n,args:s,blockNumber:C.number}),h=(...n)=>n.forEach(s=>z.add(s)),A=()=>(h("amount"),y(t.amount)),D=()=>(h("minAmountOut"),y(t.minAmountOut)),c=n=>K(n,"Provide an explicit checksummed account.",G),u=[],o,d=0n,w="",g;if(p==="pair_oracle"){if(c(await m("pairContract"))!==Q)throw new e("The oracle does not use the pinned canonical pair.");w="Permissionless oracle checkpoint; it sends no reward to this wallet and may not yet produce a valid TWAP."}else if(p==="futures"||p==="underwriting"){if(c(await m("token"))!==v.address||await T.readContract({address:v.address,abi:Y,functionName:"decimals",blockNumber:C.number})!==9)throw new e("This desk does not use the pinned valueless 9-decimal tNET test collateral.");let n=E.futures.address,s=E.underwriting.address;if(p==="futures"?c(await m("vault"))!==s:c(await m("clearinghouse"))!==n)throw new e("Futures and underwriting counterparties do not match the published pins.");if(w="Experimental tNET test program; tNET has no monetary value. Futures margin and underwriting capital can be lost. Utilization/ADL can prevent redemption. Prices and fees are read from the contract oracle; these calls encode no price floor.",r==="open"){if(h("isLong","sizeUsdWad","maxPayment"),typeof t.isLong!="boolean")throw new e("Provide isLong as a boolean.");let a=A(),f=y(t.sizeUsdWad);if(a>=1n<<128n||f>=1n<<128n)throw new e("Position margin and notional must fit uint128.");let k=c(await m("oracle"));if(k!==W("0xc8a11E8793F8714a159061369173dc86A0A5E23F"))throw new e("The futures oracle is not the published deployment.");let $=await T.readContract({address:k,abi:ee(["function marginPriceWad() view returns (uint256)"]),functionName:"marginPriceWad",blockNumber:C.number});if($<=0n)throw new e("Futures margin price is unavailable.");let i=f*5n/10000n*1000000000n/$;if(d=a+i,o=v,d>y(t.maxPayment))throw new e("Margin plus taker fee exceeds maxPayment.");u=[t.isLong,f,a],w+=` Entry fee ${i} tNET base units; exact approval caps price drift and may require a fresh preview.`}else if(r==="marginCall"){h("account");let a=c(t.account);if(await m("liquidatable",[a])!==!0)throw new e("The selected futures trader is not liquidatable.");u=[a]}else if(r==="subscribe"){d=A(),o=v,u=[d];let[a,f]=await Promise.all([m("totalShares"),m("equityTokens")]);if(typeof a!="bigint"||typeof f!="bigint"||a>0n&&f===0n)throw new e("Underwriting share price is invalid.");let k=a===0n?d:d*a/f;if(k===0n||k<D())throw new e("Underwriting subscription rounds to zero or misses the local share minimum.");w+=` Current quote ${k} underwriting share units; the share minimum is a local check, not encoded calldata.`}else if(r==="redeem"){let a=A();if(a>await m("sharesOf",[l]))throw new e("The wallet has insufficient underwriting shares.");u=[a],g={token:v,amount:D()}}}else{let[n,s,a,f,k,$]=await Promise.all(["net","usdg","staking","sNet","controller","book"].map(i=>m(i)));if(c(n)!==O.address||c(s)!==S.address||c(a)!==V||c(f)!==J.address||c(k)!==E.draw.address||c($)!==E.bonus.address)throw new e("WinNET token, staking, book or controller does not match its published pins.");if(w="WinNET principal is a fixed NET claim, exposed to NET price changes. Entry commits through three staking epochs; locks commit for 7 or 30 draws. Early unlock forfeits 1% of principal and cancels streak credits. Pair buys and sells each incur the NET trading tax; no prize or return is guaranteed.",r==="enter"||r==="enterWithNet"){h("referrer");let i=t.referrer===void 0?te:c(t.referrer);if(i===W(l))throw new e("WinNET does not permit self-referral.");d=A(),o=r==="enter"?S:O,u=r==="enter"?[d,D(),i]:[d,i],w+=` Referrer ${i} is recorded at the first deposit and cannot later be changed.`}else if(r==="exit"||r==="exitToUsdg"){let i=A();if(i>await m("principalOf",[l]))throw new e("WinNET exit exceeds this wallet\u2019s fixed principal.");u=r==="exit"?[i,l]:[i,D(),l],g={token:r==="exit"?O:S,amount:r==="exit"?i:y(t.minAmountOut)}}else if(r==="lockTranche"||r==="earlyUnlock"){h("trancheIndex");let i=y(t.trancheIndex,!0),I=await m("trancheAt",[l,i]);if(!Array.isArray(I)||typeof I[0]!="bigint"||I[0]===0n)throw new e("Choose a nonempty WinNET tranche.");if(r==="lockTranche"){if(h("lockDraws"),t.lockDraws!=="7"&&t.lockDraws!=="30")throw new e("Choose a 7- or 30-draw lock.");u=[i,BigInt(t.lockDraws)]}else{h("maxPenaltyAssets");let M=(I[0]+99n)/100n;if(M>y(t.maxPenaltyAssets,!0))throw new e("Early unlock exceeds maxPenaltyAssets in NET base units.");u=[i],w+=` Current irreversible forfeiture ${M} NET base units.`}}}if(Object.keys(t).some(n=>!z.has(n)))throw new e("Unexpected fields for this desk operation.");if(o&&await T.readContract({address:o.address,abi:Y,functionName:"balanceOf",args:[l],blockNumber:C.number})<d)throw new e(`Top up ${o.symbol}; this action needs ${d} base units.`);let F=`NetNet ${p}.${r}, contract ${P.address}, chain ${b}, ordered values ${JSON.stringify(u,(n,s)=>typeof s=="bigint"?String(s):s)}. ${o?`Approve exactly ${d} ${o.symbol} base units (token ${o.address}, decimals ${o.decimals}). `:""}${w}`,L=[...o?[x.approval(o.address,P.address,d.toString(),b)]:[],x.unsignedTx({to:P.address,data:Z({abi:q,functionName:r,args:u}),value:"0",chainId:b,description:F})],R=await x.preview(L,l),B=0n,j=0n;for(let n of R.changes){if(n.token.chainId!==b||!/^-?\d+$/.test(n.amount))throw new e("Invalid desk preview metadata.");let s=BigInt(n.amount);if(s<0n){if(!o||!U(n.token.address,o.address)||n.token.decimals!==o.decimals)throw new e("Desk preview spends an unexpected wallet asset.");B-=s}if(g&&U(n.token.address,g.token.address)){if(n.token.decimals!==g.token.decimals)throw new e("Desk receipt decimals mismatch.");j+=s}}if(B>d||g&&j<g.amount)throw new e("Desk preview exceeds its input budget or misses the requested receipt minimum.");return{txs:L,preview:R,summary:F}}catch(p){throw new e(x.plainError(p))}}}]});export{v as a,fe as b};
1
+ import{b as Q}from"./55NX776C.js";import{a as O,b as J,d as V}from"./65QFM4JU.js";import{a as E}from"./QYKXWBZC.js";import{a as X}from"./CEQNXF6A.js";import{K as y}from"./JC4SYMBV.js";import{c as S}from"./46ZA2R5L.js";import{a as H}from"./6IM6A5VA.js";import{a as N}from"./UWOFA6GV.js";import{d as G,g as U,i as K}from"./73N3TOJL.js";import{a as b}from"./XPFVT2EA.js";import{a as e}from"./5YS5V2LK.js";import{encodeFunctionData as Z,erc20Abi as Y,getAddress as W,parseAbi as ee,zeroAddress as te}from"viem";var v={address:W("0xCeF73866b088766DeD46Ba71d9Bd7591B5e931d2"),symbol:"tNET",decimals:9,chainId:b},_={pair_oracle:["checkpoint"],futures:["open","close","marginCall","accrueCarry","sweepCarrySkim"],underwriting:["subscribe","redeem"],prize:["enter","enterWithNet","exit","exitToUsdg","lockTranche","earlyUnlock","pokeRebase"]},fe=x=>({tools:[{name:"netnet_desk_action",inputSchema:{type:"object",additionalProperties:!1,required:["program","operation"],properties:{program:{type:"string",enum:Object.keys(_)},operation:{type:"string",enum:[...new Set(Object.values(_).flat())]},amount:N(),minAmountOut:N(),maxPayment:N(),sizeUsdWad:N(),isLong:{type:"boolean"},account:{type:"string"},referrer:{type:"string"},trancheIndex:N(),lockDraws:{enum:["7","30"]},maxPenaltyAssets:N()}},execute:async(t,l)=>{try{if(H(l),typeof t.program!="string"||!Object.hasOwn(_,t.program)||typeof t.operation!="string"||!_[t.program].includes(t.operation))throw new e("Choose a supported finite NetNet desk operation.");let p=t.program,r=t.operation,P=E[p],q=X[p],T=x.clientFor(b);if(await T.getChainId()!==b)throw new e("NetNet desk actions require chain 4663.");let C=await T.getBlock(),z=new Set(["program","operation"]),m=(n,s=[])=>T.readContract({address:P.address,abi:q,functionName:n,args:s,blockNumber:C.number}),h=(...n)=>n.forEach(s=>z.add(s)),A=()=>(h("amount"),y(t.amount)),D=()=>(h("minAmountOut"),y(t.minAmountOut)),c=n=>K(n,"Provide an explicit checksummed account.",G),u=[],o,d=0n,w="",g;if(p==="pair_oracle"){if(c(await m("pairContract"))!==Q)throw new e("The oracle does not use the pinned canonical pair.");w="Permissionless oracle checkpoint; it sends no reward to this wallet and may not yet produce a valid TWAP."}else if(p==="futures"||p==="underwriting"){if(c(await m("token"))!==v.address||await T.readContract({address:v.address,abi:Y,functionName:"decimals",blockNumber:C.number})!==9)throw new e("This desk does not use the pinned valueless 9-decimal tNET test collateral.");let n=E.futures.address,s=E.underwriting.address;if(p==="futures"?c(await m("vault"))!==s:c(await m("clearinghouse"))!==n)throw new e("Futures and underwriting counterparties do not match the published pins.");if(w="Experimental tNET test program; tNET has no monetary value. Futures margin and underwriting capital can be lost. Utilization/ADL can prevent redemption. Prices and fees are read from the contract oracle; these calls encode no price floor.",r==="open"){if(h("isLong","sizeUsdWad","maxPayment"),typeof t.isLong!="boolean")throw new e("Provide isLong as a boolean.");let a=A(),f=y(t.sizeUsdWad);if(a>=1n<<128n||f>=1n<<128n)throw new e("Position margin and notional must fit uint128.");let k=c(await m("oracle"));if(k!==W("0xc8a11E8793F8714a159061369173dc86A0A5E23F"))throw new e("The futures oracle is not the published deployment.");let $=await T.readContract({address:k,abi:ee(["function marginPriceWad() view returns (uint256)"]),functionName:"marginPriceWad",blockNumber:C.number});if($<=0n)throw new e("Futures margin price is unavailable.");let i=f*5n/10000n*1000000000n/$;if(d=a+i,o=v,d>y(t.maxPayment))throw new e("Margin plus taker fee exceeds maxPayment.");u=[t.isLong,f,a],w+=` Entry fee ${i} tNET base units; exact approval caps price drift and may require a fresh preview.`}else if(r==="marginCall"){h("account");let a=c(t.account);if(await m("liquidatable",[a])!==!0)throw new e("The selected futures trader is not liquidatable.");u=[a]}else if(r==="subscribe"){d=A(),o=v,u=[d];let[a,f]=await Promise.all([m("totalShares"),m("equityTokens")]);if(typeof a!="bigint"||typeof f!="bigint"||a>0n&&f===0n)throw new e("Underwriting share price is invalid.");let k=a===0n?d:d*a/f;if(k===0n||k<D())throw new e("Underwriting subscription rounds to zero or misses the local share minimum.");w+=` Current quote ${k} underwriting share units; the share minimum is a local check, not encoded calldata.`}else if(r==="redeem"){let a=A();if(a>await m("sharesOf",[l]))throw new e("The wallet has insufficient underwriting shares.");u=[a],g={token:v,amount:D()}}}else{let[n,s,a,f,k,$]=await Promise.all(["net","usdg","staking","sNet","controller","book"].map(i=>m(i)));if(c(n)!==O.address||c(s)!==S.address||c(a)!==V||c(f)!==J.address||c(k)!==E.draw.address||c($)!==E.bonus.address)throw new e("WinNET token, staking, book or controller does not match its published pins.");if(w="WinNET principal is a fixed NET claim, exposed to NET price changes. Entry commits through three staking epochs; locks commit for 7 or 30 draws. Early unlock forfeits 1% of principal and cancels streak credits. Pair buys and sells each incur the NET trading tax; no prize or return is guaranteed.",r==="enter"||r==="enterWithNet"){h("referrer");let i=t.referrer===void 0?te:c(t.referrer);if(i===W(l))throw new e("WinNET does not permit self-referral.");d=A(),o=r==="enter"?S:O,u=r==="enter"?[d,D(),i]:[d,i],w+=` Referrer ${i} is recorded at the first deposit and cannot later be changed.`}else if(r==="exit"||r==="exitToUsdg"){let i=A();if(i>await m("principalOf",[l]))throw new e("WinNET exit exceeds this wallet\u2019s fixed principal.");u=r==="exit"?[i,l]:[i,D(),l],g={token:r==="exit"?O:S,amount:r==="exit"?i:y(t.minAmountOut)}}else if(r==="lockTranche"||r==="earlyUnlock"){h("trancheIndex");let i=y(t.trancheIndex,!0),I=await m("trancheAt",[l,i]);if(!Array.isArray(I)||typeof I[0]!="bigint"||I[0]===0n)throw new e("Choose a nonempty WinNET tranche.");if(r==="lockTranche"){if(h("lockDraws"),t.lockDraws!=="7"&&t.lockDraws!=="30")throw new e("Choose a 7- or 30-draw lock.");u=[i,BigInt(t.lockDraws)]}else{h("maxPenaltyAssets");let M=(I[0]+99n)/100n;if(M>y(t.maxPenaltyAssets,!0))throw new e("Early unlock exceeds maxPenaltyAssets in NET base units.");u=[i],w+=` Current irreversible forfeiture ${M} NET base units.`}}}if(Object.keys(t).some(n=>!z.has(n)))throw new e("Unexpected fields for this desk operation.");if(o&&await T.readContract({address:o.address,abi:Y,functionName:"balanceOf",args:[l],blockNumber:C.number})<d)throw new e(`Top up ${o.symbol}; this action needs ${d} base units.`);let F=`NetNet ${p}.${r}, contract ${P.address}, chain ${b}, ordered values ${JSON.stringify(u,(n,s)=>typeof s=="bigint"?String(s):s)}. ${o?`Approve exactly ${d} ${o.symbol} base units (token ${o.address}, decimals ${o.decimals}). `:""}${w}`,L=[...o?[x.approval(o.address,P.address,d.toString(),b)]:[],x.unsignedTx({to:P.address,data:Z({abi:q,functionName:r,args:u}),value:"0",chainId:b,description:F})],R=await x.preview(L,l),B=0n,j=0n;for(let n of R.changes){if(n.token.chainId!==b||!/^-?\d+$/.test(n.amount))throw new e("Invalid desk preview metadata.");let s=BigInt(n.amount);if(s<0n){if(!o||!U(n.token.address,o.address)||n.token.decimals!==o.decimals)throw new e("Desk preview spends an unexpected wallet asset.");B-=s}if(g&&U(n.token.address,g.token.address)){if(n.token.decimals!==g.token.decimals)throw new e("Desk receipt decimals mismatch.");j+=s}}if(B>d||g&&j<g.amount)throw new e("Desk preview exceeds its input budget or misses the requested receipt minimum.");return{txs:L,preview:R,summary:F}}catch(p){throw new e(x.plainError(p))}}}]});export{v as a,fe as b};
@@ -1 +1 @@
1
- import{a as $}from"./B7V7AA5A.js";import{a as U}from"./EKGHKEKV.js";import{b as I}from"./KEPQXFHU.js";import{c as k}from"./JRZLKIYB.js";import{g as S}from"./65QFM4JU.js";import{c as G}from"./HL2MLC3O.js";import{a as b}from"./CXMC3T6B.js";import{b as E}from"./AXYOJBX6.js";import{a as h}from"./6IM6A5VA.js";import{a as D}from"./UWOFA6GV.js";import{g as y,n as C}from"./73N3TOJL.js";import{a as s,d as P,i as w}from"./XPFVT2EA.js";import{a as m}from"./5YS5V2LK.js";import{encodeFunctionData as v,parseAbi as j}from"viem";var a=w[s].vaults.netnet.address,d={address:w[s].tokens.USDG.address,chainId:s,decimals:P,symbol:"USDG"},N={address:a,chainId:s,decimals:18,symbol:"nnUSDG"},o=j(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function balanceOf(address owner) view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),_=D("Positive USDG amount in integer base units (6 decimals)."),O="Preview amounts are estimates; these ERC-4626 calls have no on-chain minimum output argument. No transaction was sent.";function M(e){return C(e,"Amount must be positive and fit in uint256.",{notString:"Provide an integer amount string in base units.",positive:!0})}function g(e,f){if(Object.keys(e).some(l=>!f.includes(l)))throw new m("Unsupported NetNet argument.")}var q=e=>{async function f(t){try{return await t()}catch(n){throw new m(e.plainError(n))}}async function l(){let t=e.clientFor(s);if(await t.getChainId()!==s)throw new m("NetNet requires chain 4663.");let[n,r]=await Promise.all([t.readContract({address:a,abi:o,functionName:"asset"}),t.readContract({address:a,abi:o,functionName:"decimals"})]);if(!y(n,d.address))throw new m("NetNet does not report the pinned USDG asset.");if(r!==N.decimals)throw new m("NetNet share decimals do not match the pinned metadata.");return t}async function A(t,n,r){let i=await e.preview(t,n),p=i.changes.map(({token:u,amount:c})=>{let T=c.startsWith("-");return`${T?"-":"+"}${e.formatAmount(T?c.slice(1):c,u.decimals)} ${u.symbol}`}).join(", ");return{txs:t,preview:i,summary:`${r} ${i.summary} ${p?`Estimated changes: ${p}. `:""}${O}`}}async function R(t){return f(async()=>{h(t);let n=await l(),r=await n.readContract({address:a,abi:o,functionName:"balanceOf",args:[t]});if(r===0n)return[];let i=await n.readContract({address:a,abi:o,functionName:"convertToAssets",args:[r]});return[{module:"netnet",id:`${s}:${a}`,chainId:s,assets:[{token:{...d},amount:i.toString()}],description:`${e.formatAmount(r.toString(),N.decimals)} nnUSDG shares in NetNet Credit (${a}); underlying USDG is an estimate, not a liquidity guarantee.`}]})}return{positions:R,tools:[{name:"netnet_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:t=>f(async()=>{g(t,[]);let r=await(await l()).readContract({address:a,abi:o,functionName:"totalAssets"});return[{address:a,name:"NetNet Credit",chainId:s,asset:{...d},shares:{...N},totalAssets:{token:{...d},amount:r.toString()}}]})},{name:"netnet_deposit",inputSchema:{type:"object",properties:{amount:_},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=M(t.amount);await l();let i=[e.approval(d.address,a,r.toString(),s),e.unsignedTx({to:a,data:v({abi:o,functionName:"deposit",args:[r,n]}),value:"0",chainId:s,description:`Deposit ${e.formatAmount(r.toString(),d.decimals)} USDG into NetNet Credit.`})];return A(i,n,"Approve the exact USDG amount, then deposit into NetNet Credit.")})},{name:"netnet_withdraw",inputSchema:{type:"object",properties:{amount:{anyOf:[_,{const:"max",description:"Redeem the fresh full nnUSDG share balance."}]}},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=t.amount==="max"?void 0:M(t.amount),i=await l(),p,u;if(r===void 0){let c=await i.readContract({address:a,abi:o,functionName:"balanceOf",args:[n]});if(c===0n)throw new m("This wallet has no NetNet shares to redeem.");p=v({abi:o,functionName:"redeem",args:[c,n,n]}),u=`Redeem all ${e.formatAmount(c.toString(),N.decimals)} nnUSDG shares for USDG.`}else p=v({abi:o,functionName:"withdraw",args:[r,n,n]}),u=`Withdraw ${e.formatAmount(r.toString(),d.decimals)} USDG from NetNet Credit (unmeasured on the recorded fork; full exit uses amount "max" redeem).`;return A([e.unsignedTx({to:a,data:p,value:"0",chainId:s,description:u})],n,u)})}]}};function ie(e){return E("netnet",[q(e),S(e),k(e),G(e),$(e),U(e),I(e),{tools:b(e,"netnet",[{vault:a,asset:d}])}])}export{q as a,ie as b};
1
+ import{a as $}from"./QCD33HMD.js";import{a as U}from"./BXN3MDS4.js";import{c as G}from"./HL2MLC3O.js";import{b as I}from"./JREVERSC.js";import{c as k}from"./55NX776C.js";import{g as S}from"./65QFM4JU.js";import{a as b}from"./6PU2CMQZ.js";import{b as E}from"./AXYOJBX6.js";import{a as h}from"./6IM6A5VA.js";import{a as D}from"./UWOFA6GV.js";import{g as y,n as C}from"./73N3TOJL.js";import{a as s,d as P,i as w}from"./XPFVT2EA.js";import{a as m}from"./5YS5V2LK.js";import{encodeFunctionData as v,parseAbi as j}from"viem";var a=w[s].vaults.netnet.address,d={address:w[s].tokens.USDG.address,chainId:s,decimals:P,symbol:"USDG"},N={address:a,chainId:s,decimals:18,symbol:"nnUSDG"},o=j(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function balanceOf(address owner) view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),_=D("Positive USDG amount in integer base units (6 decimals)."),O="Preview amounts are estimates; these ERC-4626 calls have no on-chain minimum output argument. No transaction was sent.";function M(e){return C(e,"Amount must be positive and fit in uint256.",{notString:"Provide an integer amount string in base units.",positive:!0})}function g(e,f){if(Object.keys(e).some(l=>!f.includes(l)))throw new m("Unsupported NetNet argument.")}var q=e=>{async function f(t){try{return await t()}catch(n){throw new m(e.plainError(n))}}async function l(){let t=e.clientFor(s);if(await t.getChainId()!==s)throw new m("NetNet requires chain 4663.");let[n,r]=await Promise.all([t.readContract({address:a,abi:o,functionName:"asset"}),t.readContract({address:a,abi:o,functionName:"decimals"})]);if(!y(n,d.address))throw new m("NetNet does not report the pinned USDG asset.");if(r!==N.decimals)throw new m("NetNet share decimals do not match the pinned metadata.");return t}async function A(t,n,r){let i=await e.preview(t,n),p=i.changes.map(({token:u,amount:c})=>{let T=c.startsWith("-");return`${T?"-":"+"}${e.formatAmount(T?c.slice(1):c,u.decimals)} ${u.symbol}`}).join(", ");return{txs:t,preview:i,summary:`${r} ${i.summary} ${p?`Estimated changes: ${p}. `:""}${O}`}}async function R(t){return f(async()=>{h(t);let n=await l(),r=await n.readContract({address:a,abi:o,functionName:"balanceOf",args:[t]});if(r===0n)return[];let i=await n.readContract({address:a,abi:o,functionName:"convertToAssets",args:[r]});return[{module:"netnet",id:`${s}:${a}`,chainId:s,assets:[{token:{...d},amount:i.toString()}],description:`${e.formatAmount(r.toString(),N.decimals)} nnUSDG shares in NetNet Credit (${a}); underlying USDG is an estimate, not a liquidity guarantee.`}]})}return{positions:R,tools:[{name:"netnet_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:t=>f(async()=>{g(t,[]);let r=await(await l()).readContract({address:a,abi:o,functionName:"totalAssets"});return[{address:a,name:"NetNet Credit",chainId:s,asset:{...d},shares:{...N},totalAssets:{token:{...d},amount:r.toString()}}]})},{name:"netnet_deposit",inputSchema:{type:"object",properties:{amount:_},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=M(t.amount);await l();let i=[e.approval(d.address,a,r.toString(),s),e.unsignedTx({to:a,data:v({abi:o,functionName:"deposit",args:[r,n]}),value:"0",chainId:s,description:`Deposit ${e.formatAmount(r.toString(),d.decimals)} USDG into NetNet Credit.`})];return A(i,n,"Approve the exact USDG amount, then deposit into NetNet Credit.")})},{name:"netnet_withdraw",inputSchema:{type:"object",properties:{amount:{anyOf:[_,{const:"max",description:"Redeem the fresh full nnUSDG share balance."}]}},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=t.amount==="max"?void 0:M(t.amount),i=await l(),p,u;if(r===void 0){let c=await i.readContract({address:a,abi:o,functionName:"balanceOf",args:[n]});if(c===0n)throw new m("This wallet has no NetNet shares to redeem.");p=v({abi:o,functionName:"redeem",args:[c,n,n]}),u=`Redeem all ${e.formatAmount(c.toString(),N.decimals)} nnUSDG shares for USDG.`}else p=v({abi:o,functionName:"withdraw",args:[r,n,n]}),u=`Withdraw ${e.formatAmount(r.toString(),d.decimals)} USDG from NetNet Credit (unmeasured on the recorded fork; full exit uses amount "max" redeem).`;return A([e.unsignedTx({to:a,data:p,value:"0",chainId:s,description:u})],n,u)})}]}};function ie(e){return E("netnet",[q(e),S(e),k(e),G(e),$(e),U(e),I(e),{tools:b(e,"netnet",[{vault:a,asset:d}])}])}export{q as a,ie as b};
@@ -1 +1 @@
1
- import{d as n,f as a,g as s,h as l,i as u}from"./EC5W3UZD.js";import{c as e}from"./HZUWK5B2.js";var m="In-kind exits are a separate unsupported flow.";function b(t,i){return n(t,i,e)}function V(t,i,o,r,x,p){return a(t,i,o,r,x,p,e)}function A(t,i,o){return s(t,i,o,e,m)}function P(t){return l(t,e.symbol)}function S(t,i,o,r){u(t,i,o,r,e)}export{b as a,V as b,A as c,P as d,S as e};
1
+ import{d as n,f as a,g as s,h as l,i as u}from"./EC5W3UZD.js";import{c as e}from"./46ZA2R5L.js";var m="In-kind exits are a separate unsupported flow.";function b(t,i){return n(t,i,e)}function V(t,i,o,r,x,p){return a(t,i,o,r,x,p,e)}function A(t,i,o){return s(t,i,o,e,m)}function P(t){return l(t,e.symbol)}function S(t,i,o,r){u(t,i,o,r,e)}export{b as a,V as b,A as c,P as d,S as e};
@@ -1 +1 @@
1
- import{a as d}from"./O47JXRXN.js";import{K as O}from"./5H3MQWH7.js";import{a as v}from"./6IM6A5VA.js";import{a as A}from"./UWOFA6GV.js";import{d as k,i as T}from"./73N3TOJL.js";import{a as p}from"./XPFVT2EA.js";import{a as r}from"./5YS5V2LK.js";import{a as g}from"./JXOEJPJ4.js";import{encodeFunctionData as C,getAddress as l,parseAbi as E,zeroAddress as N}from"viem";var w=E(["function owner() view returns (address)","function paused() view returns (bool)","function maximumLoanDuration() view returns (uint256)","function adminFeeInBasisPoints() view returns (uint16)","function pause()","function unpause()","function updateAdminFee(uint16)","function updateMaximumLoanDuration(uint256)","function setERC20Permit(address,bool)","function setERC20Permits(address[],bool[])","function getERC20Permit(address) view returns (bool)","function requestTransferOwnership(address)","function cancelTransferOwnership()","function acceptTransferOwnership()","function rejectTransferOwnership()"]),P=["pause","unpause","updateAdminFee","updateMaximumLoanDuration","setERC20Permit","setERC20Permits","requestTransferOwnership","cancelTransferOwnership","acceptTransferOwnership","rejectTransferOwnership"];function m(u){return T(u,"Provide an explicit checksummed address.",k)}var S=u=>{let h=(n,i,c,e)=>({name:n,inputSchema:{type:"object",properties:i,required:c,additionalProperties:!1},execute:async(s,t)=>{try{if(v(t),Object.keys(s).some(a=>!Object.hasOwn(i,a)))throw new r("Unsupported Longbow administration argument.");return await e(s,t)}catch(a){throw new r(u.plainError(a))}}});async function b(){let n=u.clientFor(p);if(await n.getChainId()!==p)throw new r("Longbow requires chain 4663.");return n}return{tools:[h("longbow_nft_admin",{token:{type:"string"}},[],async n=>{let i=await b(),c=["owner","paused","maximumLoanDuration","adminFeeInBasisPoints"],e=await Promise.all(c.map(s=>i.readContract({address:d,abi:w,functionName:s})));return{chainId:p,contract:d,...Object.fromEntries(c.map((s,t)=>[s,typeof e[t]=="bigint"?String(e[t]):e[t]])),...n.token===void 0?{}:{token:m(n.token),permitted:await i.readContract({address:d,abi:w,functionName:"getERC20Permit",args:[m(n.token)]})}}}),h("longbow_manage_nft",{operation:{type:"string",enum:P},value:A(),account:{type:"string"},enabled:{type:"boolean"},tokens:{type:"array",maxItems:32,items:{type:"string"}},permissions:{type:"array",maxItems:32,items:{type:"boolean"}}},["operation"],async(n,i)=>{if(typeof n.operation!="string"||!P.includes(n.operation))throw new r("Choose a documented NFT administration operation.");let c=await b(),e=n.operation,s=e.startsWith("update")?["operation","value"]:e==="setERC20Permit"?["operation","account","enabled"]:e==="setERC20Permits"?["operation","tokens","permissions"]:e==="requestTransferOwnership"?["operation","account"]:["operation"];if(Object.keys(n).some(o=>!s.includes(o)))throw new r("Unexpected fields for this NFT administration operation.");if(!["acceptTransferOwnership","rejectTransferOwnership"].includes(e)){let o=await c.readContract({address:d,abi:w,functionName:"owner"});if(l(o)!==l(i))throw new r("This wallet lacks the NFT loan owner role.")}let t=[];if(e.startsWith("update")){let o=O(n.value,!0);if(o>(e==="updateAdminFee"?10000n:(1n<<32n)-1n))throw new r("NFT fee/duration exceeds the contract limit.");t=[e==="updateAdminFee"?Number(o):o]}else if(e==="setERC20Permit"){if(typeof n.enabled!="boolean")throw new r("Provide enabled as a boolean.");t=[m(n.account),n.enabled]}else if(e==="setERC20Permits"){if(!Array.isArray(n.tokens)||!Array.isArray(n.permissions)||!n.tokens.length||n.tokens.length>32||n.tokens.length!==n.permissions.length||n.permissions.some(f=>typeof f!="boolean"))throw new r("Provide equal bounded token and permission arrays.");let o=n.tokens.map(m);if(new Set(o).size!==o.length)throw new r("Currency tokens must be unique.");t=[o,n.permissions]}else if(e==="requestTransferOwnership"){let o=m(n.account);if(o===N)throw new r("New owner must be nonzero.");t=[o]}let a=`Longbow NFT protocol administration ${e} on ${d}, values ${JSON.stringify(t,(o,f)=>typeof f=="bigint"?String(f):f)}. This changes protocol-wide settings or authority. Ownership acceptance/rejection requires the pending owner; the contract preview verifies that role. Permitting a currency here does not qualify it for Oak\u2019s borrower tools.`,y=[u.unsignedTx({to:d,data:C({abi:w,functionName:e,args:t}),value:"0",chainId:p,description:a})];return{txs:y,preview:await u.preview(y,i),summary:a}}),h("longbow_referral",{},[],async(n,i)=>{let c=await u.http(`https://longbow.credit/api/referral/stats/${l(i)}`,{method:"GET",redirect:"error"});if(!c.ok)throw new r(`Longbow referral service returned HTTP ${c.status}; referral state is unavailable.`);let e=await c.json();if(!e||typeof e!="object"||m(e.address)!==l(i))throw new r("Referral response does not match this wallet.");let s=a=>{if(typeof a!="number"||!Number.isSafeInteger(a)||a<0)throw new r("Invalid referral count.");return a},t=e.bonusEarnedAllTime;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new r("Invalid referral bonus estimate.");if(e.code!==null&&e.code!==void 0&&(typeof e.code!="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(e.code)))throw new r("Invalid referral code.");return{address:l(i),chainId:p,code:e.code??null,referrals:s(e.referrals),activeThisEpoch:s(e.activeThisEpoch),bonusEstimateUsd:t,source:"Longbow public referral service; off-chain estimates, not verified payments.",warning:g("Referral links are permanent according to the app. Registration/linking publishes wallet associations and requires a separate authorized publication flow. This tool only reads stats; no payout or claim is promised.")}})]}};export{w as a,S as b};
1
+ import{K as O}from"./JC4SYMBV.js";import{a as d}from"./O47JXRXN.js";import{a as v}from"./6IM6A5VA.js";import{a as A}from"./UWOFA6GV.js";import{d as k,i as T}from"./73N3TOJL.js";import{a as p}from"./XPFVT2EA.js";import{a as r}from"./5YS5V2LK.js";import{a as g}from"./JXOEJPJ4.js";import{encodeFunctionData as C,getAddress as l,parseAbi as E,zeroAddress as N}from"viem";var w=E(["function owner() view returns (address)","function paused() view returns (bool)","function maximumLoanDuration() view returns (uint256)","function adminFeeInBasisPoints() view returns (uint16)","function pause()","function unpause()","function updateAdminFee(uint16)","function updateMaximumLoanDuration(uint256)","function setERC20Permit(address,bool)","function setERC20Permits(address[],bool[])","function getERC20Permit(address) view returns (bool)","function requestTransferOwnership(address)","function cancelTransferOwnership()","function acceptTransferOwnership()","function rejectTransferOwnership()"]),P=["pause","unpause","updateAdminFee","updateMaximumLoanDuration","setERC20Permit","setERC20Permits","requestTransferOwnership","cancelTransferOwnership","acceptTransferOwnership","rejectTransferOwnership"];function m(u){return T(u,"Provide an explicit checksummed address.",k)}var S=u=>{let h=(n,i,c,e)=>({name:n,inputSchema:{type:"object",properties:i,required:c,additionalProperties:!1},execute:async(s,t)=>{try{if(v(t),Object.keys(s).some(a=>!Object.hasOwn(i,a)))throw new r("Unsupported Longbow administration argument.");return await e(s,t)}catch(a){throw new r(u.plainError(a))}}});async function b(){let n=u.clientFor(p);if(await n.getChainId()!==p)throw new r("Longbow requires chain 4663.");return n}return{tools:[h("longbow_nft_admin",{token:{type:"string"}},[],async n=>{let i=await b(),c=["owner","paused","maximumLoanDuration","adminFeeInBasisPoints"],e=await Promise.all(c.map(s=>i.readContract({address:d,abi:w,functionName:s})));return{chainId:p,contract:d,...Object.fromEntries(c.map((s,t)=>[s,typeof e[t]=="bigint"?String(e[t]):e[t]])),...n.token===void 0?{}:{token:m(n.token),permitted:await i.readContract({address:d,abi:w,functionName:"getERC20Permit",args:[m(n.token)]})}}}),h("longbow_manage_nft",{operation:{type:"string",enum:P},value:A(),account:{type:"string"},enabled:{type:"boolean"},tokens:{type:"array",maxItems:32,items:{type:"string"}},permissions:{type:"array",maxItems:32,items:{type:"boolean"}}},["operation"],async(n,i)=>{if(typeof n.operation!="string"||!P.includes(n.operation))throw new r("Choose a documented NFT administration operation.");let c=await b(),e=n.operation,s=e.startsWith("update")?["operation","value"]:e==="setERC20Permit"?["operation","account","enabled"]:e==="setERC20Permits"?["operation","tokens","permissions"]:e==="requestTransferOwnership"?["operation","account"]:["operation"];if(Object.keys(n).some(o=>!s.includes(o)))throw new r("Unexpected fields for this NFT administration operation.");if(!["acceptTransferOwnership","rejectTransferOwnership"].includes(e)){let o=await c.readContract({address:d,abi:w,functionName:"owner"});if(l(o)!==l(i))throw new r("This wallet lacks the NFT loan owner role.")}let t=[];if(e.startsWith("update")){let o=O(n.value,!0);if(o>(e==="updateAdminFee"?10000n:(1n<<32n)-1n))throw new r("NFT fee/duration exceeds the contract limit.");t=[e==="updateAdminFee"?Number(o):o]}else if(e==="setERC20Permit"){if(typeof n.enabled!="boolean")throw new r("Provide enabled as a boolean.");t=[m(n.account),n.enabled]}else if(e==="setERC20Permits"){if(!Array.isArray(n.tokens)||!Array.isArray(n.permissions)||!n.tokens.length||n.tokens.length>32||n.tokens.length!==n.permissions.length||n.permissions.some(f=>typeof f!="boolean"))throw new r("Provide equal bounded token and permission arrays.");let o=n.tokens.map(m);if(new Set(o).size!==o.length)throw new r("Currency tokens must be unique.");t=[o,n.permissions]}else if(e==="requestTransferOwnership"){let o=m(n.account);if(o===N)throw new r("New owner must be nonzero.");t=[o]}let a=`Longbow NFT protocol administration ${e} on ${d}, values ${JSON.stringify(t,(o,f)=>typeof f=="bigint"?String(f):f)}. This changes protocol-wide settings or authority. Ownership acceptance/rejection requires the pending owner; the contract preview verifies that role. Permitting a currency here does not qualify it for Oak\u2019s borrower tools.`,y=[u.unsignedTx({to:d,data:C({abi:w,functionName:e,args:t}),value:"0",chainId:p,description:a})];return{txs:y,preview:await u.preview(y,i),summary:a}}),h("longbow_referral",{},[],async(n,i)=>{let c=await u.http(`https://longbow.credit/api/referral/stats/${l(i)}`,{method:"GET",redirect:"error"});if(!c.ok)throw new r(`Longbow referral service returned HTTP ${c.status}; referral state is unavailable.`);let e=await c.json();if(!e||typeof e!="object"||m(e.address)!==l(i))throw new r("Referral response does not match this wallet.");let s=a=>{if(typeof a!="number"||!Number.isSafeInteger(a)||a<0)throw new r("Invalid referral count.");return a},t=e.bonusEarnedAllTime;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new r("Invalid referral bonus estimate.");if(e.code!==null&&e.code!==void 0&&(typeof e.code!="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(e.code)))throw new r("Invalid referral code.");return{address:l(i),chainId:p,code:e.code??null,referrals:s(e.referrals),activeThisEpoch:s(e.activeThisEpoch),bonusEstimateUsd:t,source:"Longbow public referral service; off-chain estimates, not verified payments.",warning:g("Referral links are permanent according to the app. Registration/linking publishes wallet associations and requires a separate authorized publication flow. This tool only reads stats; no payout or claim is promised.")}})]}};export{w as a,S as b};
@@ -1 +1 @@
1
- import{a as c,b as T,e as v,f as F,g as I}from"./ITIIHCZK.js";import{a as l}from"./UWOFA6GV.js";import{c as A,g,h as S}from"./73N3TOJL.js";import{a as h}from"./XPFVT2EA.js";import{a as d}from"./5YS5V2LK.js";import{encodeFunctionData as y,getAddress as M,parseAbi as j,parseAbiItem as D,zeroAddress as H}from"viem";var x=M("0x000000001f26a0044baa66024e7b6599c61963f8"),_=D("event AuctionCreated(address indexed auction,address indexed token,uint256 amount,bytes configData)"),n=j(["function currency() view returns (address)","function token() view returns (address)","function startBlock() view returns (uint64)","function endBlock() view returns (uint64)","function claimBlock() view returns (uint64)","function validationHook() view returns (address)","function clearingPrice() view returns (uint256)","function isGraduated() view returns (bool)","function bids(uint256) view returns ((uint64 startBlock,uint24 startCumulativeMps,uint64 exitedBlock,uint256 maxPrice,address owner,uint256 amountQ96,uint256 tokensFilled))","function submitBid(uint256 maxPrice,uint128 amount,address owner,uint256 prevTickPrice,bytes hookData) payable returns (uint256)","function exitBid(uint256)","function exitPartiallyFilledBid(uint256,uint64,uint64)","function claimTokens(uint256)","function claimTokensBatch(address,uint256[])","function checkpoint()","function sweepCurrency()","function sweepUnsoldTokens()"]);async function $(s,B){let o=T(B.auction),t=c(B.creationBlock,"creationBlock",64,!0),e=await s.getLogs({address:x,event:_,args:{auction:o},fromBlock:t,toBlock:t,strict:!0});if(e.length!==1||!g(e[0].address,x)||!S(e[0].args.auction,o))throw new d("Auction has no matching AuctionCreated event at the pinned CCA factory and creationBlock.");return o}async function Q(s,B){let o=s.clientFor(h),t=await $(o,B),e=await o.getBlockNumber(),[a,k,i,b,m,C,u,w]=await Promise.all([o.readContract({address:t,abi:n,functionName:"currency",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"token",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"startBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"endBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"claimBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"validationHook",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"clearingPrice",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"isGraduated",blockNumber:e})]);return{auction:t,currency:a,saleToken:k,startBlock:i,endBlock:b,claimBlock:m,validationHook:C,clearingPrice:u,graduated:w,blockNumber:e}}var U={auction:A,creationBlock:l(),bidId:l(),amount:l(),maxPrice:l(),prevTickPrice:l(),lastFullyFilledCheckpointBlock:l(),outbidBlock:l(),mode:{type:"string",enum:["full","partial"]},bidIds:{type:"array",minItems:1,maxItems:50,items:l()}};function R(s){let o=["status","bid","exit","claim","checkpoint","sweep_currency","sweep_tokens"].map(t=>({name:`uniswap_auction_${t}`,inputSchema:{type:"object",additionalProperties:!1,required:["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode"]:[]],properties:U},async execute(e,a){I(e,["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode","lastFullyFilledCheckpointBlock","outbidBlock"]:t==="claim"?["bidId","bidIds"]:t==="status"?["bidId"]:[]]);let i=await Q(s,e),b=s.clientFor(h),[m,C]=await Promise.all([v(s,i.currency,i.blockNumber),v(s,i.saleToken,i.blockNumber)]),u=e.bidId===void 0?void 0:await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[c(e.bidId,"bidId",256,!0)],blockNumber:i.blockNumber});if(t==="status")return{auction:i.auction,paymentToken:m,saleToken:C,startBlock:i.startBlock.toString(),endBlock:i.endBlock.toString(),claimBlock:i.claimBlock.toString(),validationHook:i.validationHook,clearingPrice:i.clearingPrice.toString(),graduated:i.graduated,...u?{bid:{...u,startBlock:u.startBlock.toString(),exitedBlock:u.exitedBlock.toString(),maxPrice:u.maxPrice.toString(),amountQ96:u.amountQ96.toString(),tokensFilled:u.tokensFilled.toString()}}:{},summary:"CCA prices use currency-base-units per sale-token-base-unit in Q96. Clearing price/graduation reflect the latest checkpoint and may lag the head."};let w=[],f,N=0n;if(t==="bid"){if(i.validationHook!==H)throw new d("This auction has a validation hook. Its validation/signing contract is not configured; do not pass an off-chain signature manually.");if(i.blockNumber<i.startBlock||i.blockNumber>=i.endBlock)throw new d("Auction is not in its bidding window.");let r=c(e.amount,"amount",128),p=c(e.maxPrice,"maxPrice"),P=c(e.prevTickPrice,"prevTickPrice",256,!0);if(p<=i.clearingPrice)throw new d("Bid maxPrice must be above the checkpoint clearing price.");i.currency===H?N=r:w.push(s.approval(i.currency,i.auction,r.toString(),h)),f=y({abi:n,functionName:"submitBid",args:[p,r,a,P,"0x"]})}else if(t==="exit"){if(!u||!g(u.owner,a))throw new d("Only exit a bid owned by the signing wallet.");let r=c(e.bidId,"bidId",256,!0);if(e.mode==="full"){if(e.lastFullyFilledCheckpointBlock!==void 0||e.outbidBlock!==void 0)throw new d("Full exit takes no checkpoint hints.");f=y({abi:n,functionName:"exitBid",args:[r]})}else if(e.mode==="partial")f=y({abi:n,functionName:"exitPartiallyFilledBid",args:[r,c(e.lastFullyFilledCheckpointBlock,"lastFullyFilledCheckpointBlock",64,!0),c(e.outbidBlock,"outbidBlock",64,!0)]});else throw new d("Choose full or partial exit explicitly; partial exits require checkpoint hints.")}else if(t==="claim"){if(e.bidId===void 0==(e.bidIds===void 0))throw new d("Provide bidId or bidIds, not both.");let r=e.bidIds===void 0?[c(e.bidId,"bidId",256,!0)]:Array.isArray(e.bidIds)?e.bidIds.map(p=>c(p,"bidIds",256,!0)):[];if(r.length<1||r.length>50||new Set(r.map(String)).size!==r.length)throw new d("Provide 1 to 50 unique bid IDs.");for(let p of r){let P=await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[p],blockNumber:i.blockNumber});if(!g(P.owner,a))throw new d("Claimed tokens must belong to the signing wallet.")}f=y({abi:n,functionName:"claimTokensBatch",args:[a,r]})}else f=y({abi:n,functionName:t==="checkpoint"?"checkpoint":t==="sweep_currency"?"sweepCurrency":"sweepUnsoldTokens"});return w.push(s.unsignedTx({to:i.auction,data:f,value:N.toString(),chainId:h,description:`CCA ${t} on factory-verified auction ${i.auction}. Bid owner ${a}.`})),F(s,w,a,`CCA ${t}; checkpoint/exit/claim eligibility and creator-only sweeps are checked by the contract in preview. Sweeps pay the auction's immutable funds/tokens recipient, not an arbitrary recipient.`)}}));return o.push({name:"uniswap_auctions",inputSchema:{type:"object",additionalProperties:!1,properties:{fromBlock:l(),toBlock:l()}},async execute(t){I(t,["fromBlock","toBlock"]);let e=s.clientFor(h),a=await e.getBlockNumber(),k=t.fromBlock===void 0?a>9999n?a-9999n:0n:c(t.fromBlock,"fromBlock",64,!0),i=t.toBlock===void 0?a:c(t.toBlock,"toBlock",64,!0);if(k>i||i>a||i-k>=10000n)throw new d("Scan an ordered range of at most 10000 blocks, ending at or before the head.");let b=await e.getLogs({address:x,event:_,fromBlock:k,toBlock:i,strict:!0});return{factory:x,fromBlock:k.toString(),toBlock:i.toString(),auctions:b.map(m=>({auction:m.args.auction,token:m.args.token,amount:m.args.amount.toString(),creationBlock:m.blockNumber.toString()})),summary:"Factory-verified auctions in this block window only. An empty result does not establish that no auctions exist outside it. Scan earlier windows for older launches."}}}),{tools:o}}export{x as a,_ as b,n as c,$ as d,Q as e,R as f};
1
+ import{a as c,b as T,e as v,f as F,g as I}from"./64AF7ECA.js";import{a as l}from"./UWOFA6GV.js";import{c as A,g,h as S}from"./73N3TOJL.js";import{a as h}from"./XPFVT2EA.js";import{a as d}from"./5YS5V2LK.js";import{encodeFunctionData as y,getAddress as M,parseAbi as j,parseAbiItem as D,zeroAddress as H}from"viem";var x=M("0x000000001f26a0044baa66024e7b6599c61963f8"),_=D("event AuctionCreated(address indexed auction,address indexed token,uint256 amount,bytes configData)"),n=j(["function currency() view returns (address)","function token() view returns (address)","function startBlock() view returns (uint64)","function endBlock() view returns (uint64)","function claimBlock() view returns (uint64)","function validationHook() view returns (address)","function clearingPrice() view returns (uint256)","function isGraduated() view returns (bool)","function bids(uint256) view returns ((uint64 startBlock,uint24 startCumulativeMps,uint64 exitedBlock,uint256 maxPrice,address owner,uint256 amountQ96,uint256 tokensFilled))","function submitBid(uint256 maxPrice,uint128 amount,address owner,uint256 prevTickPrice,bytes hookData) payable returns (uint256)","function exitBid(uint256)","function exitPartiallyFilledBid(uint256,uint64,uint64)","function claimTokens(uint256)","function claimTokensBatch(address,uint256[])","function checkpoint()","function sweepCurrency()","function sweepUnsoldTokens()"]);async function $(s,B){let o=T(B.auction),t=c(B.creationBlock,"creationBlock",64,!0),e=await s.getLogs({address:x,event:_,args:{auction:o},fromBlock:t,toBlock:t,strict:!0});if(e.length!==1||!g(e[0].address,x)||!S(e[0].args.auction,o))throw new d("Auction has no matching AuctionCreated event at the pinned CCA factory and creationBlock.");return o}async function Q(s,B){let o=s.clientFor(h),t=await $(o,B),e=await o.getBlockNumber(),[a,k,i,b,m,C,u,w]=await Promise.all([o.readContract({address:t,abi:n,functionName:"currency",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"token",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"startBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"endBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"claimBlock",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"validationHook",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"clearingPrice",blockNumber:e}),o.readContract({address:t,abi:n,functionName:"isGraduated",blockNumber:e})]);return{auction:t,currency:a,saleToken:k,startBlock:i,endBlock:b,claimBlock:m,validationHook:C,clearingPrice:u,graduated:w,blockNumber:e}}var U={auction:A,creationBlock:l(),bidId:l(),amount:l(),maxPrice:l(),prevTickPrice:l(),lastFullyFilledCheckpointBlock:l(),outbidBlock:l(),mode:{type:"string",enum:["full","partial"]},bidIds:{type:"array",minItems:1,maxItems:50,items:l()}};function R(s){let o=["status","bid","exit","claim","checkpoint","sweep_currency","sweep_tokens"].map(t=>({name:`uniswap_auction_${t}`,inputSchema:{type:"object",additionalProperties:!1,required:["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode"]:[]],properties:U},async execute(e,a){I(e,["auction","creationBlock",...t==="bid"?["amount","maxPrice","prevTickPrice"]:t==="exit"?["bidId","mode","lastFullyFilledCheckpointBlock","outbidBlock"]:t==="claim"?["bidId","bidIds"]:t==="status"?["bidId"]:[]]);let i=await Q(s,e),b=s.clientFor(h),[m,C]=await Promise.all([v(s,i.currency,i.blockNumber),v(s,i.saleToken,i.blockNumber)]),u=e.bidId===void 0?void 0:await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[c(e.bidId,"bidId",256,!0)],blockNumber:i.blockNumber});if(t==="status")return{auction:i.auction,paymentToken:m,saleToken:C,startBlock:i.startBlock.toString(),endBlock:i.endBlock.toString(),claimBlock:i.claimBlock.toString(),validationHook:i.validationHook,clearingPrice:i.clearingPrice.toString(),graduated:i.graduated,...u?{bid:{...u,startBlock:u.startBlock.toString(),exitedBlock:u.exitedBlock.toString(),maxPrice:u.maxPrice.toString(),amountQ96:u.amountQ96.toString(),tokensFilled:u.tokensFilled.toString()}}:{},summary:"CCA prices use currency-base-units per sale-token-base-unit in Q96. Clearing price/graduation reflect the latest checkpoint and may lag the head."};let w=[],f,N=0n;if(t==="bid"){if(i.validationHook!==H)throw new d("This auction has a validation hook. Its validation/signing contract is not configured; do not pass an off-chain signature manually.");if(i.blockNumber<i.startBlock||i.blockNumber>=i.endBlock)throw new d("Auction is not in its bidding window.");let r=c(e.amount,"amount",128),p=c(e.maxPrice,"maxPrice"),P=c(e.prevTickPrice,"prevTickPrice",256,!0);if(p<=i.clearingPrice)throw new d("Bid maxPrice must be above the checkpoint clearing price.");i.currency===H?N=r:w.push(s.approval(i.currency,i.auction,r.toString(),h)),f=y({abi:n,functionName:"submitBid",args:[p,r,a,P,"0x"]})}else if(t==="exit"){if(!u||!g(u.owner,a))throw new d("Only exit a bid owned by the signing wallet.");let r=c(e.bidId,"bidId",256,!0);if(e.mode==="full"){if(e.lastFullyFilledCheckpointBlock!==void 0||e.outbidBlock!==void 0)throw new d("Full exit takes no checkpoint hints.");f=y({abi:n,functionName:"exitBid",args:[r]})}else if(e.mode==="partial")f=y({abi:n,functionName:"exitPartiallyFilledBid",args:[r,c(e.lastFullyFilledCheckpointBlock,"lastFullyFilledCheckpointBlock",64,!0),c(e.outbidBlock,"outbidBlock",64,!0)]});else throw new d("Choose full or partial exit explicitly; partial exits require checkpoint hints.")}else if(t==="claim"){if(e.bidId===void 0==(e.bidIds===void 0))throw new d("Provide bidId or bidIds, not both.");let r=e.bidIds===void 0?[c(e.bidId,"bidId",256,!0)]:Array.isArray(e.bidIds)?e.bidIds.map(p=>c(p,"bidIds",256,!0)):[];if(r.length<1||r.length>50||new Set(r.map(String)).size!==r.length)throw new d("Provide 1 to 50 unique bid IDs.");for(let p of r){let P=await b.readContract({address:i.auction,abi:n,functionName:"bids",args:[p],blockNumber:i.blockNumber});if(!g(P.owner,a))throw new d("Claimed tokens must belong to the signing wallet.")}f=y({abi:n,functionName:"claimTokensBatch",args:[a,r]})}else f=y({abi:n,functionName:t==="checkpoint"?"checkpoint":t==="sweep_currency"?"sweepCurrency":"sweepUnsoldTokens"});return w.push(s.unsignedTx({to:i.auction,data:f,value:N.toString(),chainId:h,description:`CCA ${t} on factory-verified auction ${i.auction}. Bid owner ${a}.`})),F(s,w,a,`CCA ${t}; checkpoint/exit/claim eligibility and creator-only sweeps are checked by the contract in preview. Sweeps pay the auction's immutable funds/tokens recipient, not an arbitrary recipient.`)}}));return o.push({name:"uniswap_auctions",inputSchema:{type:"object",additionalProperties:!1,properties:{fromBlock:l(),toBlock:l()}},async execute(t){I(t,["fromBlock","toBlock"]);let e=s.clientFor(h),a=await e.getBlockNumber(),k=t.fromBlock===void 0?a>9999n?a-9999n:0n:c(t.fromBlock,"fromBlock",64,!0),i=t.toBlock===void 0?a:c(t.toBlock,"toBlock",64,!0);if(k>i||i>a||i-k>=10000n)throw new d("Scan an ordered range of at most 10000 blocks, ending at or before the head.");let b=await e.getLogs({address:x,event:_,fromBlock:k,toBlock:i,strict:!0});return{factory:x,fromBlock:k.toString(),toBlock:i.toString(),auctions:b.map(m=>({auction:m.args.auction,token:m.args.token,amount:m.args.amount.toString(),creationBlock:m.blockNumber.toString()})),summary:"Factory-verified auctions in this block window only. An empty result does not establish that no auctions exist outside it. Scan earlier windows for older launches."}}}),{tools:o}}export{x as a,_ as b,n as c,$ as d,Q as e,R as f};
@@ -1 +1 @@
1
- import{m as A,n as q}from"./D3OWLDVB.js";import{b as U,i as C,n as X,o as F,q as V}from"./CCEWSOBT.js";import{a as $}from"./RFJCG4NA.js";import{b as j,e as O,h as z}from"./HZUWK5B2.js";import{a as y,b as h}from"./XCFA73P2.js";import{a as v}from"./LIUXNOLP.js";import{a as P}from"./OG5HRQU4.js";import{a as S}from"./RETS2ZEK.js";import{o as g}from"./IWALIX7Q.js";import{a as m,b as f,c as W,d as k,i as w,j as R,k as K,p as B}from"./XPFVT2EA.js";import{a as c}from"./5YS5V2LK.js";import{a as T,b as H}from"./JXOEJPJ4.js";import{getAddress as b,isAddress as D,parseAbi as ie}from"viem";var Y=[{inputs:[],name:"available",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"ethUsdE18",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"liquidityUsdgE6",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"phase",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"priceSigner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"signer",type:"address"}],name:"setPriceSigner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"spotOakPerEthE18",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"supplyNet",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"syncPhase",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"wallet",type:"address"},{internalType:"uint256",name:"oakPerEthE18",type:"uint256"},{internalType:"uint64",name:"timestamp",type:"uint64"},{internalType:"bytes32",name:"nonce",type:"bytes32"}],internalType:"struct PriceNote",name:"n",type:"tuple"},{internalType:"bytes",name:"sig",type:"bytes"},{internalType:"address",name:"boundWallet",type:"address"}],name:"verifyNote",outputs:[{internalType:"uint256",name:"oakPerEthE18",type:"uint256"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"signer",type:"address"}],name:"PriceSignerSet",type:"event"},{inputs:[],name:"NotReady",type:"error"},{inputs:[],name:"NoteBadSignature",type:"error"},{inputs:[],name:"NoteExpired",type:"error"},{inputs:[],name:"NoteNotYetValid",type:"error"},{inputs:[{internalType:"uint256",name:"spot",type:"uint256"},{internalType:"uint256",name:"note",type:"uint256"}],name:"NoteOutsideGuard",type:"error"},{inputs:[],name:"NoteWrongWallet",type:"error"},{inputs:[{internalType:"address",name:"source",type:"address"}],name:"OracleUnreadable",type:"error"}];var M=300,re="1000000000000000000",J=b(w[m].tokens.USDG.address),Q=b(w[f].deployments.test_USDG.address),_=b(w[m].tokens.WETH.address),I=b(w[f].deployments.test_WETH.address);function Z(n){let e=n.address.toLowerCase();return n.chainId===m?e===J.toLowerCase():n.chainId===f?e===Q.toLowerCase():!1}function ee(n){return n.chainId!==m&&n.chainId!==f?!1:h(n.address)===y}function te(n){let e=n.address.toLowerCase();return n.chainId===m?e===_.toLowerCase():n.chainId===f?e===I.toLowerCase():!1}function ae(n){return ee(n)||te(n)}var se=-887272,oe=887272,de=(1n<<256n)-1n,ce=ie(["function observe(uint32[] secondsAgos) view returns (int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s)","function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)"]);function L(n,e){if(typeof n=="bigint")return n;if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new c(`Invalid ${e} timestamp.`);return BigInt(n)}if(typeof n=="string"&&/^-?\d+$/.test(n.trim()))return BigInt(n.trim());throw new c(`Invalid ${e} timestamp.`)}function Pe(n,e=BigInt(Math.floor(Date.now()/1e3)),t=M){try{return p(n,e,t),!0}catch{return!1}}function p(n,e=BigInt(Math.floor(Date.now()/1e3)),t=M){if(!Number.isInteger(t)||t<0)throw new c("Maximum price age must be a non-negative integer.");let a=L(n,"price"),s=L(e,"current");if(a<=0n)throw new c("Price timestamp must be positive.");if(a>s)throw new c("Price timestamp is in the future.");let r=s-a;if(r>BigInt(t))throw new c(`Price is stale: age ${r}s exceeds ${t}s.`);return a.toString()}function ue(n){if(!Number.isInteger(n)||n<se||n>oe)throw new c(`Tick ${n} is outside valid Uniswap bounds.`);let e=BigInt(n<0?-n:n),t=(e&0x1n)!==0n?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&0x2n)!==0n&&(t=t*0xfff97272373d413259a46990580e213an>>128n),(e&0x4n)!==0n&&(t=t*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&0x8n)!==0n&&(t=t*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&0x10n)!==0n&&(t=t*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&0x20n)!==0n&&(t=t*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&0x40n)!==0n&&(t=t*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&0x80n)!==0n&&(t=t*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&0x100n)!==0n&&(t=t*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&0x200n)!==0n&&(t=t*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&0x400n)!==0n&&(t=t*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&0x800n)!==0n&&(t=t*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&0x1000n)!==0n&&(t=t*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&0x2000n)!==0n&&(t=t*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&0x4000n)!==0n&&(t=t*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&0x8000n)!==0n&&(t=t*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&0x10000n)!==0n&&(t=t*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&0x20000n)!==0n&&(t=t*0x5d6af8dedb81196699c329225ee604n>>128n),(e&0x40000n)!==0n&&(t=t*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&0x80000n)!==0n&&(t=t*0x48a170391f7dc42444e8fa2n>>128n),n>0&&(t=de/t),(t>>32n)+(t%(1n<<32n)===0n?0n:1n)}async function me(n,e,t){if(typeof n=="object"&&n!==null){let i=n.chainId??e,o=h(n.address)===y?y:b(n.address),d={address:o,symbol:n.symbol,decimals:n.decimals,chainId:i};return Z(d)?{address:o,symbol:"USDG",decimals:k,chainId:i}:ee(d)?{address:y,symbol:"ETH",decimals:18,chainId:i}:te(d)?{address:o,symbol:"WETH",decimals:18,chainId:i}:t.officialStockTokens?z(d,t.officialStockTokens):d}let a=n.trim(),s=a.toUpperCase(),r=a.toLowerCase();if(s==="ETH"||D(a,{strict:!1})&&h(a)===y)return{...j,chainId:e};if(s==="WETH"||e===m&&r===_.toLowerCase()||e===f&&r===I.toLowerCase()){if(e!==m&&e!==f)throw new c(`No canonical WETH address configured for chain ${e}.`);return{address:e===f?I:_,symbol:"WETH",decimals:18,chainId:e}}if(s==="USDG"||e===m&&r===R.toLowerCase()||e===f&&r===K.toLowerCase()){if(e!==m&&e!==f)throw new c(`No canonical USDG address configured for chain ${e}.`);return{address:e===f?Q:J,symbol:"USDG",decimals:k,chainId:e}}if(e===m&&(s==="USDE"||r===O.address.toLowerCase()))return{...O,chainId:e};let u=t.oakTokenAddress??process.env.OAK_TOKEN_ADDRESS;if(s==="OAK"||u&&a.toLowerCase()===u.toLowerCase()){if(!u&&!D(a,{strict:!1}))throw new c("OAK token address is required to price OAK.");return{address:b(u??a),symbol:"OAK",decimals:W,chainId:e}}if(t.officialStockTokens){let i=t.officialStockTokens.find(o=>o.chainId===e&&o.symbol.toUpperCase()===s);if(i)return i;if(D(a,{strict:!1})){let o=b(a),d=t.officialStockTokens.find(l=>l.chainId===e&&l.address.toLowerCase()===o.toLowerCase());if(d)return d}}if(D(a,{strict:!1})){let i=b(a),o=t.client??g(t.rpcUrl,e),[d,l]=await Promise.all([P(o,e,i,"symbol",t.blockNumber),P(o,e,i,"decimals",t.blockNumber)]);return{address:i,symbol:d,decimals:Number(l),chainId:e}}throw new c(`Unknown token ${T(a)}.`)}async function N(n,e,t){if(e)return(await n.readContract({address:e,abi:Y,functionName:"ethUsdE18",blockNumber:t})).toString();let s=(await n.readContract({address:b(B),abi:ce,functionName:"observe",args:[[U,0]],blockNumber:t}))[0];if(!s||s.length<2)throw new c("ETH/USDG pool observation returned insufficient tick cumulatives.");let r=X(s[0],s[1],U),u=ue(r);return F(u)}async function x(n,e,t,a){if(n.timestamp!==void 0)return p(n.timestamp,t(),a);if(e&&typeof e.getBlock=="function"){let r=await v(e,n.blockNumber);return p(r.timestamp,t(),a)}let s=t();return p(s,s,a)}async function ve(n,e={}){let t=e.chainId??m,a=e.maxAgeSeconds??M,s=()=>e.now!==void 0?L(e.now,"current"):BigInt(Math.floor(Date.now()/1e3)),r=await me(n,t,e);if((H(r.symbol)||r.symbol.length>256)&&(r.symbol=T(r.symbol)),e.signedNote||e.priceNote){let i=e.signedNote?e.signedNote.note:e.priceNote,o=p(i.timestamp,s(),a);if(e.spotOakPerEthE18!==void 0&&!A(i.oakPerEthE18,e.spotOakPerEthE18))throw new c("Price note is outside the 50% spot guard band.");let d=e.signedNote?.signature??e.signature,l=e.signedNote?.consumer??e.consumer;if(d&&l){let G=await q({note:i,signature:d,consumer:l,signer:e.signer,now:s(),spotOakPerEthE18:e.spotOakPerEthE18,chainId:t});if(!G.valid)throw new c(G.error??"Price note verification failed.")}let E=e.ethUsdE18!==void 0?e.ethUsdE18.toString():await N(e.client??g(e.rpcUrl,t),e.oracleAddress);return{token:r,usdE18:C(E,i.oakPerEthE18),timestamp:o}}if(e.trades){let i=await x(e,e.client,s,a),o=V(e.trades,{now:s(),windowStart:e.windowStart,windowEnd:e.windowEnd});if(e.spotOakPerEthE18!==void 0&&!A(o,e.spotOakPerEthE18))throw new c("30-minute average is outside the 50% spot guard band.");let d=e.ethUsdE18!==void 0?e.ethUsdE18.toString():await N(e.client??g(e.rpcUrl,t),e.oracleAddress);return{token:r,usdE18:C(d,o),timestamp:i}}if(e.usdE18!==void 0){let i=await x(e,e.client,s,a),o=S(e.usdE18.toString());if(o<=0n)throw new c("USD price must be positive.");return{token:r,usdE18:o.toString(),timestamp:i}}if(e.resolver){let i=await e.resolver(r),o=p(i.timestamp,s(),a),d=S(i.usdE18);if(d<=0n)throw new c("USD price must be positive.");return{token:r,usdE18:d.toString(),timestamp:o}}let u=e.client??g(e.rpcUrl,t);if(Z(r)){let i=await x(e,u,s,a);return{token:r,usdE18:re,timestamp:i}}if(ae(r)){let i=await x(e,u,s,a),o=await N(u,e.oracleAddress,e.blockNumber);return{token:r,usdE18:o,timestamp:i}}if(r.chainId===m)try{let i=await v(u,e.blockNumber),o=p(i.timestamp,s(),a);if(i.number===null)throw new c("Pons reference requires a mined block.");let[d,l]=await Promise.all([$(r,u,i.number),N(u,e.oracleAddress,i.number)]),E=S(l)*d.numerator/d.denominator;if(E<=0n)throw new c("Pons USD reference price must be positive.");return{token:r,usdE18:E.toString(),timestamp:o}}catch{}throw new c(`No fresh on-chain price source available for token ${T(r.symbol)} (${r.address}).`)}export{M as a,re as b,Z as c,ee as d,te as e,ae as f,Pe as g,p as h,ue as i,ve as j};
1
+ import{m as A,n as q}from"./D3OWLDVB.js";import{b as U,i as C,n as X,o as F,q as V}from"./CCEWSOBT.js";import{a as $}from"./RFJCG4NA.js";import{b as j,e as O,h as z}from"./46ZA2R5L.js";import{a as y,b as h}from"./VJ3W2V3B.js";import{a as v}from"./LIUXNOLP.js";import{a as P}from"./OG5HRQU4.js";import{a as S}from"./RETS2ZEK.js";import{o as g}from"./IWALIX7Q.js";import{a as m,b as f,c as W,d as k,i as w,j as R,k as K,p as B}from"./XPFVT2EA.js";import{a as c}from"./5YS5V2LK.js";import{a as T,b as H}from"./JXOEJPJ4.js";import{getAddress as b,isAddress as D,parseAbi as ie}from"viem";var Y=[{inputs:[],name:"available",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"ethUsdE18",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"liquidityUsdgE6",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"phase",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"priceSigner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"signer",type:"address"}],name:"setPriceSigner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"spotOakPerEthE18",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"supplyNet",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"syncPhase",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"wallet",type:"address"},{internalType:"uint256",name:"oakPerEthE18",type:"uint256"},{internalType:"uint64",name:"timestamp",type:"uint64"},{internalType:"bytes32",name:"nonce",type:"bytes32"}],internalType:"struct PriceNote",name:"n",type:"tuple"},{internalType:"bytes",name:"sig",type:"bytes"},{internalType:"address",name:"boundWallet",type:"address"}],name:"verifyNote",outputs:[{internalType:"uint256",name:"oakPerEthE18",type:"uint256"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"signer",type:"address"}],name:"PriceSignerSet",type:"event"},{inputs:[],name:"NotReady",type:"error"},{inputs:[],name:"NoteBadSignature",type:"error"},{inputs:[],name:"NoteExpired",type:"error"},{inputs:[],name:"NoteNotYetValid",type:"error"},{inputs:[{internalType:"uint256",name:"spot",type:"uint256"},{internalType:"uint256",name:"note",type:"uint256"}],name:"NoteOutsideGuard",type:"error"},{inputs:[],name:"NoteWrongWallet",type:"error"},{inputs:[{internalType:"address",name:"source",type:"address"}],name:"OracleUnreadable",type:"error"}];var M=300,re="1000000000000000000",J=b(w[m].tokens.USDG.address),Q=b(w[f].deployments.test_USDG.address),_=b(w[m].tokens.WETH.address),I=b(w[f].deployments.test_WETH.address);function Z(n){let e=n.address.toLowerCase();return n.chainId===m?e===J.toLowerCase():n.chainId===f?e===Q.toLowerCase():!1}function ee(n){return n.chainId!==m&&n.chainId!==f?!1:h(n.address)===y}function te(n){let e=n.address.toLowerCase();return n.chainId===m?e===_.toLowerCase():n.chainId===f?e===I.toLowerCase():!1}function ae(n){return ee(n)||te(n)}var se=-887272,oe=887272,de=(1n<<256n)-1n,ce=ie(["function observe(uint32[] secondsAgos) view returns (int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s)","function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)"]);function L(n,e){if(typeof n=="bigint")return n;if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new c(`Invalid ${e} timestamp.`);return BigInt(n)}if(typeof n=="string"&&/^-?\d+$/.test(n.trim()))return BigInt(n.trim());throw new c(`Invalid ${e} timestamp.`)}function Pe(n,e=BigInt(Math.floor(Date.now()/1e3)),t=M){try{return p(n,e,t),!0}catch{return!1}}function p(n,e=BigInt(Math.floor(Date.now()/1e3)),t=M){if(!Number.isInteger(t)||t<0)throw new c("Maximum price age must be a non-negative integer.");let a=L(n,"price"),s=L(e,"current");if(a<=0n)throw new c("Price timestamp must be positive.");if(a>s)throw new c("Price timestamp is in the future.");let r=s-a;if(r>BigInt(t))throw new c(`Price is stale: age ${r}s exceeds ${t}s.`);return a.toString()}function ue(n){if(!Number.isInteger(n)||n<se||n>oe)throw new c(`Tick ${n} is outside valid Uniswap bounds.`);let e=BigInt(n<0?-n:n),t=(e&0x1n)!==0n?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&0x2n)!==0n&&(t=t*0xfff97272373d413259a46990580e213an>>128n),(e&0x4n)!==0n&&(t=t*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&0x8n)!==0n&&(t=t*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&0x10n)!==0n&&(t=t*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&0x20n)!==0n&&(t=t*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&0x40n)!==0n&&(t=t*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&0x80n)!==0n&&(t=t*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&0x100n)!==0n&&(t=t*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&0x200n)!==0n&&(t=t*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&0x400n)!==0n&&(t=t*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&0x800n)!==0n&&(t=t*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&0x1000n)!==0n&&(t=t*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&0x2000n)!==0n&&(t=t*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&0x4000n)!==0n&&(t=t*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&0x8000n)!==0n&&(t=t*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&0x10000n)!==0n&&(t=t*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&0x20000n)!==0n&&(t=t*0x5d6af8dedb81196699c329225ee604n>>128n),(e&0x40000n)!==0n&&(t=t*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&0x80000n)!==0n&&(t=t*0x48a170391f7dc42444e8fa2n>>128n),n>0&&(t=de/t),(t>>32n)+(t%(1n<<32n)===0n?0n:1n)}async function me(n,e,t){if(typeof n=="object"&&n!==null){let i=n.chainId??e,o=h(n.address)===y?y:b(n.address),d={address:o,symbol:n.symbol,decimals:n.decimals,chainId:i};return Z(d)?{address:o,symbol:"USDG",decimals:k,chainId:i}:ee(d)?{address:y,symbol:"ETH",decimals:18,chainId:i}:te(d)?{address:o,symbol:"WETH",decimals:18,chainId:i}:t.officialStockTokens?z(d,t.officialStockTokens):d}let a=n.trim(),s=a.toUpperCase(),r=a.toLowerCase();if(s==="ETH"||D(a,{strict:!1})&&h(a)===y)return{...j,chainId:e};if(s==="WETH"||e===m&&r===_.toLowerCase()||e===f&&r===I.toLowerCase()){if(e!==m&&e!==f)throw new c(`No canonical WETH address configured for chain ${e}.`);return{address:e===f?I:_,symbol:"WETH",decimals:18,chainId:e}}if(s==="USDG"||e===m&&r===R.toLowerCase()||e===f&&r===K.toLowerCase()){if(e!==m&&e!==f)throw new c(`No canonical USDG address configured for chain ${e}.`);return{address:e===f?Q:J,symbol:"USDG",decimals:k,chainId:e}}if(e===m&&(s==="USDE"||r===O.address.toLowerCase()))return{...O,chainId:e};let u=t.oakTokenAddress??process.env.OAK_TOKEN_ADDRESS;if(s==="OAK"||u&&a.toLowerCase()===u.toLowerCase()){if(!u&&!D(a,{strict:!1}))throw new c("OAK token address is required to price OAK.");return{address:b(u??a),symbol:"OAK",decimals:W,chainId:e}}if(t.officialStockTokens){let i=t.officialStockTokens.find(o=>o.chainId===e&&o.symbol.toUpperCase()===s);if(i)return i;if(D(a,{strict:!1})){let o=b(a),d=t.officialStockTokens.find(l=>l.chainId===e&&l.address.toLowerCase()===o.toLowerCase());if(d)return d}}if(D(a,{strict:!1})){let i=b(a),o=t.client??g(t.rpcUrl,e),[d,l]=await Promise.all([P(o,e,i,"symbol",t.blockNumber),P(o,e,i,"decimals",t.blockNumber)]);return{address:i,symbol:d,decimals:Number(l),chainId:e}}throw new c(`Unknown token ${T(a)}.`)}async function N(n,e,t){if(e)return(await n.readContract({address:e,abi:Y,functionName:"ethUsdE18",blockNumber:t})).toString();let s=(await n.readContract({address:b(B),abi:ce,functionName:"observe",args:[[U,0]],blockNumber:t}))[0];if(!s||s.length<2)throw new c("ETH/USDG pool observation returned insufficient tick cumulatives.");let r=X(s[0],s[1],U),u=ue(r);return F(u)}async function x(n,e,t,a){if(n.timestamp!==void 0)return p(n.timestamp,t(),a);if(e&&typeof e.getBlock=="function"){let r=await v(e,n.blockNumber);return p(r.timestamp,t(),a)}let s=t();return p(s,s,a)}async function ve(n,e={}){let t=e.chainId??m,a=e.maxAgeSeconds??M,s=()=>e.now!==void 0?L(e.now,"current"):BigInt(Math.floor(Date.now()/1e3)),r=await me(n,t,e);if((H(r.symbol)||r.symbol.length>256)&&(r.symbol=T(r.symbol)),e.signedNote||e.priceNote){let i=e.signedNote?e.signedNote.note:e.priceNote,o=p(i.timestamp,s(),a);if(e.spotOakPerEthE18!==void 0&&!A(i.oakPerEthE18,e.spotOakPerEthE18))throw new c("Price note is outside the 50% spot guard band.");let d=e.signedNote?.signature??e.signature,l=e.signedNote?.consumer??e.consumer;if(d&&l){let G=await q({note:i,signature:d,consumer:l,signer:e.signer,now:s(),spotOakPerEthE18:e.spotOakPerEthE18,chainId:t});if(!G.valid)throw new c(G.error??"Price note verification failed.")}let E=e.ethUsdE18!==void 0?e.ethUsdE18.toString():await N(e.client??g(e.rpcUrl,t),e.oracleAddress);return{token:r,usdE18:C(E,i.oakPerEthE18),timestamp:o}}if(e.trades){let i=await x(e,e.client,s,a),o=V(e.trades,{now:s(),windowStart:e.windowStart,windowEnd:e.windowEnd});if(e.spotOakPerEthE18!==void 0&&!A(o,e.spotOakPerEthE18))throw new c("30-minute average is outside the 50% spot guard band.");let d=e.ethUsdE18!==void 0?e.ethUsdE18.toString():await N(e.client??g(e.rpcUrl,t),e.oracleAddress);return{token:r,usdE18:C(d,o),timestamp:i}}if(e.usdE18!==void 0){let i=await x(e,e.client,s,a),o=S(e.usdE18.toString());if(o<=0n)throw new c("USD price must be positive.");return{token:r,usdE18:o.toString(),timestamp:i}}if(e.resolver){let i=await e.resolver(r),o=p(i.timestamp,s(),a),d=S(i.usdE18);if(d<=0n)throw new c("USD price must be positive.");return{token:r,usdE18:d.toString(),timestamp:o}}let u=e.client??g(e.rpcUrl,t);if(Z(r)){let i=await x(e,u,s,a);return{token:r,usdE18:re,timestamp:i}}if(ae(r)){let i=await x(e,u,s,a),o=await N(u,e.oracleAddress,e.blockNumber);return{token:r,usdE18:o,timestamp:i}}if(r.chainId===m)try{let i=await v(u,e.blockNumber),o=p(i.timestamp,s(),a);if(i.number===null)throw new c("Pons reference requires a mined block.");let[d,l]=await Promise.all([$(r,u,i.number),N(u,e.oracleAddress,i.number)]),E=S(l)*d.numerator/d.denominator;if(E<=0n)throw new c("Pons USD reference price must be positive.");return{token:r,usdE18:E.toString(),timestamp:o}}catch{}throw new c(`No fresh on-chain price source available for token ${T(r.symbol)} (${r.address}).`)}export{M as a,re as b,Z as c,ee as d,te as e,ae as f,Pe as g,p as h,ue as i,ve as j};
@@ -1 +1 @@
1
- import{f as c}from"./FL3EF72E.js";import{a,f as p,g as u}from"./ITIIHCZK.js";import{a as e}from"./UWOFA6GV.js";import{a as r}from"./XPFVT2EA.js";import{a as n}from"./5YS5V2LK.js";import{encodeFunctionData as d,parseAbi as f}from"viem";var m=f(["function deposit() payable","function withdraw(uint256)"]);function H(i){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{type:"string",enum:["wrap","unwrap"]},amount:e()}},async execute(t,w){if(u(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new n("Choose direction wrap or unwrap.");let o=a(t.amount,"amount"),s=t.direction==="wrap"?d({abi:m,functionName:"deposit"}):d({abi:m,functionName:"withdraw",args:[o]});return p(i,[i.unsignedTx({to:c,data:s,value:t.direction==="wrap"?o.toString():"0",chainId:r,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],w,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{m as a,H as b};
1
+ import{f as c}from"./ANQ43XJA.js";import{a,f as p,g as u}from"./64AF7ECA.js";import{a as e}from"./UWOFA6GV.js";import{a as r}from"./XPFVT2EA.js";import{a as n}from"./5YS5V2LK.js";import{encodeFunctionData as d,parseAbi as f}from"viem";var m=f(["function deposit() payable","function withdraw(uint256)"]);function H(i){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{type:"string",enum:["wrap","unwrap"]},amount:e()}},async execute(t,w){if(u(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new n("Choose direction wrap or unwrap.");let o=a(t.amount,"amount"),s=t.direction==="wrap"?d({abi:m,functionName:"deposit"}):d({abi:m,functionName:"withdraw",args:[o]});return p(i,[i.unsignedTx({to:c,data:s,value:t.direction==="wrap"?o.toString():"0",chainId:r,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],w,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{m as a,H as b};
@@ -0,0 +1 @@
1
+ import{e as m,h as t}from"./73N3TOJL.js";import{b as E}from"./IWALIX7Q.js";import{i as C}from"./XPFVT2EA.js";import{a as v,b as g}from"./5YS5V2LK.js";import{keccak256 as j,parseAbi as D}from"viem";var A=Object.freeze({robinswapV2:Object.freeze({factory:"0xa95DA9b9fCef09A07F99444fE9304457d6ECdccA",kind:"v2",kyberswap:"robinswap-v2",velora:void 0}),uniswapV2:Object.freeze({factory:"0x8BcEAA40b9aCDfAedf85ADf4fF01f5ad6517937F",kind:"v2",kyberswap:"uniswap",velora:"uniswapv2"}),uniswapV3:Object.freeze({factory:C[4663].uniswap.v3_factory.address,kind:"v3",kyberswap:"uniswapv3",velora:"uniswapv3"})}),L=Object.freeze(Object.fromEntries(Object.entries(A).map(([r,n])=>[r,n.factory])));function V(r){return Object.values(A).flatMap(n=>n[r]??[])}var P=D(["function token0() view returns (address)","function token1() view returns (address)","function factory() view returns (address)","function fee() view returns (uint24)"]),S=D(["function getPair(address,address) view returns (address)","function getPool(address,address,uint24) view returns (address)"]),a=new Map;function M(r,n,i){let d=a.get(j(i));return!!d&&d.expires>Date.now()&&t(d.token,r)&&d.pools.some(u=>t(u,n))}async function B(r,n,i,d,u,z){let w=[...new Set(d.filter(o=>!t(o,u)).map(o=>o.toLowerCase()))];if(!w.length)return;let k=j(z);a.delete(k);let f=await r.getBlockNumber();for(let o of w){let s=e=>new v(`KyberSwap source receiver ${o} is not a verified input pool: ${e}.`),l=Array.isArray(n)?n.map(e=>Array.isArray(e)?e[0]:void 0).find(e=>m(e)&&t(e.pool,o)&&t(e.tokenIn,i)):void 0;if(!m(l)||typeof l.tokenOut!="string")throw s("not named as an input hop in the accepted route");let O=await r.getCode({address:o,blockNumber:f});if(!O||O==="0x")throw s("no deployed code");try{let[e,p,y]=await Promise.all(["token0","token1","factory"].map(c=>r.readContract({address:o,abi:P,functionName:c,blockNumber:f}))),h=t(e,i)?p:t(p,i)?e:void 0;if(!h||!t(h,l.tokenOut))throw s("tokens do not match the input route");let x=Object.values(A).find(c=>t(y,c.factory));if(!x)throw s("factory is not pinned");let b;if(x.kind==="v2")b=await r.readContract({address:y,abi:S,functionName:"getPair",args:[e,p],blockNumber:f});else{let c=await r.readContract({address:o,abi:P,functionName:"fee",blockNumber:f});b=await r.readContract({address:y,abi:S,functionName:"getPool",args:[e,p,c],blockNumber:f})}if(!t(b,o))throw s("not registered by the pinned factory")}catch(e){throw e instanceof v||E(e)?e:g(e,3)?s("pool token or factory read reverted; this pool interface is not supported by Oak"):s("on-chain verification unavailable")}}for(let[o,s]of a)s.expires<=Date.now()&&a.delete(o);a.size>=1e3&&a.delete(a.keys().next().value),a.set(k,{token:i,pools:w,expires:Date.now()+6e4})}export{A as a,L as b,V as c,M as d,B as e};