@oakagentkit/core 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/build/dist/api/modules/fobo/client.js +1 -1
  2. package/build/dist/api/modules/fobo/index.js +1 -1
  3. package/build/dist/api/modules/fobo/intent.js +1 -1
  4. package/build/dist/api/modules/fobo/steps.js +1 -1
  5. package/build/dist/api/modules/fobo/verify.js +1 -1
  6. package/build/dist/api/modules/longbow/administration.js +1 -1
  7. package/build/dist/api/modules/longbow/fixed.js +1 -1
  8. package/build/dist/api/modules/longbow/index.js +1 -1
  9. package/build/dist/api/modules/merkl/discovery.js +1 -1
  10. package/build/dist/api/modules/merkl/index.js +1 -1
  11. package/build/dist/api/modules/merkl/manage.js +1 -1
  12. package/build/dist/api/modules/morpho/bundles.js +1 -1
  13. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  14. package/build/dist/api/modules/morpho/index.d.ts +2 -1
  15. package/build/dist/api/modules/morpho/index.js +1 -1
  16. package/build/dist/api/modules/morpho/local-guard.d.ts +2 -2
  17. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  18. package/build/dist/api/modules/morpho/midnight.js +1 -1
  19. package/build/dist/api/modules/morpho/protocol.js +1 -1
  20. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  21. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  22. package/build/dist/api/modules/netnet/card-read.js +1 -1
  23. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  24. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  25. package/build/dist/api/modules/netnet/financial.js +1 -1
  26. package/build/dist/api/modules/netnet/index.js +1 -1
  27. package/build/dist/chunks/{NDSNE6PS.js → 3UQXTZ5R.js} +1 -1
  28. package/build/dist/chunks/{NTUXDIY6.js → 5CPB33XA.js} +1 -1
  29. package/build/dist/chunks/{MQ37QX6U.js → 72EV7TGI.js} +1 -1
  30. package/build/dist/chunks/{M7CQPTRK.js → CXH46MHJ.js} +1 -1
  31. package/build/dist/chunks/{UYULQHZJ.js → FSYYD3OM.js} +1 -1
  32. package/build/dist/chunks/{Z2QV6EZY.js → HPY2ONAS.js} +1 -1
  33. package/build/dist/chunks/{AIYNFIG6.js → I3ZBOSSH.js} +1 -1
  34. package/build/dist/chunks/{AG2G7BHH.js → NCAV7Q4C.js} +1 -1
  35. package/build/dist/chunks/{M6SQPOOL.js → OFWTO4N6.js} +1 -1
  36. package/build/dist/chunks/{OLDQV43V.js → PHGHJ7SN.js} +1 -1
  37. package/build/dist/chunks/{QHV5GORV.js → SO6O7JK2.js} +1 -1
  38. package/build/dist/chunks/{HQIS3QI7.js → SVKG4JOY.js} +2 -2
  39. package/build/dist/chunks/{HOBIXKGO.js → UCHJYWGU.js} +1 -1
  40. package/build/dist/chunks/{4NDIYRH5.js → WCI3FHWT.js} +1 -1
  41. package/build/dist/chunks/{W7OCS4AM.js → X5I5EJ5T.js} +1 -1
  42. package/build/dist/chunks/{AXHFNE6L.js → XKLXVTSE.js} +3 -3
  43. package/build/dist/chunks/{2JWAFLJU.js → YAVWSW3G.js} +1 -1
  44. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import{a as R}from"./DFM4T6ZE.js";import{d as N}from"./HQIS3QI7.js";import{b as D,d as M,f as C}from"./4ZD5D2UP.js";import{t as E}from"./MQ5F2VOK.js";import{a}from"./XSD5NL7J.js";import{a as P}from"./JXOEJPJ4.js";import{decodeFunctionData as _,erc20Abi as X,formatUnits as $,getAddress as x,isAddress as Q,parseUnits as K,parseAbi as V,zeroAddress as f}from"viem";var be=300,m={permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",router:"0x204FAca1764B154221e35c0d20aBb3c525710498",factory:"0xd7e538e98A208fD19e46bc549FF4710C33664e18",limitOrders:"0x3126f62d604a0AA2de8788e3eC21dDd8F2a2f82a",fobo:"0x000DE658153f47f23e92973C8EB1e89762703676",usdg:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},T=["eth","fobo","usdg","msft","tsla","spcx","googl","amzn","aapl","nvda","meta"],b=(t,e=0)=>({type:"string",minLength:e,maxLength:t}),w=(t,e="string")=>({type:e,enum:t}),B={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},v={type:"string",pattern:"^[0-9]+$",description:"Exact input in token base units, as a decimal integer string."},U={type:"integer",minimum:1,maximum:100},L={token:B,amount:v,payWith:w(["pair","eth","usdg","fobo"]),slippageBps:{type:"integer",minimum:1,maximum:5e3}},Z={token:"FOBO coin contract address on chain 4663; obtain it from fobo_browse or fobo_token.",query:"Search FOBO coins and traders by name, ticker or address; omit to browse recent launches.",limit:"Maximum number of results, from 1 to 100.",side:"Trade direction: buy the coin or sell it back to the payment currency.",payWith:"Payment currency: pair uses the coin\u2019s own pair; trades also accept eth, usdg or fobo.",slippageBps:"Maximum loss against quoted output in basis points (50 = 0.5%); default 50.",hash:"Public transaction hash (0x followed by 64 hex digits) to look up on FOBO.",name:"New coin name, 1 to 32 characters.",ticker:"New coin ticker, 2 to 10 letters or digits; normalized to uppercase.",description:"Public description of the new coin, at most 280 characters.",imageUrl:"Optional public HTTPS image URL; omit for no image. Local uploads are unsupported.",links:"Optional public project links stored with the launched coin.",telegram:"Public Telegram URL.",discord:"Public Discord URL.",github:"Public GitHub URL.",website:"Public project website URL.",pair:"Pair currency: eth, fobo, usdg or a supported stock ticker; referral claims use this currency.",devBuyTokens:"Whole tokens in the initial buy, 0 to 50,000,000 (5% of supply); default 0.",vestMonths:"Initial-buy lock in months: 0, 1, 3, 6 or 12; default 0. A lock requires an initial buy.",limitMarketCapUsd:"Target market capitalization in whole USD, as a decimal string; not a per-token price.",expiresIn:"Order lifetime: 1h, 1d, 7d or 30d; default 7d.",maxFeePerFill:"Maximum keeper fee per fill in payment-token base units, as an exact decimal integer string.",orderId:"Positive numeric ID of the local wallet\u2019s limit order to cancel.",kind:"Claim creator fees, referral earnings or vesting tokens.",to:"Optional recipient address for a referral claim; omit for this wallet. Other claims always pay this wallet."},l=(t,e=[])=>({type:"object",additionalProperties:!1,required:e,properties:Object.fromEntries(Object.entries(t).map(([r,s])=>{let o=s;return[r,{...o,description:o.description??Z[r]}]}))}),Y={fobo_browse:l({query:b(64,1),limit:U}),fobo_token:l({token:B},["token"]),fobo_portfolio:l({}),fobo_leaderboard:l({limit:U}),fobo_claims:l({}),fobo_limit_orders:l({token:B}),fobo_quote:l({...L,side:w(["buy","sell"])},["token","side","amount"]),fobo_fee_schedule:l({}),fobo_limit_pay_tokens:l({}),fobo_transaction:l({hash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}},["hash"]),fobo_buy:l(L,["token","amount"]),fobo_sell:l(L,["token","amount"]),fobo_launch:l({name:b(32,1),ticker:{type:"string",pattern:"^\\$?[a-zA-Z0-9]{2,10}$"},description:b(280),imageUrl:{...b(2e3),pattern:"^https://"},links:l({telegram:b(200),discord:b(200),github:b(200),website:b(200)}),pair:w(T),devBuyTokens:{type:"integer",minimum:0,maximum:5e7},vestMonths:w([0,1,3,6,12],"integer"),maxInitialBuyAmount:{...v,description:"Maximum pair-token base units to spend on the initial buy, excluding the live launch fee. Required when devBuyTokens is positive."}},["name","ticker"]),fobo_limit_order:l({token:B,side:w(["buy","sell"]),payWith:b(42,2),amount:v,limitMarketCapUsd:{type:"string",pattern:"^\\d{1,30}(\\.\\d{1,18})?$"},expiresIn:w(["1h","1d","7d","30d"]),maxFeePerFill:v},["token","side","amount","limitMarketCapUsd","maxFeePerFill"]),fobo_cancel_limit_order:l({orderId:{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}},["orderId"]),fobo_claim:l({kind:w(["creator","referral","vesting"]),token:B,pair:w(T),to:B},["kind"])},ee={fobo_buy:"buy",fobo_sell:"sell",fobo_launch:"launch",fobo_limit_order:"limitOrder",fobo_cancel_limit_order:"cancel",fobo_claim:"claim"},te={buy:"prepare_trade",sell:"prepare_trade",launch:"prepare_launch",limitOrder:"prepare_limit_order",cancel:"prepare_cancel_limit_order",claim:"prepare_claim"};function g(t){if(!t||typeof t!="object"||Array.isArray(t))throw new a("FOBO returned an invalid answer. Ask for a fresh summary.");return t}function ne(t,e){function r(s,o){let d=s.properties;if(Object.keys(o).some(n=>!Object.hasOwn(d,n)))throw new a("Unexpected FOBO argument. Use the fields declared by the tool.");for(let n of s.required)if(o[n]===void 0)throw new a(`Missing FOBO argument: ${n}.`);for(let[n,i]of Object.entries(o)){let c=d[n];if(c.type==="object"){r(c,g(i));continue}if(c.type==="integer"){if(typeof i!="number"||!Number.isSafeInteger(i)||i<Number(c.minimum??0)||i>Number(c.maximum??Number.MAX_SAFE_INTEGER))throw new a(`Invalid FOBO argument: ${n}.`)}else if(typeof i!="string"||i.length<Number(c.minLength??0)||i.length>Number(c.maxLength??256)||typeof c.pattern=="string"&&!new RegExp(c.pattern).test(i))throw new a(`Invalid FOBO argument: ${n}.`);if(Array.isArray(c.enum)&&!c.enum.includes(i))throw new a(`Invalid FOBO argument: ${n}.`)}}if(r(Y[t],g(e)),t==="fobo_claim"&&(e.kind==="referral"?e.pair===void 0:e.token===void 0))throw new a("Referral claims need pair; creator and vesting claims need token.");if(t==="fobo_claim"&&e.kind!=="referral"&&e.to!==void 0)throw new a("Only referral claims may name another recipient.");if(t==="fobo_launch"){if(Number(e.vestMonths??0)>0&&Number(e.devBuyTokens??0)===0)throw new a("A vesting lock needs an initial buy.");if(Number(e.devBuyTokens??0)>0&&(typeof e.maxInitialBuyAmount!="string"||BigInt(e.maxInitialBuyAmount)===0n))throw new a("An initial buy needs maxInitialBuyAmount in pair-token base units. Ask the person for that spending cap.");if(e.imageUrl!==void 0){let s=new URL(String(e.imageUrl));if(s.protocol!=="https:"||s.username||s.password)throw new a("Use a public https image URL.")}}return structuredClone(e)}function y(t){let e=t.toLowerCase();if(e===f||e==="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")return{address:f,decimals:18};if(e===m.usdg.toLowerCase())return{address:m.usdg,decimals:6};if(e===m.fobo.toLowerCase())return{address:m.fobo,decimals:18};if(t==="eth")return{address:f,decimals:18};if(t==="usdg")return{address:m.usdg,decimals:6};if(t==="fobo")return{address:m.fobo,decimals:18};let r=R.tokens.find(s=>T.includes(t)&&s.symbol.toLowerCase()===t||s.token.toLowerCase()===e);if(r)return{address:x(r.token),decimals:18};throw new a("FOBO did not identify a supported pair currency. Ask for token details first.")}function A(t,e,r){if(typeof t!="string"||!/^\d{1,78}(\.\d{1,18})?$/.test(t)||(t.split(".")[1]?.length??0)>e)throw new a(`FOBO returned an invalid ${r}. Ask for a fresh quote.`);return K(t,e).toString()}function re(t,e,r,s){if(String(t.payWith).replace(/^\$/,"").toLowerCase()!==s.toLowerCase())throw new a("FOBO quote payment currency differs from the request.");if(t.slippageBps!==r)throw new a("FOBO quote slippage differs from the request.");let o=A(t.expectedOut,e,"quote output"),d=A(t.minOut,e,"quote minimum"),n=BigInt(o)*BigInt(1e4-r)/10000n;if(BigInt(d)<=0n||BigInt(d)>BigInt(o)||BigInt(d)<n)throw new a("FOBO quote minimum exceeds the approved slippage loss.");return{amountOut:o,minimum:d}}function W(t){let e=Object.fromEntries(Object.entries(t.request).filter(([r])=>!r.startsWith("_")&&r!=="maxInitialBuyAmount"));return typeof e.links=="string"&&(e.links=JSON.parse(e.links)),e.amount!==void 0&&(e.amount=$(BigInt(String(e.amount)),Number(t.request._inputDecimals))),e.maxFeePerFill!==void 0&&(e.maxFeePerFill=$(BigInt(String(e.maxFeePerFill)),Number(t.request._payDecimals))),(t.kind==="buy"||t.kind==="sell")&&(e.side=t.kind),t.kind==="claim"&&e.pair!==void 0&&(e.currency=e.pair,delete e.pair),{...e,account:t.wallet}}function S(t,e,r="0x0Af57F62982D03066ef917AcAd87F771c06528Ec"){let[s,o]=BigInt(t)<BigInt(e)?[t,e]:[e,t];return{currency0:s,currency1:o,fee:r===f?500:0,tickSpacing:r===f?10:60,hooks:r}}function j(t,e){let r=t===f?e:t;if(t!==f&&e!==f)throw new a("FOBO base-currency routes must pass through ETH.");if(r.toLowerCase()===m.usdg.toLowerCase())return S(t,e,f);if(r.toLowerCase()===m.fobo.toLowerCase())return S(t,e);throw new a("FOBO has not pinned a route between this pair and ETH. Use the token\u2019s own pair.")}function oe(t,e,r,s){let o=[];return r.toLowerCase()!==e.toLowerCase()&&(r!==f&&o.push(j(r,f)),e!==f&&o.push(j(f,e))),o.push(S(e,t)),s?o.reverse():o}function ie(t,e,r,s){let o=t.request,d=t.terms;if(t.kind==="buy"||t.kind==="sell")return{kind:"trade",currencyIn:o._currencyIn,currencyOut:o._currencyOut,amountIn:BigInt(d.amountIn),minOut:BigInt(d.minOut),now:e,pools:JSON.parse(String(o._pools)),...s?{permit:s}:{}};if(t.kind==="launch"){let i=(r?_({abi:D,data:r.data}).args[0]:void 0)?.devBuyMaxCost??BigInt(d.amountIn??"0");if(i>BigInt(d.amountIn??"0"))throw new a("FOBO launch exceeds the approved initial-buy spending cap. Nothing further was signed.");return{kind:"launch",name:String(o.name),ticker:String(o.ticker).replace(/^\$/,"").toUpperCase(),pair:y(String(o.pair)).address,devBuyTokens:BigInt(d.devBuyTokens??0)*10n**18n,devBuyMaxCost:i,vestMonths:d.vestMonths??0,launchFeeWei:BigInt(d.launchFeeWei),now:e}}if(t.kind==="limitOrder"){if(!r)throw new a("FOBO order is missing its unsigned transaction.");let n=_({abi:M,data:r.data});if(n.functionName!=="place")throw new a("FOBO order must call place.");let i=n.args[5],k={"1h":3600,"1d":86400,"7d":604800,"30d":2592e3}[String(o.expiresIn??"7d")],O=BigInt(t.quotedAt+k);if(i<O-60n||i>BigInt(e+k)+60n)throw new a("FOBO changed the approved order expiry. Nothing further was signed.");return{kind:"limitOrder",side:o.side==="buy"?0:1,token:d.token,payToken:y(String(o.payWith)).address,amount:BigInt(d.amountIn),limitPriceUsdE18:K(String(o.limitMarketCapUsd),18)/1000000000n,expiry:i,maxFeePerFill:BigInt(String(o.maxFeePerFill))}}if(t.kind==="cancel")return{kind:"cancel",orderId:BigInt(String(o.orderId))};if(o.kind==="creator")return{kind:"claim",claimKind:"creator",poolKey:JSON.parse(String(o._poolKey))};if(o.kind==="referral")return{kind:"claim",claimKind:"referral",currency:y(String(o.pair)).address,recipient:o.to??t.wallet};if(o.kind==="vesting"&&r)return{kind:"claim",claimKind:"vesting",lockId:_({abi:C,data:r.data}).args[0],beneficiary:t.wallet};throw new a("FOBO claim does not match a supported claim kind.")}function ae(t){let e={...g(t)};if(e.status==="needs_signature"&&e.transactions===void 0&&(e.transactions=[]),!["ready","needs_approval","needs_signature"].includes(String(e.status))||!Array.isArray(e.transactions)||e.transactions.length>32)throw new a("FOBO returned an unsupported preparation. Nothing further was signed. Ask for a fresh summary.");return e}function se(t,e,r){let s=g(e);if(![4663,"0x1237"].includes(s.chainId)||String(s.from).toLowerCase()!==t.wallet.toLowerCase()||BigInt(String(s.value??"0"))!==0n)throw new a("FOBO approval has the wrong wallet, chain or ETH value. Nothing further was signed.");let o=_({abi:X,data:String(s.data)});if(o.functionName!=="approve")throw new a("FOBO requested something other than an approval.");let d=o.args[0],n=t.kind==="launch"?m.factory:t.kind==="limitOrder"?m.limitOrders:m.permit2;if(d.toLowerCase()!==n.toLowerCase()||String(s.to).toLowerCase()!==String(t.request._currencyIn).toLowerCase()||t.terms.amountIn===void 0)throw new a("FOBO approval does not match the approved token and spender. Nothing further was signed.");return N(e,{kind:"approval",token:x(String(s.to)),spender:d,amount:BigInt(t.terms.amountIn)},t.wallet)}async function de(t,e,r,s,o){if(e.status==="needs_signature"){if(e.transactions.length)throw new a("FOBO attached unexpected transactions to a signature request.");return[]}if(!e.transactions.length||t.kind!=="claim"&&e.transactions.length!==1)throw new a("FOBO returned an unexpected transaction count. Nothing further was signed.");if(e.status==="needs_approval"){if(!["buy","sell","launch","limitOrder"].includes(t.kind))throw new a("This FOBO action must not need an approval.");return e.transactions.map(n=>se(t,n,r))}if(e.transactions.some(n=>String(g(n).data).toLowerCase().startsWith("0x095ea7b3")))throw new a("FOBO attached an approval to a ready action. Ask for a fresh summary.");if(t.kind==="claim"&&t.request.kind==="vesting"){let n=o??E({chainId:4663}).readContract,i=V(["function getLock(uint256 id) view returns ((address token,uint64 start,uint32 duration,address beneficiary,uint256 amount,uint256 claimed))"]);for(let c of e.transactions){let k=_({abi:C,data:c.data}).args[0],O=await n({address:"0x51d217Ecf7c0e4EbF54258444B9617D012Fd7D0a",abi:i,functionName:"getLock",args:[k]});if(O.beneficiary.toLowerCase()!==t.wallet.toLowerCase()||O.token.toLowerCase()!==String(t.request.token).toLowerCase())throw new a("FOBO vesting lock does not belong to this wallet and token. Nothing further was signed.")}}let d=e.transactions.map(n=>N(n,ie(t,r,n,s),t.wallet));if(t.kind==="launch"){let n=BigInt(t.terms.launchFeeWei??"0"),i=t.request.pair==="eth"?n+BigInt(t.terms.amountIn??"0"):n;if(d.some(c=>BigInt(c.value)>i||BigInt(c.value)<n))throw new a("FOBO launch exceeds the approved spending cap or changed its fee. Nothing further was signed.")}if(typeof t.request._prepared=="string"){let n=JSON.parse(t.request._prepared);if(d.length!==n.length||d.some((i,c)=>i.to.toLowerCase()!==n[c].to.toLowerCase()||i.data.toLowerCase()!==n[c].data.toLowerCase()||BigInt(i.value)!==BigInt(n[c].value)))throw new a("FOBO changed the approved terms. Nothing further was signed. Ask for a fresh summary.")}return d}function ce(t){let e="Oak fee: 0 bps on FOBO\u2019s own route.";if(t.kind==="buy"||t.kind==="sell"){let r=t.terms.tokenPoolTaxPercentNow;if(typeof r!="number"||!Number.isFinite(r)||r<0||r>100)throw new a("FOBO quote did not identify its current tax.");return`${e} FOBO's tax right now: ${r}%; included in the quoted output and minimum.`}return t.kind==="launch"?`${e} FOBO launch fee: ${$(BigInt(t.terms.launchFeeWei),18)} ETH (${t.terms.launchFeeWei} wei).`:t.kind==="limitOrder"?`${e} FOBO keeper fee: at most ${t.request.maxFeePerFill} pay-token base units per fill. Pool tax applies when the order fills; the future tax is not known at preparation.`:`${e} No additional FOBO fee for this ${t.kind==="cancel"?"cancellation":"claim"}; network fees are additional.`}async function we(t,e,r,s){let o=Object.entries(ee).find(([,u])=>u===e)?.[0];if(!o||!Q(s,{strict:!1}))throw new a("Provide a valid FOBO action and local wallet.");let d=ne(o,r),n={};for(let[u,p]of Object.entries(d))n[u]=typeof p=="object"?JSON.stringify(p):p;let i={version:1,kind:e,wallet:x(s),chainId:4663,request:n,terms:{},quotedAt:Math.floor(Date.now()/1e3)};if(e==="launch"){n.pair??="eth",n.devBuyTokens??=0,n.vestMonths??=0;let u=g(g(await t.call("get_fee_schedule",{})).launch);if(u.launchesPaused===!0)throw new a("FOBO launches are paused. Nothing was signed.");let p=y(String(n.pair));n._currencyIn=p.address,n._inputDecimals=p.decimals,i.preparation={status:"ready",transactions:[]},i.terms={launchFeeWei:A(u.feeEth,18,"launch fee"),devBuyTokens:Number(n.devBuyTokens),vestMonths:Number(n.vestMonths),amountIn:String(n.maxInitialBuyAmount??"0")}}else if(e==="buy"||e==="sell"||e==="limitOrder"){n.payWith??=e==="limitOrder"?"eth":"pair";let u=String(n.payWith),p=g(await t.call("get_token",{token:n.token}));if(String(p.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO token metadata does not match the requested token.");let H=y(String(p.pair).replace(/^\$/,"").toLowerCase());u==="pair"&&(u=String(p.pair).replace(/^\$/,"").toLowerCase());let F=y(u);n._payDecimals=F.decimals;let I=e==="limitOrder"?n.side:e;if(n._currencyIn=I==="sell"?String(n.token):F.address,n._currencyOut=I==="sell"?F.address:String(n.token),n._inputDecimals=I==="sell"?18:F.decimals,n._outputDecimals=I==="sell"?F.decimals:18,e!=="limitOrder"&&(n._pools=JSON.stringify(oe(x(String(n.token)),H.address,F.address,I==="sell"))),i.terms={token:x(String(n.token)),payWith:String(n.payWith),amountIn:String(n.amount)},BigInt(String(n.amount))===0n)throw new a("FOBO input amount must be positive.");if(e!=="limitOrder"){n.slippageBps??=50;let{account:J,...z}=W(i),h=g(await t.call("quote_trade",z)),G=A(h.amountIn,Number(n._inputDecimals),"quote input"),{minimum:q}=re(h,Number(n._outputDecimals),Number(n.slippageBps),u);if(G!==n.amount||BigInt(q)===0n||String(h.token).toLowerCase()!==String(n.token).toLowerCase()||h.side!==e)throw new a("FOBO quote does not match the requested trade. Nothing was signed.");if(i.terms.minOut=q,i.terms.slippageBps=Number(n.slippageBps),typeof h.tokenPoolTaxPercentNow!="number"||!Number.isFinite(h.tokenPoolTaxPercentNow)||h.tokenPoolTaxPercentNow<0||h.tokenPoolTaxPercentNow>100)throw new a("FOBO quote did not identify its current tax.");i.terms.tokenPoolTaxPercentNow=h.tokenPoolTaxPercentNow}}if(e==="claim"&&n.kind==="creator"){let u=g(await t.call("get_token",{token:n.token}));if(String(u.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO claim token metadata does not match.");n._poolKey=JSON.stringify(S(y(String(u.pair).replace(/^\$/,"").toLowerCase()).address,x(String(n.token))))}if(e!=="launch"){let u=ae(await t.call(te[e],W(i))),p=await de(i,u,i.quotedAt);if(i.preparation={status:u.status,transactions:p},e==="cancel"||e==="claim"||e==="limitOrder"){if(u.status==="needs_signature")throw new a("This FOBO action must not need a permit signature.");u.status==="ready"&&(n._prepared=JSON.stringify(p))}}let c=e==="launch"?`Launch ${P(String(n.name))} (${P(String(n.ticker))}), pair ${n.pair}, initial buy ${n.devBuyTokens} tokens, lock ${n.vestMonths} months.`:e==="limitOrder"?`Place a FOBO ${n.side} order for ${n.token}, limit market cap ${n.limitMarketCapUsd} USD, expiry ${n.expiresIn??"7d"}, maximum keeper fee ${n.maxFeePerFill} pay-token base units per fill.`:e==="claim"?`Claim FOBO ${n.kind} earnings${n.token?` for ${n.token}`:` in ${n.pair}`} to ${n.to??s}.`:e==="cancel"?`Cancel FOBO order ${n.orderId} and refund ${s}.`:`${e} on FOBO for ${n.token}.`,k=e==="launch"?`Launch fee ${i.terms.launchFeeWei} wei; initial-buy spending cap ${i.terms.amountIn} pair-token base units.`:`Exact input ${i.terms.amountIn??"0"} base units.`,O=`${c}
1
+ import{a as R}from"./DFM4T6ZE.js";import{d as N}from"./SVKG4JOY.js";import{b as D,d as M,f as C}from"./4ZD5D2UP.js";import{t as E}from"./MQ5F2VOK.js";import{a}from"./XSD5NL7J.js";import{a as P}from"./JXOEJPJ4.js";import{decodeFunctionData as _,erc20Abi as X,formatUnits as $,getAddress as x,isAddress as Q,parseUnits as K,parseAbi as V,zeroAddress as f}from"viem";var be=300,m={permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",router:"0x204FAca1764B154221e35c0d20aBb3c525710498",factory:"0xd7e538e98A208fD19e46bc549FF4710C33664e18",limitOrders:"0x3126f62d604a0AA2de8788e3eC21dDd8F2a2f82a",fobo:"0x000DE658153f47f23e92973C8EB1e89762703676",usdg:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},T=["eth","fobo","usdg","msft","tsla","spcx","googl","amzn","aapl","nvda","meta"],b=(t,e=0)=>({type:"string",minLength:e,maxLength:t}),w=(t,e="string")=>({type:e,enum:t}),B={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},v={type:"string",pattern:"^[0-9]+$",description:"Exact input in token base units, as a decimal integer string."},U={type:"integer",minimum:1,maximum:100},L={token:B,amount:v,payWith:w(["pair","eth","usdg","fobo"]),slippageBps:{type:"integer",minimum:1,maximum:5e3}},Z={token:"FOBO coin contract address on chain 4663; obtain it from fobo_browse or fobo_token.",query:"Search FOBO coins and traders by name, ticker or address; omit to browse recent launches.",limit:"Maximum number of results, from 1 to 100.",side:"Trade direction: buy the coin or sell it back to the payment currency.",payWith:"Payment currency: pair uses the coin\u2019s own pair; trades also accept eth, usdg or fobo.",slippageBps:"Maximum loss against quoted output in basis points (50 = 0.5%); default 50.",hash:"Public transaction hash (0x followed by 64 hex digits) to look up on FOBO.",name:"New coin name, 1 to 32 characters.",ticker:"New coin ticker, 2 to 10 letters or digits; normalized to uppercase.",description:"Public description of the new coin, at most 280 characters.",imageUrl:"Optional public HTTPS image URL; omit for no image. Local uploads are unsupported.",links:"Optional public project links stored with the launched coin.",telegram:"Public Telegram URL.",discord:"Public Discord URL.",github:"Public GitHub URL.",website:"Public project website URL.",pair:"Pair currency: eth, fobo, usdg or a supported stock ticker; referral claims use this currency.",devBuyTokens:"Whole tokens in the initial buy, 0 to 50,000,000 (5% of supply); default 0.",vestMonths:"Initial-buy lock in months: 0, 1, 3, 6 or 12; default 0. A lock requires an initial buy.",limitMarketCapUsd:"Target market capitalization in whole USD, as a decimal string; not a per-token price.",expiresIn:"Order lifetime: 1h, 1d, 7d or 30d; default 7d.",maxFeePerFill:"Maximum keeper fee per fill in payment-token base units, as an exact decimal integer string.",orderId:"Positive numeric ID of the local wallet\u2019s limit order to cancel.",kind:"Claim creator fees, referral earnings or vesting tokens.",to:"Optional recipient address for a referral claim; omit for this wallet. Other claims always pay this wallet."},l=(t,e=[])=>({type:"object",additionalProperties:!1,required:e,properties:Object.fromEntries(Object.entries(t).map(([r,s])=>{let o=s;return[r,{...o,description:o.description??Z[r]}]}))}),Y={fobo_browse:l({query:b(64,1),limit:U}),fobo_token:l({token:B},["token"]),fobo_portfolio:l({}),fobo_leaderboard:l({limit:U}),fobo_claims:l({}),fobo_limit_orders:l({token:B}),fobo_quote:l({...L,side:w(["buy","sell"])},["token","side","amount"]),fobo_fee_schedule:l({}),fobo_limit_pay_tokens:l({}),fobo_transaction:l({hash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}},["hash"]),fobo_buy:l(L,["token","amount"]),fobo_sell:l(L,["token","amount"]),fobo_launch:l({name:b(32,1),ticker:{type:"string",pattern:"^\\$?[a-zA-Z0-9]{2,10}$"},description:b(280),imageUrl:{...b(2e3),pattern:"^https://"},links:l({telegram:b(200),discord:b(200),github:b(200),website:b(200)}),pair:w(T),devBuyTokens:{type:"integer",minimum:0,maximum:5e7},vestMonths:w([0,1,3,6,12],"integer"),maxInitialBuyAmount:{...v,description:"Maximum pair-token base units to spend on the initial buy, excluding the live launch fee. Required when devBuyTokens is positive."}},["name","ticker"]),fobo_limit_order:l({token:B,side:w(["buy","sell"]),payWith:b(42,2),amount:v,limitMarketCapUsd:{type:"string",pattern:"^\\d{1,30}(\\.\\d{1,18})?$"},expiresIn:w(["1h","1d","7d","30d"]),maxFeePerFill:v},["token","side","amount","limitMarketCapUsd","maxFeePerFill"]),fobo_cancel_limit_order:l({orderId:{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}},["orderId"]),fobo_claim:l({kind:w(["creator","referral","vesting"]),token:B,pair:w(T),to:B},["kind"])},ee={fobo_buy:"buy",fobo_sell:"sell",fobo_launch:"launch",fobo_limit_order:"limitOrder",fobo_cancel_limit_order:"cancel",fobo_claim:"claim"},te={buy:"prepare_trade",sell:"prepare_trade",launch:"prepare_launch",limitOrder:"prepare_limit_order",cancel:"prepare_cancel_limit_order",claim:"prepare_claim"};function g(t){if(!t||typeof t!="object"||Array.isArray(t))throw new a("FOBO returned an invalid answer. Ask for a fresh summary.");return t}function ne(t,e){function r(s,o){let d=s.properties;if(Object.keys(o).some(n=>!Object.hasOwn(d,n)))throw new a("Unexpected FOBO argument. Use the fields declared by the tool.");for(let n of s.required)if(o[n]===void 0)throw new a(`Missing FOBO argument: ${n}.`);for(let[n,i]of Object.entries(o)){let c=d[n];if(c.type==="object"){r(c,g(i));continue}if(c.type==="integer"){if(typeof i!="number"||!Number.isSafeInteger(i)||i<Number(c.minimum??0)||i>Number(c.maximum??Number.MAX_SAFE_INTEGER))throw new a(`Invalid FOBO argument: ${n}.`)}else if(typeof i!="string"||i.length<Number(c.minLength??0)||i.length>Number(c.maxLength??256)||typeof c.pattern=="string"&&!new RegExp(c.pattern).test(i))throw new a(`Invalid FOBO argument: ${n}.`);if(Array.isArray(c.enum)&&!c.enum.includes(i))throw new a(`Invalid FOBO argument: ${n}.`)}}if(r(Y[t],g(e)),t==="fobo_claim"&&(e.kind==="referral"?e.pair===void 0:e.token===void 0))throw new a("Referral claims need pair; creator and vesting claims need token.");if(t==="fobo_claim"&&e.kind!=="referral"&&e.to!==void 0)throw new a("Only referral claims may name another recipient.");if(t==="fobo_launch"){if(Number(e.vestMonths??0)>0&&Number(e.devBuyTokens??0)===0)throw new a("A vesting lock needs an initial buy.");if(Number(e.devBuyTokens??0)>0&&(typeof e.maxInitialBuyAmount!="string"||BigInt(e.maxInitialBuyAmount)===0n))throw new a("An initial buy needs maxInitialBuyAmount in pair-token base units. Ask the person for that spending cap.");if(e.imageUrl!==void 0){let s=new URL(String(e.imageUrl));if(s.protocol!=="https:"||s.username||s.password)throw new a("Use a public https image URL.")}}return structuredClone(e)}function y(t){let e=t.toLowerCase();if(e===f||e==="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")return{address:f,decimals:18};if(e===m.usdg.toLowerCase())return{address:m.usdg,decimals:6};if(e===m.fobo.toLowerCase())return{address:m.fobo,decimals:18};if(t==="eth")return{address:f,decimals:18};if(t==="usdg")return{address:m.usdg,decimals:6};if(t==="fobo")return{address:m.fobo,decimals:18};let r=R.tokens.find(s=>T.includes(t)&&s.symbol.toLowerCase()===t||s.token.toLowerCase()===e);if(r)return{address:x(r.token),decimals:18};throw new a("FOBO did not identify a supported pair currency. Ask for token details first.")}function A(t,e,r){if(typeof t!="string"||!/^\d{1,78}(\.\d{1,18})?$/.test(t)||(t.split(".")[1]?.length??0)>e)throw new a(`FOBO returned an invalid ${r}. Ask for a fresh quote.`);return K(t,e).toString()}function re(t,e,r,s){if(String(t.payWith).replace(/^\$/,"").toLowerCase()!==s.toLowerCase())throw new a("FOBO quote payment currency differs from the request.");if(t.slippageBps!==r)throw new a("FOBO quote slippage differs from the request.");let o=A(t.expectedOut,e,"quote output"),d=A(t.minOut,e,"quote minimum"),n=BigInt(o)*BigInt(1e4-r)/10000n;if(BigInt(d)<=0n||BigInt(d)>BigInt(o)||BigInt(d)<n)throw new a("FOBO quote minimum exceeds the approved slippage loss.");return{amountOut:o,minimum:d}}function W(t){let e=Object.fromEntries(Object.entries(t.request).filter(([r])=>!r.startsWith("_")&&r!=="maxInitialBuyAmount"));return typeof e.links=="string"&&(e.links=JSON.parse(e.links)),e.amount!==void 0&&(e.amount=$(BigInt(String(e.amount)),Number(t.request._inputDecimals))),e.maxFeePerFill!==void 0&&(e.maxFeePerFill=$(BigInt(String(e.maxFeePerFill)),Number(t.request._payDecimals))),(t.kind==="buy"||t.kind==="sell")&&(e.side=t.kind),t.kind==="claim"&&e.pair!==void 0&&(e.currency=e.pair,delete e.pair),{...e,account:t.wallet}}function S(t,e,r="0x0Af57F62982D03066ef917AcAd87F771c06528Ec"){let[s,o]=BigInt(t)<BigInt(e)?[t,e]:[e,t];return{currency0:s,currency1:o,fee:r===f?500:0,tickSpacing:r===f?10:60,hooks:r}}function j(t,e){let r=t===f?e:t;if(t!==f&&e!==f)throw new a("FOBO base-currency routes must pass through ETH.");if(r.toLowerCase()===m.usdg.toLowerCase())return S(t,e,f);if(r.toLowerCase()===m.fobo.toLowerCase())return S(t,e);throw new a("FOBO has not pinned a route between this pair and ETH. Use the token\u2019s own pair.")}function oe(t,e,r,s){let o=[];return r.toLowerCase()!==e.toLowerCase()&&(r!==f&&o.push(j(r,f)),e!==f&&o.push(j(f,e))),o.push(S(e,t)),s?o.reverse():o}function ie(t,e,r,s){let o=t.request,d=t.terms;if(t.kind==="buy"||t.kind==="sell")return{kind:"trade",currencyIn:o._currencyIn,currencyOut:o._currencyOut,amountIn:BigInt(d.amountIn),minOut:BigInt(d.minOut),now:e,pools:JSON.parse(String(o._pools)),...s?{permit:s}:{}};if(t.kind==="launch"){let i=(r?_({abi:D,data:r.data}).args[0]:void 0)?.devBuyMaxCost??BigInt(d.amountIn??"0");if(i>BigInt(d.amountIn??"0"))throw new a("FOBO launch exceeds the approved initial-buy spending cap. Nothing further was signed.");return{kind:"launch",name:String(o.name),ticker:String(o.ticker).replace(/^\$/,"").toUpperCase(),pair:y(String(o.pair)).address,devBuyTokens:BigInt(d.devBuyTokens??0)*10n**18n,devBuyMaxCost:i,vestMonths:d.vestMonths??0,launchFeeWei:BigInt(d.launchFeeWei),now:e}}if(t.kind==="limitOrder"){if(!r)throw new a("FOBO order is missing its unsigned transaction.");let n=_({abi:M,data:r.data});if(n.functionName!=="place")throw new a("FOBO order must call place.");let i=n.args[5],k={"1h":3600,"1d":86400,"7d":604800,"30d":2592e3}[String(o.expiresIn??"7d")],O=BigInt(t.quotedAt+k);if(i<O-60n||i>BigInt(e+k)+60n)throw new a("FOBO changed the approved order expiry. Nothing further was signed.");return{kind:"limitOrder",side:o.side==="buy"?0:1,token:d.token,payToken:y(String(o.payWith)).address,amount:BigInt(d.amountIn),limitPriceUsdE18:K(String(o.limitMarketCapUsd),18)/1000000000n,expiry:i,maxFeePerFill:BigInt(String(o.maxFeePerFill))}}if(t.kind==="cancel")return{kind:"cancel",orderId:BigInt(String(o.orderId))};if(o.kind==="creator")return{kind:"claim",claimKind:"creator",poolKey:JSON.parse(String(o._poolKey))};if(o.kind==="referral")return{kind:"claim",claimKind:"referral",currency:y(String(o.pair)).address,recipient:o.to??t.wallet};if(o.kind==="vesting"&&r)return{kind:"claim",claimKind:"vesting",lockId:_({abi:C,data:r.data}).args[0],beneficiary:t.wallet};throw new a("FOBO claim does not match a supported claim kind.")}function ae(t){let e={...g(t)};if(e.status==="needs_signature"&&e.transactions===void 0&&(e.transactions=[]),!["ready","needs_approval","needs_signature"].includes(String(e.status))||!Array.isArray(e.transactions)||e.transactions.length>32)throw new a("FOBO returned an unsupported preparation. Nothing further was signed. Ask for a fresh summary.");return e}function se(t,e,r){let s=g(e);if(![4663,"0x1237"].includes(s.chainId)||String(s.from).toLowerCase()!==t.wallet.toLowerCase()||BigInt(String(s.value??"0"))!==0n)throw new a("FOBO approval has the wrong wallet, chain or ETH value. Nothing further was signed.");let o=_({abi:X,data:String(s.data)});if(o.functionName!=="approve")throw new a("FOBO requested something other than an approval.");let d=o.args[0],n=t.kind==="launch"?m.factory:t.kind==="limitOrder"?m.limitOrders:m.permit2;if(d.toLowerCase()!==n.toLowerCase()||String(s.to).toLowerCase()!==String(t.request._currencyIn).toLowerCase()||t.terms.amountIn===void 0)throw new a("FOBO approval does not match the approved token and spender. Nothing further was signed.");return N(e,{kind:"approval",token:x(String(s.to)),spender:d,amount:BigInt(t.terms.amountIn)},t.wallet)}async function de(t,e,r,s,o){if(e.status==="needs_signature"){if(e.transactions.length)throw new a("FOBO attached unexpected transactions to a signature request.");return[]}if(!e.transactions.length||t.kind!=="claim"&&e.transactions.length!==1)throw new a("FOBO returned an unexpected transaction count. Nothing further was signed.");if(e.status==="needs_approval"){if(!["buy","sell","launch","limitOrder"].includes(t.kind))throw new a("This FOBO action must not need an approval.");return e.transactions.map(n=>se(t,n,r))}if(e.transactions.some(n=>String(g(n).data).toLowerCase().startsWith("0x095ea7b3")))throw new a("FOBO attached an approval to a ready action. Ask for a fresh summary.");if(t.kind==="claim"&&t.request.kind==="vesting"){let n=o??E({chainId:4663}).readContract,i=V(["function getLock(uint256 id) view returns ((address token,uint64 start,uint32 duration,address beneficiary,uint256 amount,uint256 claimed))"]);for(let c of e.transactions){let k=_({abi:C,data:c.data}).args[0],O=await n({address:"0x51d217Ecf7c0e4EbF54258444B9617D012Fd7D0a",abi:i,functionName:"getLock",args:[k]});if(O.beneficiary.toLowerCase()!==t.wallet.toLowerCase()||O.token.toLowerCase()!==String(t.request.token).toLowerCase())throw new a("FOBO vesting lock does not belong to this wallet and token. Nothing further was signed.")}}let d=e.transactions.map(n=>N(n,ie(t,r,n,s),t.wallet));if(t.kind==="launch"){let n=BigInt(t.terms.launchFeeWei??"0"),i=t.request.pair==="eth"?n+BigInt(t.terms.amountIn??"0"):n;if(d.some(c=>BigInt(c.value)>i||BigInt(c.value)<n))throw new a("FOBO launch exceeds the approved spending cap or changed its fee. Nothing further was signed.")}if(typeof t.request._prepared=="string"){let n=JSON.parse(t.request._prepared);if(d.length!==n.length||d.some((i,c)=>i.to.toLowerCase()!==n[c].to.toLowerCase()||i.data.toLowerCase()!==n[c].data.toLowerCase()||BigInt(i.value)!==BigInt(n[c].value)))throw new a("FOBO changed the approved terms. Nothing further was signed. Ask for a fresh summary.")}return d}function ce(t){let e="Oak fee: 0 bps on FOBO\u2019s own route.";if(t.kind==="buy"||t.kind==="sell"){let r=t.terms.tokenPoolTaxPercentNow;if(typeof r!="number"||!Number.isFinite(r)||r<0||r>100)throw new a("FOBO quote did not identify its current tax.");return`${e} FOBO's tax right now: ${r}%; included in the quoted output and minimum.`}return t.kind==="launch"?`${e} FOBO launch fee: ${$(BigInt(t.terms.launchFeeWei),18)} ETH (${t.terms.launchFeeWei} wei).`:t.kind==="limitOrder"?`${e} FOBO keeper fee: at most ${t.request.maxFeePerFill} pay-token base units per fill. Pool tax applies when the order fills; the future tax is not known at preparation.`:`${e} No additional FOBO fee for this ${t.kind==="cancel"?"cancellation":"claim"}; network fees are additional.`}async function we(t,e,r,s){let o=Object.entries(ee).find(([,u])=>u===e)?.[0];if(!o||!Q(s,{strict:!1}))throw new a("Provide a valid FOBO action and local wallet.");let d=ne(o,r),n={};for(let[u,p]of Object.entries(d))n[u]=typeof p=="object"?JSON.stringify(p):p;let i={version:1,kind:e,wallet:x(s),chainId:4663,request:n,terms:{},quotedAt:Math.floor(Date.now()/1e3)};if(e==="launch"){n.pair??="eth",n.devBuyTokens??=0,n.vestMonths??=0;let u=g(g(await t.call("get_fee_schedule",{})).launch);if(u.launchesPaused===!0)throw new a("FOBO launches are paused. Nothing was signed.");let p=y(String(n.pair));n._currencyIn=p.address,n._inputDecimals=p.decimals,i.preparation={status:"ready",transactions:[]},i.terms={launchFeeWei:A(u.feeEth,18,"launch fee"),devBuyTokens:Number(n.devBuyTokens),vestMonths:Number(n.vestMonths),amountIn:String(n.maxInitialBuyAmount??"0")}}else if(e==="buy"||e==="sell"||e==="limitOrder"){n.payWith??=e==="limitOrder"?"eth":"pair";let u=String(n.payWith),p=g(await t.call("get_token",{token:n.token}));if(String(p.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO token metadata does not match the requested token.");let H=y(String(p.pair).replace(/^\$/,"").toLowerCase());u==="pair"&&(u=String(p.pair).replace(/^\$/,"").toLowerCase());let F=y(u);n._payDecimals=F.decimals;let I=e==="limitOrder"?n.side:e;if(n._currencyIn=I==="sell"?String(n.token):F.address,n._currencyOut=I==="sell"?F.address:String(n.token),n._inputDecimals=I==="sell"?18:F.decimals,n._outputDecimals=I==="sell"?F.decimals:18,e!=="limitOrder"&&(n._pools=JSON.stringify(oe(x(String(n.token)),H.address,F.address,I==="sell"))),i.terms={token:x(String(n.token)),payWith:String(n.payWith),amountIn:String(n.amount)},BigInt(String(n.amount))===0n)throw new a("FOBO input amount must be positive.");if(e!=="limitOrder"){n.slippageBps??=50;let{account:J,...z}=W(i),h=g(await t.call("quote_trade",z)),G=A(h.amountIn,Number(n._inputDecimals),"quote input"),{minimum:q}=re(h,Number(n._outputDecimals),Number(n.slippageBps),u);if(G!==n.amount||BigInt(q)===0n||String(h.token).toLowerCase()!==String(n.token).toLowerCase()||h.side!==e)throw new a("FOBO quote does not match the requested trade. Nothing was signed.");if(i.terms.minOut=q,i.terms.slippageBps=Number(n.slippageBps),typeof h.tokenPoolTaxPercentNow!="number"||!Number.isFinite(h.tokenPoolTaxPercentNow)||h.tokenPoolTaxPercentNow<0||h.tokenPoolTaxPercentNow>100)throw new a("FOBO quote did not identify its current tax.");i.terms.tokenPoolTaxPercentNow=h.tokenPoolTaxPercentNow}}if(e==="claim"&&n.kind==="creator"){let u=g(await t.call("get_token",{token:n.token}));if(String(u.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO claim token metadata does not match.");n._poolKey=JSON.stringify(S(y(String(u.pair).replace(/^\$/,"").toLowerCase()).address,x(String(n.token))))}if(e!=="launch"){let u=ae(await t.call(te[e],W(i))),p=await de(i,u,i.quotedAt);if(i.preparation={status:u.status,transactions:p},e==="cancel"||e==="claim"||e==="limitOrder"){if(u.status==="needs_signature")throw new a("This FOBO action must not need a permit signature.");u.status==="ready"&&(n._prepared=JSON.stringify(p))}}let c=e==="launch"?`Launch ${P(String(n.name))} (${P(String(n.ticker))}), pair ${n.pair}, initial buy ${n.devBuyTokens} tokens, lock ${n.vestMonths} months.`:e==="limitOrder"?`Place a FOBO ${n.side} order for ${n.token}, limit market cap ${n.limitMarketCapUsd} USD, expiry ${n.expiresIn??"7d"}, maximum keeper fee ${n.maxFeePerFill} pay-token base units per fill.`:e==="claim"?`Claim FOBO ${n.kind} earnings${n.token?` for ${n.token}`:` in ${n.pair}`} to ${n.to??s}.`:e==="cancel"?`Cancel FOBO order ${n.orderId} and refund ${s}.`:`${e} on FOBO for ${n.token}.`,k=e==="launch"?`Launch fee ${i.terms.launchFeeWei} wei; initial-buy spending cap ${i.terms.amountIn} pair-token base units.`:`Exact input ${i.terms.amountIn??"0"} base units.`,O=`${c}
2
2
  Leaves wallet: ${k}
3
3
  Comes back: ${i.terms.minOut?`at least ${i.terms.minOut} output base units`:e==="launch"?"the launched token and any initial buy, subject to the stated lock":"the approved order or claim proceeds to the named recipient"}.
4
4
  Fees: no Oak swap fee on FOBO's route. ${ce(i)}
@@ -1,4 +1,4 @@
1
- import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Re}from"./7MR37STI.js";import{a as ae}from"./3CCBUYUM.js";import{a as Ze,b as Ge,d as At}from"./X24YTJST.js";import{h as Je,i as St}from"./2GXHYI23.js";import{b as kt,c as yt,d as gt}from"./W7QNSNOH.js";import{d as wt,e as te}from"./GYPMUYB5.js";import{a as ht}from"./Z7FGEWO2.js";import{b as bt}from"./SPJCSEKP.js";import{a as q}from"./43LI5NKJ.js";import{a as A,d as W}from"./66F5ZH34.js";import{d as Oe,g as R,i as Ee}from"./NWNYJ26T.js";import{b as Le}from"./IX3GZMTM.js";import{o as ft}from"./MQ5F2VOK.js";import{b as f,j as z}from"./TI727O2H.js";import{a as i,e as ie}from"./XSD5NL7J.js";import{a as Ye}from"./JXOEJPJ4.js";import{encodeFunctionData as be,erc20Abi as Qa,getAddress as aa,parseAbi as pt,zeroAddress as Xa}from"viem";import{decodeAbiParameters as ca,encodeFunctionData as ua,getAddress as le,parseAbiParameters as ma,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as ra,encodeFunctionData as na,erc20Abi as sa,getAddress as Ct,parseAbi as ia,parseAbiParameters as la,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",da="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=ia(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${da} 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 Pt=(e,t)=>e<t?e:t;async function io(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),c=e.clientFor(f),m=await At(c,t,s),d=(S,B,Ce,ee=[])=>c.readContract({address:S,abi:B,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,b,h,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,sa,"balanceOf",[n]),d(t,Ze,"previewRedeem",[a])]);if(typeof b!="string"||Ct(b)!==$)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<p.timestamp||u>p.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Ge(h))throw new i("maxShares exceeds the wallet share balance.");let y=Pt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-y,T=k[0]?.penalty??0n,x=g*10n**18n/(10n**18n+T);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(x===0n)break;let B=Pt(S.supplied,x);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),x-=B}if(x>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)>Ge(w))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 P=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],E=(await Promise.all(P.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,B)=>S+Ge(B),0n);if(E===0n||E>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>ra(la(Lt),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 ${E} 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.`,v=na({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),U=[e.approval(t,et,E.toString(),f),e.unsignedTx({to:et,data:v,value:"0",chainId:f,description:F})],D=await e.preview(U,n),V=-D.changes.filter(S=>S.token.chainId===f&&R(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(V<=0n||V>E)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:U,preview:D,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},_e={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},pa=ma("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),$t=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:Ut,description:"Bundle: supply, withdraw, supplyCollateralAndBorrow, repayAndWithdrawCollateral, or migrateBorrowPosition (move debt to destinationMarketId)."},marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits); the source market for migrateBorrowPosition."},destinationMarketId:{type:"string",description:"Only for migrateBorrowPosition: verified market id (0x + 64 hex) to move the borrow into; must share the same tokens."},assets:A(`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),collateralAssets:A(`Collateral amount in base units of the market's collateral token (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),shares:A("Market share amount in base units (supply or borrow shares, read the position), instead of assets. Give assets or shares, not both."),maxRepayAssets:A('Most loan token you accept paying to repay, in base units of the loan token (read its decimals). Example: "1000000" = 1 USDG.'),maxLtv:A("Highest loan-to-value allowed after the bundle, as an 18-decimal wad in base units (0.8e18 = 80 percent); cannot exceed the market LLTV."),deadline:A("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000."),allocations:{type:"array",maxItems:4,description:"Up to four Public Allocator moves that add liquidity to the market before borrowing or withdrawing; one per vault.",items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string",description:"Pinned NetNet or Longbow V2 vault address (0x + 40 hex) to pull liquidity from; one entry per vault."},sourceMarketId:{type:"string",description:"Source market id (0x + 64 hex) to pull from; omit to allocate idle vault assets."},assets:A(`Amount to reallocate, in base units of the vault's asset (USDG 6 decimals, WETH 18). Example: "1000000" = 1 USDG.`),maxPenaltyAssets:A(`Highest allocator penalty you accept, in base units of the vault's asset. Example: "10000" = 0.01 USDG for a 6-decimal asset.`)}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(f);if(await n.getChainId()!==f||typeof r!="string"||!Ut.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(v=>!l.includes(v)))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,c]=await Promise.all([n.readContract({address:we,abi:Re,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:we,abi:Re,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(le(u)!==$||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async v=>{if(typeof v!="string"||!j(v))throw new i("Choose a verified Morpho market with a supported exit.");let U=await n.readContract({address:$,abi:O,functionName:"idToMarketParams",args:[v],blockNumber:a.number}),D={loanToken:le(U[0]),collateralToken:le(U[1]),oracle:le(U[2]),irm:le(U[3]),lltv:U[4]};if(!R(ke({...D,lltv:String(D.lltv)}),v))throw new i("Blue bundle market identity mismatch.");return D},d=await m(t.marketId),p=r==="migrateBorrowPosition"?await m(t.destinationMarketId):d;if(d.loanToken!==p.loanToken||d.collateralToken!==p.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:$,abi:O,functionName:"isAuthorized",args:[s,we],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${we}, 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),h=t.shares===void 0?0n:N(t.shares,!0),w=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(h===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&h>0n||b===0n&&h===0n&&w===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=[],x=0n;for(let v of k){if(!v||typeof v!="object"||Array.isArray(v)||Object.keys(v).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let U=v,D=await It(e,{vault:U.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(D.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(D.definition.vault.toLowerCase());let V=N(U.assets),S=N(U.maxPenaltyAssets,!0);if(!D.permission||V>=1n<<128n||V>D.headroom||D.penalty>10n**18n||D.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(V*D.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=B;let Ce=U.sourceMarketId===void 0,ee=Ce?void 0:D.sources.find(Xe=>R(Xe.id,String(U.sourceMarketId)));if(Ce?!D.canIdle||V>D.data.idle:!ee||!ee.canPull||V>ee.capacity||V>D.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:D.definition.vault,adapter:D.target.adapter,marketParams:D.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?ca(pa,ee.data)[0]:D.params,assets:V,penalty:D.penalty,fromIdle:Ce})}let M,C,P,I=0n;if(r==="supply")M="blueBundlesV1Supply",P=d.loanToken,I=b,C=[d,b,tt,0n,he,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[d,b,h,_e,T,0n,he,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",P=d.collateralToken,I=w,x>=b&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[d,w,b,y,tt,_e,T,0n,he,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",P=d.loanToken,I=N(t.maxRepayAssets,!0),b>I||h>0n&&I===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[d,b,h,I,w,y,tt,_e,0n,he,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[d,p,y,_e,T,0n,he,o];let E=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} 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 ${I}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...P&&I?[e.approval(P,we,I.toString(),f)]:[],e.unsignedTx({to:we,data:ua({abi:Re,functionName:M,args:C}),value:"0",chainId:f,description:E})],H=await e.preview(Z,s),F=new Map;for(let v of H.changes)if(BigInt(v.amount)<0n){let U=v.token.address.toLowerCase();F.set(U,(F.get(U)??0n)-BigInt(v.amount))}if([...F].some(([v,U])=>!P||v!==P.toLowerCase()||U>I))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:E}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as fa,encodeAbiParameters as Rt,encodeFunctionData as at,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as ba}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ha=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=ae.find(e=>e.name==="take"),Ot=[nt.inputs[0]],wa=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(wa,[e])]));return rt(Bt(["0xff",e.midnight,ba,t]))}var de=10n**18n,Gt=(e,t)=>(e+(t-1n)/2n)/t;function _t(e){if(e<0n)return 10n**36n/_t(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*de),l=n*r/(3n*de);return de+r+n+l<<s}function ka(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Gt(Gt(10n**36n,de+_t(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function He(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 ot(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 ya=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let a=He(n,32),o=e.clientFor(f);if(await o.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),c=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await c("toMarket",[a]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![z[f].tokens.USDG.address,z[f].tokens.WETH.address].some(k=>R(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[p,b,h,w]=await Promise.all([c("position",[a,l]),c("updatePositionView",[m,a,l]),c("marketState",[a]),c("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Nt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Nt,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:f}};return{id:a,rpc:o,block:u,market:m,read:c,token:y,loan:await y(m.loanToken),position:ot(p,6),updated:ot(b,3),state:ot(h,13),healthy:w}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,c)}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",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,d)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ya(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",description:"Hex proof data (0x...) that the offer's pinned ratifier uses to confirm the maker approved this offer."},units:A("Fixed debt units to trade, as a decimal string below 2^128. The asset cost or proceeds follow from the offer price; maxAssets and minAssets bound them."),maxAssets:A('Most loan token you will spend when buying credit, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minAssets:A('Least loan token you must receive when selling credit or borrowing, in base units of the market loan token. Example: "1000000" = 1 USDG.')},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=He(n.offer),[o]=fa(Ot,a);if(!R(Rt(Ot,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Et(o.market),l),c=N(n.units),m=N(n.maxAssets,!0),d=N(n.minAssets,!0),p=He(n.ratifierData);if(c>=1n<<128n||R(o.maker,l)||o.callback!==ye||o.callbackData!=="0x"||!ha.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!==ye||!o.buy&&o.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&c>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]),h=ka(o.tick);if(b>h&&o.buy)throw new i("Settlement fee exceeds the offer price.");let w=o.buy?h-b:h,y=w+b,k=v=>o.buy?v/de:(v+de-1n)/de,g=k(c*y),T=k(c*w);if(o.buy?T<d||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||x+(o.maxAssets?o.buy?g:T:c)>(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:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],P=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,p,l],blockNumber:u.block.number});if(M!==!0||P!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let I=at({abi:ae,functionName:"take",args:[o,p,c,l,o.buy?l:ye,ye,"0x"]}),E=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} 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(),f)],e.unsignedTx({to:Y,data:I,value:"0",chainId:f,description:E})],H=await r(Z,l,E),F=H.preview.changes.filter(v=>v.token.chainId===f&&R(v.token.address,u.loan.address)).reduce((v,U)=>v+BigInt(U.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",description:"Midnight market id: 0x + 64 hex digits (bytes32)."},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"],description:"Action: add or remove collateral, repay debt, withdraw matured credit, refresh the position, or claim continuous fees (fee claimer only)."},amount:A('Amount in base units of the relevant token: the collateral token for collateral operations, else the loan token (read decimals). Example: "1000000" = 1 USDG.'),collateralIndex:{type:"integer",minimum:0,maximum:127,description:"Zero-based position of the collateral in the market collateral list; required for supplyCollateral and withdrawCollateral only."}},["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,c,m=a.loan,d=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(d=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,d,l]}else{if(d=N(n.amount),d>=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 h=BigInt(String(n.collateralIndex)),w=await a.token(a.market.collateralParams[Number(h)].token);if(m=w,o==="withdrawCollateral"&&d>await a.read("collateral",[a.id,l,h]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,h,d,l]:[a.market,h,d,l,l],o==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&d>a.position[4]||o==="withdraw"&&(d>a.updated[0]||d>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,d,l,ye,"0x"]:[a.market,d,l,l],o==="repay"&&(c=a.loan)}}let p=`Midnight ${o}: ${d} ${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=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:at({abi:ae,functionName:String(o),args:u}),value:"0",chainId:f,description:p})];return r(b,l,p)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"],description:"Midnight management function name; role-gated except setConsumed and setIsAuthorized, which act on this wallet."},values:{type:"array",maxItems:3,description:"Ordered arguments for the chosen operation, as in the Midnight ABI: decimal strings for integers (base units), 0x addresses or bytes32, or booleans.",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(p=>p.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let c=e.clientFor(f);if(await c.getChainId()!==f)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((p,b)=>{let h=n.values[b];if(p.type==="bool"){if(typeof h!="boolean")throw new i("Use boolean management values.");return h}if(p.type==="address")return Ee(h,"Use explicit management addresses.",Oe);if(p.type==="bytes32")return He(h,32);if(/^uint/.test(p.type)){let w=N(h,!0);if(w>=1n<<BigInt(p.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return w}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!R(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let p=await c.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`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:at({abi:ae,functionName:o,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as ga,encodeFunctionData as G,erc20Abi as it,getAddress as L,isAddress as Fe,keccak256 as Sa,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Aa="https://api.morpho.org/graphql",$=L(z[f].morpho.morpho_blue.address),xa=L(z[f].morpho.adaptive_curve_irm.address),Ia=L(z[f].morpho.USDG.address),me=L(z[f].morpho.WETH.address),Ta=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Ma={"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."},lt=[{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"}],va=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return va.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Ma[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,Ue=120n,ze=1000000n,We=1n,Se=10n**18n,Pa=10n**36n,jt=(1n<<128n)-1n,Ca=(1n<<256n)-1n,X=Ve(["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)"]),La=Ve(["function price() view returns (uint256)"]),Da=Ve(["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)"]),Kt=Ve(["function deposit() payable"]);function pe(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function $e(e,t){return e===0n?0n:(e+t-1n)/t}function Ua(e,t,s){return e*(s+ze)/(t+We)}function $a(e,t,s){return $e(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return $e(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Pa*s/Se}function Ba(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function xe(e,t){let s=[],r={};for(let n of t.changes){let l=Ba(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 Qt(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 je(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"||!Fe(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:Le(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>=Se)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function ke(e){let t=je(e),s=ga(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return Sa(s)}function dt(e){let t=e.toLowerCase();return t===ht.toLowerCase()||t===wt.toLowerCase()||t===te.toLowerCase()}function Ie(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function ne(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 Xt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=f){if(q(t),dt(t))return{...kt,chainId:s};let r=L(t),n=r.toLowerCase();if(s===f){if(n===Ia.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,a]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[o]=re(J("string"),l),[u]=re(J("uint8"),a);return{address:r,symbol:Xt(o),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,$,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=re(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 ne(e,$,G({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Te(e,t,s){let r=await ne(e,$,G({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Ke(e,t){let s=await ne(e,L(t),G({abi:La,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Na(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,L(t.irm),G({abi:Da,functionName:"borrowRateView",args:[t,s]})),[n]=re(J("uint256"),r);return n}function Qe(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=$e(n*n,2n*Se),a=$e(l*n,3n*Se);return e.totalBorrowAssets+$e(e.totalBorrowAssets*(n+l+a),Se)}async function Be(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Na(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:Qe(s,l,o),accruedThrough:o,rate:l}}async function Zt(e,t,s){let r=await ne(e,L(t),G({abi:it,functionName:"balanceOf",args:[L(s)]})),[n]=re(J("uint256"),r);return n}async function fe(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?je(n):void 0,a=l?ke(l):void 0,o=r!==void 0?Qt(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&&!j(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[c,m]=await Promise.all([Yt(e,u),Jt(e,u)]);if(c.loanToken===te||c.collateralToken===te||c.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${f}.`);let d=ke(c);if(d.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${d}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===c.oracle.toLowerCase()&&l.irm.toLowerCase()===c.irm.toLowerCase()&&l.lltv===c.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:c,marketState:m}}function Me(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=Le(t);if(s<=0n||s>jt)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function ve(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 Oa(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:a,marketParams:o}=await fe(l,t,!0),u=await Q(l,o.collateralToken,f),c=o.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),b=p.toString(),h=e.formatAmount(b,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:b,description:`Wrap ${h} ETH into WETH at ${me}.`})),w.push(e.approval(o.collateralToken,$,b,f)),w.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supplyCollateral",args:[o,p,n,"0x"]}),value:"0",description:`Supply ${h} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply_collateral",chainId:f,marketId:a,marketParams:pe(o),collateralToken:u,assets:b,formattedAssets:h,onBehalf:n,txs:w,summary:`${d?`Send ${h} ETH to wrap into WETH. `:""}Supply ${h} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ea(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.loanToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=Me(t),w=h.toString(),y=e.formatAmount(w,m.decimals),k=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(h>k)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${k.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),T=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||T+h>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+h).toString()} exceeds max borrow ${g.toString()} base units.`);let x=$a(h,b.totalBorrowAssets,c.totalBorrowShares),C=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"borrow",args:[u,h,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${w} base units) from Morpho market ${o}.`})],P=await e.preview(C,r),{formattedChanges:I,formattedNetOutflows:E}=xe(e,P);return{action:"morpho_borrow",chainId:f,marketId:o,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:y,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:P,formattedChanges:I,formattedNetOutflows:E}}async function Ga(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f);if(t.shares!==void 0){let I=Le(t.shares);if(I<=0n||I===Ca||I>jt)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(W("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 fe(l,t,!0),[c,m,d]=await Promise.all([Q(l,o.loanToken,f),Te(l,a,n),Zt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let p=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let I=Le(t.shares);if(I>m.borrowShares)throw new i(`Repay shares (${I.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=I}else p=Me(t);let h=b>0n?await Be(l,o,u,Ue):void 0,w=b>0n?se(b,h.totalBorrowAssets,u.totalBorrowShares):p;if(d<w)throw new i(`Insufficient loan token balance for repayment: wallet holds ${d.toString()} base units, but ${w.toString()} base units are required (including accrued interest).`);let y=w.toString(),k=e.formatAmount(y,c.decimals),g=e.approval(o.loanToken,$,y,f),T=e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"repay",args:[o,p,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${c.symbol}) on Morpho market ${a}.`:`Repay ${k} ${c.symbol} (${p.toString()} base units) on Morpho market ${a}.`}),x=[g,T],M=await e.preview(x,r),{formattedChanges:C,formattedNetOutflows:P}=xe(e,M);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,repayAssets:p.toString(),repayShares:b.toString(),requiredAssets:y,...h?{accruedThrough:h.accruedThrough.toString(),borrowRatePerSecond:h.rate.toString(),inclusionSeconds:Ue.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:x,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${c.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${Ue} seconds.`:`Repay ${k} ${c.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:P}}async function Ra(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.collateralToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(h<=0n||h>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${h.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let C=d.collateral-h,P=Ae(C,p,u.lltv),I=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(I>P)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${P.toString()} would fall below current debt ${I.toString()} base units.`)}let w=h.toString(),y=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdrawCollateral",args:[u,h,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${w} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw_collateral",chainId:f,marketId:o,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function _a(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:a,marketState:o}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==me.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let c=Me(t),m=c.toString(),[d,p]=await Promise.all([Q(n,a.loanToken,f),u?Promise.resolve(c):Zt(n,a.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,d.decimals),h=[];u&&h.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${me}.`})),h.push(e.approval(a.loanToken,$,m,f)),h.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supply",args:[a,c,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Ua(c,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(a),loanToken:d,assets:m,formattedAssets:b,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:h,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${d.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 Ha(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),l=W("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 fe(n,t,!0),[c,m]=await Promise.all([Q(n,o.loanToken,f),Te(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${a}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),b=l?m.supplyShares:0n;if(!l&&p>d)throw new i(`Withdrawal exceeds the lent balance: requested ${p.toString()} base units, position holds about ${d.toString()}. Use withdrawAll for a full exit.`);let h=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>h)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${h.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdraw",args:[o,p,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${c.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,withdrawAssets:p.toString(),withdrawShares:b.toString(),estimatedAssets:w.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${c.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function ea(e,t,s){let r=await e.http(Aa,{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 ta(e){let t=`query Markets($chainId: Int!) {
1
+ import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Ge}from"./7MR37STI.js";import{a as oe}from"./3CCBUYUM.js";import{a as Ze,b as Ee,d as At}from"./X24YTJST.js";import{h as Je,i as St}from"./2GXHYI23.js";import{b as kt,c as yt,d as gt}from"./W7QNSNOH.js";import{d as wt,e as te}from"./GYPMUYB5.js";import{a as ht}from"./Z7FGEWO2.js";import{b as bt}from"./SPJCSEKP.js";import{a as q}from"./43LI5NKJ.js";import{a as A,d as W}from"./66F5ZH34.js";import{d as Ne,g as R,i as Oe}from"./NWNYJ26T.js";import{b as Le}from"./IX3GZMTM.js";import{o as ft}from"./MQ5F2VOK.js";import{b as f,j as z}from"./TI727O2H.js";import{a as i,e as ie}from"./XSD5NL7J.js";import{a as Ye}from"./JXOEJPJ4.js";import{encodeFunctionData as be,erc20Abi as Xo,getAddress as ao,parseAbi as pt,zeroAddress as Yo}from"viem";import{decodeAbiParameters as mo,encodeFunctionData as po,getAddress as le,parseAbiParameters as fo,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as no,encodeFunctionData as so,erc20Abi as io,getAddress as Ct,parseAbi as lo,parseAbiParameters as co,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",uo="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=lo(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${uo} sharesPermit,uint256 deadline)`]);function O(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 Pt=(e,t)=>e<t?e:t;async function la(e,t,s,r,n){q(n);let l=O(r.amount),o=O(r.maxShares),a=O(r.maxPenaltyAssets,!0),u=O(r.deadline),c=e.clientFor(f),m=await At(c,t,s),d=(S,N,Ce,ee=[])=>c.readContract({address:S,abi:N,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,h,b,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,io,"balanceOf",[n]),d(t,Ze,"previewRedeem",[o])]);if(typeof h!="string"||Ct(h)!==B)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<p.timestamp||u>p.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(o>Ee(b))throw new i("maxShares exceeds the wallet share balance.");let k=Pt(m.idle,l),y=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-k,I=y[0]?.penalty??0n,x=g*10n**18n/(10n**18n+I);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let T=[];for(let S of y){if(x===0n)break;let N=Pt(S.supplied,x);T.push({marketId:S.id,assets:N,penalty:(N*S.penalty+10n**18n-1n)/10n**18n}),x-=N}if(x>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(T.length)>Ee(w))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(T.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let P=T.reduce((S,N)=>S+N.penalty,0n);if(P>a)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let C=[...k?[k]:[],...T.flatMap(S=>[S.assets,S.penalty].filter(N=>N>0n))],v=(await Promise.all(C.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,N)=>S+Ee(N),0n);if(v===0n||v>o)throw new i("Separately rounded burns exceed maxShares.");let Z=T.map(S=>no(co(Lt),m.markets.find(N=>N.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 ${v} share base units; receive ${k} ${s.symbol} base units and Morpho Blue supply positions ${T.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${P} ${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.`,M=so({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),$=[e.approval(t,et,v.toString(),f),e.unsignedTx({to:et,data:M,value:"0",chainId:f,description:F})],U=await e.preview($,n),V=-U.changes.filter(S=>S.token.chainId===f&&R(S.token.address,t)).reduce((S,N)=>{if(N.token.decimals!==18||!/^-?\d+$/.test(N.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(N.amount)},0n);if(V<=0n||V>v)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:$,preview:U,summary:F,receipt:{idleAssets:k.toString(),positions:T.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:P.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},Re={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},bo=fo("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),$t=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:Ut,description:"Bundle: supply, withdraw, supplyCollateralAndBorrow, repayAndWithdrawCollateral, or migrateBorrowPosition (move debt to destinationMarketId)."},marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits); the source market for migrateBorrowPosition."},destinationMarketId:{type:"string",description:"Only for migrateBorrowPosition: verified market id (0x + 64 hex) to move the borrow into; must share the same tokens."},assets:A(`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),collateralAssets:A(`Collateral amount in base units of the market's collateral token (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),shares:A("Market share amount in base units (supply or borrow shares, read the position), instead of assets. Give assets or shares, not both."),maxRepayAssets:A('Most loan token you accept paying to repay, in base units of the loan token (read its decimals). Example: "1000000" = 1 USDG.'),maxLtv:A("Highest loan-to-value allowed after the bundle, as an 18-decimal wad in base units (0.8e18 = 80 percent); cannot exceed the market LLTV."),deadline:A("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000."),allocations:{type:"array",maxItems:4,description:"Up to four Public Allocator moves that add liquidity to the market before borrowing or withdrawing; one per vault.",items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string",description:"Pinned NetNet or Longbow V2 vault address (0x + 40 hex) to pull liquidity from; one entry per vault."},sourceMarketId:{type:"string",description:"Source market id (0x + 64 hex) to pull from; omit to allocate idle vault assets."},assets:A(`Amount to reallocate, in base units of the vault's asset (USDG 6 decimals, WETH 18). Example: "1000000" = 1 USDG.`),maxPenaltyAssets:A(`Highest allocator penalty you accept, in base units of the vault's asset. Example: "10000" = 0.01 USDG for a 6-decimal asset.`)}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(f);if(await n.getChainId()!==f||typeof r!="string"||!Ut.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(M=>!l.includes(M)))throw new i("Unexpected argument for this Blue bundle.");let o=await n.getBlock(),a=O(t.deadline);if(a<o.timestamp||a>o.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,c]=await Promise.all([n.readContract({address:we,abi:Ge,functionName:"BLUE",blockNumber:o.number}),n.readContract({address:we,abi:Ge,functionName:"PUBLIC_ALLOCATOR",blockNumber:o.number})]);if(le(u)!==B||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async M=>{if(typeof M!="string"||!j(M))throw new i("Choose a verified Morpho market with a supported exit.");let $=await n.readContract({address:B,abi:E,functionName:"idToMarketParams",args:[M],blockNumber:o.number}),U={loanToken:le($[0]),collateralToken:le($[1]),oracle:le($[2]),irm:le($[3]),lltv:$[4]};if(!R(ke({...U,lltv:String(U.lltv)}),M))throw new i("Blue bundle market identity mismatch.");return U},d=await m(t.marketId),p=r==="migrateBorrowPosition"?await m(t.destinationMarketId):d;if(d.loanToken!==p.loanToken||d.collateralToken!==p.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:B,abi:E,functionName:"isAuthorized",args:[s,we],blockNumber:o.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${we}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let h=t.assets===void 0?0n:O(t.assets,!0),b=t.shares===void 0?0n:O(t.shares,!0),w=t.collateralAssets===void 0?0n:O(t.collateralAssets,!0),k=r==="supply"||r==="withdraw"?0n:O(t.maxLtv,!0);if(k>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&h===0n||r==="withdraw"&&h===0n==(b===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&h===0n||r==="repayAndWithdrawCollateral"&&(h>0n&&b>0n||h===0n&&b===0n&&w===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let y=t.allocations??[];if(!Array.isArray(y)||y.length>4||y.length&&r==="supplyCollateralAndBorrow"&&h===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,I=[],x=0n;for(let M of y){if(!M||typeof M!="object"||Array.isArray(M)||Object.keys(M).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let $=M,U=await It(e,{vault:$.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(U.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(U.definition.vault.toLowerCase());let V=O($.assets),S=O($.maxPenaltyAssets,!0);if(!U.permission||V>=1n<<128n||V>U.headroom||U.penalty>10n**18n||U.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let N=(V*U.penalty+10n**18n-1n)/10n**18n;if(N>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=N;let Ce=$.sourceMarketId===void 0,ee=Ce?void 0:U.sources.find(Xe=>R(Xe.id,String($.sourceMarketId)));if(Ce?!U.canIdle||V>U.data.idle:!ee||!ee.canPull||V>ee.capacity||V>U.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");I.push({vault:U.definition.vault,adapter:U.target.adapter,marketParams:U.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?mo(bo,ee.data)[0]:U.params,assets:V,penalty:U.penalty,fromIdle:Ce})}let T,P,C,L=0n;if(r==="supply")T="blueBundlesV1Supply",C=d.loanToken,L=h,P=[d,h,tt,0n,he,a];else if(r==="withdraw")T="blueBundlesV1Withdraw",P=[d,h,b,Re,I,0n,he,a];else if(r==="supplyCollateralAndBorrow"){if(T="blueBundlesV1SupplyCollateralAndBorrow",C=d.collateralToken,L=w,x>=h&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");P=[d,w,h,k,tt,Re,I,0n,he,a]}else if(r==="repayAndWithdrawCollateral"){if(T="blueBundlesV1RepayAndWithdrawCollateral",C=d.loanToken,L=O(t.maxRepayAssets,!0),h>L||b>0n&&L===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");P=[d,h,b,L,w,k,tt,Re,0n,he,a]}else T="blueBundlesV1MigrateBorrowPosition",P=[d,p,k,Re,I,0n,he,a];let v=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} loan-token base units; zero referral fee. Max LTV ${k}; absolute deadline ${a}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${L}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...C&&L?[e.approval(C,we,L.toString(),f)]:[],e.unsignedTx({to:we,data:po({abi:Ge,functionName:T,args:P}),value:"0",chainId:f,description:v})],H=await e.preview(Z,s),F=new Map;for(let M of H.changes)if(BigInt(M.amount)<0n){let $=M.token.address.toLowerCase();F.set($,(F.get($)??0n)-BigInt(M.amount))}if([...F].some(([M,$])=>!C||M!==C.toLowerCase()||$>L))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:v}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as ho,encodeAbiParameters as Rt,encodeFunctionData as ot,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as wo}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ko=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=oe.find(e=>e.name==="take"),Ot=[nt.inputs[0]],yo=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(yo,[e])]));return rt(Bt(["0xff",e.midnight,wo,t]))}var de=10n**18n,Gt=(e,t)=>(e+(t-1n)/2n)/t;function _t(e){if(e<0n)return 10n**36n/_t(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*de),l=n*r/(3n*de);return de+r+n+l<<s}function go(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Gt(Gt(10n**36n,de+_t(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function _e(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 at(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 So=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let o=_e(n,32),a=e.clientFor(f);if(await a.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await a.getBlock(),c=(y,g=[])=>a.readContract({address:Y,abi:oe,functionName:y,args:g,blockNumber:u.number}),m=await c("toMarket",[o]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),o))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![z[f].tokens.USDG.address,z[f].tokens.WETH.address].some(y=>R(y,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[p,h,b,w]=await Promise.all([c("position",[o,l]),c("updatePositionView",[m,o,l]),c("marketState",[o]),c("isHealthy",[m,o,l])]),k=async y=>{let[g,I]=await Promise.all([a.readContract({address:y,abi:Nt,functionName:"decimals",blockNumber:u.number}),a.readContract({address:y,abi:Nt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof I!="string")throw new i("Invalid Midnight token metadata.");return{address:K(y),decimals:g,symbol:I.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:f}};return{id:o,rpc:a,block:u,market:m,read:c,token:k,loan:await k(m.loanToken),position:at(p,6),updated:at(h,3),state:at(b,13),healthy:w}}let s=(n,l,o,a)=>({name:n,inputSchema:{type:"object",properties:l,required:o,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await a(u,c)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,o){return{txs:n,preview:await e.preview(n,l),summary:o}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let o=await t(n.marketId,l),a=await Promise.all(o.market.collateralParams.map(async(m,d)=>({token:await o.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await o.read("collateral",[o.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>o.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(o.state[11]),tickSpacing:String(o.state[12]),settlementFeeCbps:o.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:o.id,blockNumber:String(o.block.number),market:So(o.market),loanToken:o.loan,collaterals:a,debtUnits:String(o.position[4]),creditUnits:String(o.updated[0]),pendingFeeUnits:String(o.updated[1]),withdrawableUnits:String(o.state[2]),healthy:o.healthy,maturity:String(o.market.maturity),matured:o.block.timestamp>o.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",description:"Hex proof data (0x...) that the offer's pinned ratifier uses to confirm the maker approved this offer."},units:A("Fixed debt units to trade, as a decimal string below 2^128. The asset cost or proceeds follow from the offer price; maxAssets and minAssets bound them."),maxAssets:A('Most loan token you will spend when buying credit, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minAssets:A('Least loan token you must receive when selling credit or borrowing, in base units of the market loan token. Example: "1000000" = 1 USDG.')},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let o=_e(n.offer),[a]=ho(Ot,o);if(!R(Rt(Ot,[a]),o))throw new i("Offer encoding is not canonical.");let u=await t(Et(a.market),l),c=O(n.units),m=O(n.maxAssets,!0),d=O(n.minAssets,!0),p=_e(n.ratifierData);if(c>=1n<<128n||R(a.maker,l)||a.callback!==ye||a.callbackData!=="0x"||!ko.includes(K(a.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<a.start||u.block.timestamp>a.expiry||a.expiry<a.start)throw new i("The Midnight offer is not currently live.");if(a.buy&&a.receiverIfMakerIsSeller!==ye||!a.buy&&a.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(a.buy&&u.block.timestamp>u.market.maturity&&c>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let h=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),b=go(a.tick);if(h>b&&a.buy)throw new i("Settlement fee exceeds the offer price.");let w=a.buy?b-h:b,k=w+h,y=M=>a.buy?M/de:(M+de-1n)/de,g=y(c*k),I=y(c*w);if(a.buy?I<d||I===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[a.maker,a.group]);if(a.maxAssets===0n==(a.maxUnits===0n)||x+(a.maxAssets?a.buy?g:I:c)>(a.maxAssets||a.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>a.continuousFeeCap||a.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let T=await u.read("isAuthorized",[a.maker,a.ratifier]),P=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],C=await u.rpc.readContract({address:a.ratifier,abi:P,functionName:"isRatified",args:[a,p,l],blockNumber:u.block.number});if(T!==!0||C!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let L=ot({abi:oe,functionName:"take",args:[a,p,c,l,a.buy?l:ye,ye,"0x"]}),v=`Midnight ${a.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} fixed debt units; ${a.buy?`receive ${I}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${a.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=[...a.buy?[]:[e.approval(u.loan.address,Y,g.toString(),f)],e.unsignedTx({to:Y,data:L,value:"0",chainId:f,description:v})],H=await r(Z,l,v),F=H.preview.changes.filter(M=>M.token.chainId===f&&R(M.token.address,u.loan.address)).reduce((M,$)=>M+BigInt($.amount),0n);if(a.buy?F<I:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"],description:"Action: add or remove collateral, repay debt, withdraw matured credit, refresh the position, or claim continuous fees (fee claimer only)."},amount:A('Amount in base units of the relevant token: the collateral token for collateral operations, else the loan token (read decimals). Example: "1000000" = 1 USDG.'),collateralIndex:{type:"integer",minimum:0,maximum:127,description:"Zero-based position of the collateral in the market collateral list; required for supplyCollateral and withdrawCollateral only."}},["marketId","operation"],async(n,l)=>{let o=await t(n.marketId,l),a=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(a)))throw new i("Choose a finite Midnight position operation.");let u,c,m=o.loan,d=0n;if(a==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[o.market,l]}else if(a==="claimContinuousFee"){if(d=O(n.amount),n.collateralIndex!==void 0||K(String(await o.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[o.market,d,l]}else{if(d=O(n.amount),d>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(a==="supplyCollateral"||a==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=o.market.collateralParams.length)throw new i("Choose a current collateral index.");let b=BigInt(String(n.collateralIndex)),w=await o.token(o.market.collateralParams[Number(b)].token);if(m=w,a==="withdrawCollateral"&&d>await o.read("collateral",[o.id,l,b]))throw new i("Insufficient Midnight collateral.");u=a==="supplyCollateral"?[o.market,b,d,l]:[o.market,b,d,l,l],a==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(a==="repay"&&d>o.position[4]||a==="withdraw"&&(d>o.updated[0]||d>o.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=a==="repay"?[o.market,d,l,ye,"0x"]:[o.market,d,l,l],a==="repay"&&(c=o.loan)}}let p=`Midnight ${a}: ${d} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${o.id}; beneficiary ${l}; maturity ${o.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,h=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:ot({abi:oe,functionName:String(a),args:u}),value:"0",chainId:f,description:p})];return r(h,l,p)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"],description:"Midnight management function name; role-gated except setConsumed and setIsAuthorized, which act on this wallet."},values:{type:"array",maxItems:3,description:"Ordered arguments for the chosen operation, as in the Midnight ABI: decimal strings for integers (base units), 0x addresses or bytes32, or booleans.",items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let o={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(o)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let a=n.operation,u=oe.find(p=>p.name===a);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let c=e.clientFor(f);if(await c.getChainId()!==f)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((p,h)=>{let b=n.values[h];if(p.type==="bool"){if(typeof b!="boolean")throw new i("Use boolean management values.");return b}if(p.type==="address")return Oe(b,"Use explicit management addresses.",Ne);if(p.type==="bytes32")return _e(b,32);if(/^uint/.test(p.type)){let w=O(b,!0);if(w>=1n<<BigInt(p.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return w}throw new i("Unsupported management argument type.")});if(a==="setConsumed"||a==="setIsAuthorized"){if(!R(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let p=await c.readContract({address:Y,abi:oe,functionName:o[a]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`Midnight ${a}, ordered values ${JSON.stringify(n.values)}. ${a==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${a==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:ot({abi:oe,functionName:a,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as Ao,encodeFunctionData as G,erc20Abi as it,getAddress as D,isAddress as Fe,keccak256 as xo,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Io="https://api.morpho.org/graphql",B=D(z[f].morpho.morpho_blue.address),To=D(z[f].morpho.adaptive_curve_irm.address),Mo=D(z[f].morpho.USDG.address),me=D(z[f].morpho.WETH.address),vo=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Po={"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."},lt=[{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"}],Co=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return Co.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Po[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,qe=120n,ze=1000000n,We=1n,Se=10n**18n,Lo=10n**36n,jt=(1n<<128n)-1n,Do=(1n<<256n)-1n,X=Ve(["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)"]),Uo=Ve(["function price() view returns (uint256)"]),$o=Ve(["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)"]),Kt=Ve(["function deposit() payable"]);function pe(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ue(e,t){return e===0n?0n:(e+t-1n)/t}function Bo(e,t,s){return e*(s+ze)/(t+We)}function No(e,t,s){return Ue(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return Ue(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Lo*s/Se}function Oo(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function xe(e,t){let s=[],r={};for(let n of t.changes){let l=Oo(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 Qt(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 je(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let o of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof o!="string"||!Fe(o,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=D(e.loanToken),s=D(e.collateralToken),r=D(e.oracle),n=D(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Le(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>=Se)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function ke(e){let t=je(e),s=Ao(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return xo(s)}function dt(e){let t=e.toLowerCase();return t===ht.toLowerCase()||t===wt.toLowerCase()||t===te.toLowerCase()}function Ie(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),D(s)}async function ne(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 Xt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=f){if(q(t),dt(t))return{...kt,chainId:s};let r=D(t),n=r.toLowerCase();if(s===f){if(n===Mo.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,o]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[a]=re(J("string"),l),[u]=re(J("uint8"),o);return{address:r,symbol:Xt(a),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,B,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,o,a]=re(J("address, address, address, address, uint256"),s);return{loanToken:D(r),collateralToken:D(n),oracle:D(l),irm:D(o),lltv:a}}async function Jt(e,t){let s=await ne(e,B,G({abi:X,functionName:"market",args:[t]})),[r,n,l,o,a,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:o,lastUpdate:a,fee:u}}async function Te(e,t,s){let r=await ne(e,B,G({abi:X,functionName:"position",args:[t,D(s)]})),[n,l,o]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:o}}async function Ke(e,t){let s=await ne(e,D(t),G({abi:Uo,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Eo(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,D(t.irm),G({abi:$o,functionName:"borrowRateView",args:[t,s]})),[n]=re(J("uint256"),r);return n}function Qe(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ue(n*n,2n*Se),o=Ue(l*n,3n*Se);return e.totalBorrowAssets+Ue(e.totalBorrowAssets*(n+l+o),Se)}async function $e(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Eo(e,t,s)]),o=BigInt(Math.ceil(Date.now()/1e3)),a=(n.timestamp>o?n.timestamp:o)+r;return{totalBorrowAssets:Qe(s,l,a),accruedThrough:a,rate:l}}async function Zt(e,t,s){let r=await ne(e,D(t),G({abi:it,functionName:"balanceOf",args:[D(s)]})),[n]=re(J("uint256"),r);return n}async function fe(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?je(n):void 0,o=l?ke(l):void 0,a=r!==void 0?Qt(r):void 0;if(a&&o&&a!==o.toLowerCase())throw new i(`MarketParams tuple hash (${o}) does not match marketId (${a}).`);let u=(a??o).toLowerCase();if(s&&!j(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[c,m]=await Promise.all([Yt(e,u),Jt(e,u)]);if(c.loanToken===te||c.collateralToken===te||c.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${f}.`);let d=ke(c);if(d.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${d}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===c.oracle.toLowerCase()&&l.irm.toLowerCase()===c.irm.toLowerCase()&&l.lltv===c.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:c,marketState:m}}function Me(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=Le(t);if(s<=0n||s>jt)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function ve(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 Go(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:o,marketParams:a}=await fe(l,t,!0),u=await Q(l,a.collateralToken,f),c=a.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),D(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==a.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${a.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),h=p.toString(),b=e.formatAmount(h,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:h,description:`Wrap ${b} ETH into WETH at ${me}.`})),w.push(e.approval(a.collateralToken,B,h,f)),w.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supplyCollateral",args:[a,p,n,"0x"]}),value:"0",description:`Supply ${b} ${u.symbol} (${h} base units) collateral to Morpho market ${o}.`}));let k=await e.preview(w,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply_collateral",chainId:f,marketId:o,marketParams:pe(a),collateralToken:u,assets:h,formattedAssets:b,onBehalf:n,txs:w,summary:`${d?`Send ${b} ETH to wrap into WETH. `:""}Supply ${b} ${u.symbol} collateral to Morpho Blue market ${o}.`,preview:k,formattedChanges:y,formattedNetOutflows:g}}async function Ro(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=Me(t),w=b.toString(),k=e.formatAmount(w,m.decimals),y=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(b>y)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${y.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),I=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||I+b>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(I+b).toString()} exceeds max borrow ${g.toString()} base units.`);let x=No(b,h.totalBorrowAssets,c.totalBorrowShares),P=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"borrow",args:[u,b,0n,n,l]}),value:"0",description:`Borrow ${k} ${m.symbol} (${w} base units) from Morpho market ${a}.`})],C=await e.preview(P,r),{formattedChanges:L,formattedNetOutflows:v}=xe(e,C);return{action:"morpho_borrow",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:k,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:P,summary:`Borrow ${k} ${m.symbol} from Morpho Blue market ${a}.`,preview:C,formattedChanges:L,formattedNetOutflows:v}}async function eo(e,t,s,r=qe){let n=Ie(t,s);ve(t,n);let l=n,o=e.clientFor(f);if(t.shares!==void 0){let v=Le(t.shares);if(v<=0n||v===Do||v>jt)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(W("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:u,marketState:c}=await fe(o,t,!0),[m,d,p]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,l),Zt(o,u.loanToken,n)]);if(d.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let h=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=d.borrowShares;else if(t.shares!==void 0){let v=Le(t.shares);if(v>d.borrowShares)throw new i(`Repay shares (${v.toString()}) exceed current position borrowShares (${d.borrowShares.toString()}).`);b=v}else h=Me(t);let w=b>0n?await $e(o,u,c,r):void 0,k=b>0n?se(b,w.totalBorrowAssets,c.totalBorrowShares):h;if(p<k)throw new i(`Insufficient loan token balance for repayment: wallet holds ${p.toString()} base units, but ${k.toString()} base units are required (including accrued interest).`);let y=k.toString(),g=e.formatAmount(y,m.decimals),I=e.approval(u.loanToken,B,y,f),x=e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"repay",args:[u,h,b,l,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${g} ${m.symbol}) on Morpho market ${a}.`:`Repay ${g} ${m.symbol} (${h.toString()} base units) on Morpho market ${a}.`}),T=[I,x],P=await e.preview(T,n),{formattedChanges:C,formattedNetOutflows:L}=xe(e,P);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,repayAssets:h.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:r.toString()}:{},formattedRequiredAssets:g,onBehalf:l,txs:T,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${g} ${m.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${qe} seconds.`:`Repay ${g} ${m.symbol} on Morpho Blue market ${a}.`,preview:P,formattedChanges:C,formattedNetOutflows:L}}function Ka(e,t,s){if(t.repayAll!==!0)throw new i("Reviewed debt reconstruction requires repayAll.");return eo(e,t,s,0n)}async function _o(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.collateralToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(b<=0n||b>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${b.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let P=d.collateral-b,C=Ae(P,p,u.lltv),L=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(L>C)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${C.toString()} would fall below current debt ${L.toString()} base units.`)}let w=b.toString(),k=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdrawCollateral",args:[u,b,n,l]}),value:"0",description:`Withdraw ${k} ${m.symbol} (${w} base units) collateral from Morpho market ${a}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw_collateral",chainId:f,marketId:a,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:k,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${k} ${m.symbol} collateral from Morpho Blue market ${a}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function Ho(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:o,marketState:a}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&o.loanToken.toLowerCase()!==me.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let c=Me(t),m=c.toString(),[d,p]=await Promise.all([Q(n,o.loanToken,f),u?Promise.resolve(c):Zt(n,o.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let h=e.formatAmount(m,d.decimals),b=[];u&&b.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${h} ETH into WETH at ${me}.`})),b.push(e.approval(o.loanToken,B,m,f)),b.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supply",args:[o,c,0n,r,"0x"]}),value:"0",description:`Lend ${h} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Bo(c,a.totalSupplyAssets,a.totalSupplyShares),k=await e.preview(b,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(o),loanToken:d,assets:m,formattedAssets:h,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:b,summary:`${u?`Send ${h} ETH to wrap into WETH. `:""}Lend ${h} ${d.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:k,formattedChanges:y,formattedNetOutflows:g}}async function qo(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),l=W("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:o,marketParams:a,marketState:u}=await fe(n,t,!0),[c,m]=await Promise.all([Q(n,a.loanToken,f),Te(n,o,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${o}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),h=l?m.supplyShares:0n;if(!l&&p>d)throw new i(`Withdrawal exceeds the lent balance: requested ${p.toString()} base units, position holds about ${d.toString()}. Use withdrawAll for a full exit.`);let b=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>b)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${b.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let k=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdraw",args:[a,p,h,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${k} ${c.symbol}) from Morpho market ${o}.`:`Withdraw ${k} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${o}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw",chainId:f,marketId:o,marketParams:pe(a),loanToken:c,withdrawAssets:p.toString(),withdrawShares:h.toString(),estimatedAssets:w.toString(),formattedAssets:k,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${k}, including interest) from Morpho Blue market ${o}.`:`Withdraw ${k} lent ${c.symbol} from Morpho Blue market ${o}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function to(e,t,s){let r=await e.http(Io,{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 oo(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
@@ -10,9 +10,9 @@ import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Re}from"./7MR37ST
10
10
  }
11
11
  pageInfo { count countTotal }
12
12
  }
13
- }`;try{let r=(await ea(e,t,{chainId:f})).markets;if(!Array.isArray(r?.items)||typeof r.pageInfo?.countTotal!="number"||r.pageInfo.countTotal!==r.items.length||r.items.some(n=>!n||typeof n.marketId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n.marketId)))throw new i("Morpho GraphQL returned an incomplete or invalid market inventory.");return r.items}catch(s){throw new i(`Morpho GraphQL read failed: ${ie(s)}`)}}async function qa(e,t){return(await ta(e)).find(r=>r.marketId.toLowerCase()===t)??null}async function Fa(e,t){let r=await ea(e,`query Positions($chainId: Int!, $wallet: String!) {
13
+ }`;try{let r=(await to(e,t,{chainId:f})).markets;if(!Array.isArray(r?.items)||typeof r.pageInfo?.countTotal!="number"||r.pageInfo.countTotal!==r.items.length||r.items.some(n=>!n||typeof n.marketId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n.marketId)))throw new i("Morpho GraphQL returned an incomplete or invalid market inventory.");return r.items}catch(s){throw new i(`Morpho GraphQL read failed: ${ie(s)}`)}}async function Fo(e,t){return(await oo(e)).find(r=>r.marketId.toLowerCase()===t)??null}async function Vo(e,t){let r=await to(e,`query Positions($chainId: Int!, $wallet: String!) {
14
14
  marketPositions(first: 1000, where: { chainId_in: [$chainId], userAddress_in: [$wallet] }) {
15
15
  items { market { marketId } }
16
16
  pageInfo { countTotal }
17
17
  }
18
- }`,{chainId:f,wallet:t}),n=r.marketPositions?.items;if(!Array.isArray(n)||r.marketPositions?.pageInfo?.countTotal!==n.length)throw new i("Morpho GraphQL returned an incomplete wallet position list.");return n.map(l=>Qt(l.market?.marketId))}function Ft(e){let t=e;return!t||typeof t.address!="string"||!Fe(t.address,{strict:!1})?null:{address:L(t.address),symbol:Xt(t.symbol),decimals:typeof t.decimals=="number"?t.decimals:null}}function Vt(e){return typeof e=="string"&&Fe(e,{strict:!1})?L(e):null}function zt(e,t){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new i(`Morpho ${t} filter must be a token address or symbol.`);let s=e.trim().toLowerCase();return r=>!!r&&(String(r.address).toLowerCase()===s||typeof r.symbol=="string"&&r.symbol.toLowerCase()===s.replace(/^\$/,""))}async function Va(e,t){if(t.marketId!==void 0||t.marketParams!==void 0||t.includeGraphql!==void 0)throw new i("Use discover without marketId, marketParams or includeGraphql.");let s=t.limit===void 0?20:Number(t.limit);if(!Number.isSafeInteger(s)||s<1||s>100)throw new i("Morpho discover limit must be an integer from 1 to 100.");let r=zt(t.loanToken,"loanToken"),n=zt(t.collateralToken,"collateralToken"),l=W("verifiedOnly",t.verifiedOnly)===!0,a=await ta(e),o=a.map(c=>{let m=c.marketId.toLowerCase(),d=c.state??{},p=Ft(c.loanAsset),b=Ft(c.collateralAsset),h=Array.isArray(c.warnings)?c.warnings.map(w=>({type:String(w?.type??"").slice(0,64),level:String(w?.level??"").slice(0,16)})):[];return{marketId:m,listed:c.listed===!0,warnings:h,loanToken:p,collateralToken:b,lltv:typeof c.lltv=="string"||typeof c.lltv=="number"?String(c.lltv):null,oracle:Vt(c.oracle?.address),irm:Vt(c.irmAddress),state:{supplyAssets:d.supplyAssets===void 0?null:String(d.supplyAssets),borrowAssets:d.borrowAssets===void 0?null:String(d.borrowAssets),liquidityAssets:d.liquidityAssets===void 0?null:String(d.liquidityAssets),supplyApy:typeof d.supplyApy=="number"?d.supplyApy:null,borrowApy:typeof d.borrowApy=="number"?d.borrowApy:null},oak:ct(m)}}).filter(c=>(!l||c.oak.actions==="enabled")&&(!r||r(c.loanToken))&&(!n||n(c.collateralToken))),u=c=>{try{return BigInt(c.state.liquidityAssets??"0")}catch{return 0n}};return o.sort((c,m)=>{let d=+(m.oak.actions==="enabled")-+(c.oak.actions==="enabled");if(d)return d;let p=u(m)-u(c);return p>0n?1:p<0n?-1:0}),{chainId:f,morphoBlue:$,source:"Morpho API market inventory; token symbols, rates and liquidity are indexer data, not chain reads.",totalMatching:o.length,inventoryTotal:a.length,markets:o.slice(0,s),next:'Re-read a market with morpho_status {"marketId":"<id>"} before acting. Only oak.actions "enabled" markets accept Oak transactions.'}}async function za(e,t,s){let r=e.clientFor(f),n=s??t.wallet,l=n&&Fe(n,{strict:!1})?L(n):void 0;if(W("discover",t.discover)===!0)return Va(e,t);for(let c of["loanToken","collateralToken","verifiedOnly","limit"])if(t[c]!==void 0)throw new i(`Morpho ${c} is a discover filter; pass discover:true with it.`);let a=W("includeGraphql",t.includeGraphql)===!0,o=t.marketId||t.marketParams?[t]:Ta.map(c=>({marketId:c})),u=await Promise.all(o.map(async c=>{let{marketId:m,marketParams:d,marketState:p}=await fe(r,c),[b,h,w,y,k,g]=await Promise.all([Q(r,d.loanToken,f),Q(r,d.collateralToken,f),Ke(r,d.oracle),Be(r,d,p),l?Te(r,m,l):Promise.resolve(void 0),a?qa(e,m):Promise.resolve(void 0)]),T=p.totalSupplyAssets>p.totalBorrowAssets?p.totalSupplyAssets-p.totalBorrowAssets:0n,x;if(k){let M=k.borrowShares>0n?se(k.borrowShares,y.totalBorrowAssets,p.totalBorrowShares):0n,C=k.supplyShares>0n?ut(k.supplyShares,p.totalSupplyAssets,p.totalSupplyShares):0n,P=Ae(k.collateral,w,d.lltv),I=M>0n?e.formatAmount((P*Se/M).toString(),18):null;x={supplyShares:k.supplyShares.toString(),supplyAssets:C.toString(),borrowShares:k.borrowShares.toString(),borrowAssets:M.toString(),collateralAssets:k.collateral.toString(),maxBorrowAssets:P.toString(),healthFactor:I}}return{marketId:m,marketParams:pe(d),loanToken:b,collateralToken:h,state:{totalSupplyAssets:p.totalSupplyAssets.toString(),totalSupplyShares:p.totalSupplyShares.toString(),totalBorrowAssets:p.totalBorrowAssets.toString(),totalBorrowShares:p.totalBorrowShares.toString(),availableLiquidity:T.toString(),lastUpdate:p.lastUpdate.toString(),fee:p.fee.toString()},oraclePrice:w.toString(),borrowRatePerSecond:y.rate.toString(),oak:ct(m),...x?{position:x}:{},...a?{graphql:g??null}:{}}}));return{chainId:f,morphoBlue:$,adaptiveCurveIrm:xa,markets:u}}async function Wa(e,t,s,r){let[n,l]=await Promise.all([Yt(t,s),Jt(t,s)]),[a,o,u,c]=await Promise.all([Q(t,n.loanToken,f),Q(t,n.collateralToken,f),Ke(t,n.oracle),Be(t,n,l)]),m=[];r.collateral>0n&&m.push({token:o,amount:r.collateral.toString()});let d=r.supplyShares>0n?ut(r.supplyShares,l.totalSupplyAssets,l.totalSupplyShares):0n;d>0n&&m.push({token:a,amount:d.toString()});let p=r.borrowShares>0n?se(r.borrowShares,c.totalBorrowAssets,l.totalBorrowShares):0n,b=Ae(r.collateral,u,n.lltv),h=e.formatAmount(r.collateral.toString(),o.decimals),w=e.formatAmount(p.toString(),a.decimals);return{module:De,id:s,chainId:f,assets:m,economics:{principal:[...r.collateral>0n?[Je("collateral",{token:o,amount:r.collateral.toString(),source:"morpho.collateral"})]:[],...d>0n?[Je("redeemable",{token:a,amount:d.toString(),source:"morpho.supplyAssets"})]:[]],debt:p>0n?[St({token:a,amount:p.toString(),source:"morpho.borrowAssets"})]:[],rewards:[],backing:[],coverage:{complete:!0}},description:`Morpho Blue market ${s}: collateral=${h} ${o.symbol} (${r.collateral.toString()}), debt=${w} ${a.symbol} (${p.toString()}, shares=${r.borrowShares.toString()}), maxBorrow=${b.toString()}${r.supplyShares>0n?`, lent=${e.formatAmount(d.toString(),a.decimals)} ${a.symbol} (supplyShares=${r.supplyShares.toString()})`:""}.${j(s)?"":" Read-only: not in Oak's verified market registry, so Oak cannot build exits here."}`}}async function ja(e,t){q(t);let s=L(t),r=e.clientFor(f),n=[],l=new Set(lt.map(d=>d.marketId)),a;try{for(let d of await Fa(e,s))l.add(d)}catch(d){a=ie(d)}let o=[...l],u=[],c=[];if(typeof r.multicall=="function")try{let d=await r.multicall({multicallAddress:ft,batchSize:0,allowFailure:!0,contracts:o.map(p=>({address:$,abi:X,functionName:"position",args:[p,s]}))});if(d.length!==o.length)throw new i("Morpho multicall returned an incomplete position list.");d.forEach((p,b)=>{let h=o[b];if(p.status!=="success"){c.push({marketId:h,reason:ie(p.error)});return}let[w,y,k]=p.result;u.push({marketId:h,position:{supplyShares:w,borrowShares:y,collateral:k}})})}catch(d){c.push(...o.map(p=>({marketId:p,reason:ie(d)})))}else for(let d=0;d<o.length;d+=qt)u.push(...await Promise.all(o.slice(d,d+qt).map(async p=>({marketId:p,position:await Te(r,p,s).catch(b=>{c.push({marketId:p,reason:ie(b)})})}))));c.length&&n.push({module:De,id:"morpho-market-reads-incomplete",chainId:f,assets:[],incomplete:!0,description:`Morpho could not read ${c.length} of ${o.length} markets. ${[...new Set(c.map(d=>d.reason))].slice(0,3).join(" ")} Example market IDs: ${c.slice(0,3).map(d=>d.marketId).join(", ")}. Retry positions or check a known market with morpho_status {"marketId":"<id>"}; other readable markets are retained.`});let m=u.filter(d=>d.position!==void 0&&(d.position.supplyShares>0n||d.position.borrowShares>0n||d.position.collateral>0n));for(let{marketId:d,position:p}of m)try{n.push(await Wa(e,r,d,p))}catch(b){let h=j(d)!==void 0;n.push({module:De,id:d,chainId:f,assets:[],incomplete:!0,description:`Unreadable ${h?"verified":"unverified"} Morpho market ${d}: the wallet holds supplyShares=${p.supplyShares.toString()}, borrowShares=${p.borrowShares.toString()}, collateral=${p.collateral.toString()} base units, but its token or oracle reads failed (${ie(b)}). Retry morpho_status {"marketId":"${d}"}.${h?"":" Read-only in Oak."}`})}return a!==void 0&&n.push({module:De,id:"morpho-discovery-unavailable",incomplete:!0,chainId:f,assets:[],description:`Incomplete: Morpho API position discovery failed (${a}). Only Oak's ${lt.length} verified markets were checked on chain; check any other market with morpho_status {"marketId":"<id>"}.`}),n}var ce="Morpho Blue market id: 0x followed by 64 hex digits (bytes32). Provide this or marketParams.",ue="Market parameters object with loanToken, collateralToken, oracle, irm (addresses) and lltv (decimal string, 18 decimals). Provide this or marketId.",ge="Position owner address. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",st="Address receiving the tokens. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",oe=()=>`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,qe=`Amount of the market's collateral token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,Ka=e=>({tools:[{name:"morpho_supply_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(qe),amount:A(qe),collateralToken:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$",description:"Optional collateral token address (0x + 40 hex); must match the market collateral token, or be the native ETH sentinel to wrap."},wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the token supplied is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Oa(e,s,r)},{name:"morpho_withdraw_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(qe),amount:A(qe),withdrawAll:{type:"boolean",description:"true withdraws the full collateral balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ra(e,s,r)},{name:"morpho_borrow",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ea(e,s,r)},{name:"morpho_repay",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),shares:A("Borrow shares to repay, in share base units exactly as your position reports them (not loan-token units). Use instead of assets or amount."),repayAll:{type:"boolean",description:"true repays the entire debt; do not combine with assets, amount or shares."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Ga(e,s,r)},{name:"morpho_supply",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the market loan token is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>_a(e,s,r)},{name:"morpho_withdraw",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),withdrawAll:{type:"boolean",description:"true withdraws the full supplied balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ha(e,s,r)},{name:"morpho_status",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},includeGraphql:{type:"boolean",description:"true also fetches Morpho API (GraphQL) market data alongside on-chain reads."},discover:{type:"boolean",description:"List the Morpho API market inventory with Oak action eligibility instead of reading markets on chain."},loanToken:{type:"string",description:"discover filter: loan token address or symbol."},collateralToken:{type:"string",description:"discover filter: collateral token address or symbol."},verifiedOnly:{type:"boolean",description:"discover filter: only markets Oak can act on."},limit:{type:"integer",minimum:1,maximum:100,description:"discover page size, default 20."}}},execute:(s,r)=>za(e,s,r)}].map(s=>{let r=new Set(Object.keys(s.inputSchema.properties));if(r.add("wallet"),s.name!=="morpho_status")for(let l of["onBehalf","receiver","data"])r.add(l);let n=new Set(["loanToken","collateralToken","oracle","irm","lltv"]);return{...s,execute:async(l,a)=>{for(let o of Object.keys(l))if(!r.has(o))throw new i(`Unknown argument ${Ye(o)} for ${s.name}; remove it and retry.`);if(l.marketParams&&typeof l.marketParams=="object"){for(let o of Object.keys(l.marketParams))if(!n.has(o))throw new i(`Unknown Morpho marketParams field ${Ye(o)}; remove it and retry.`)}return s.execute(l,a)}}}),positions:s=>ja(e,s)}),Ko=e=>bt(De,[Ka(e),Tt(e),Wt(e),Ht(e),$t(e)]);var _=z[f].morpho.morpho_blue.address,Pe="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",O=pt(["function owner() view returns (address)","function feeRecipient() view returns (address)","function isIrmEnabled(address) view returns (bool)","function isLltvEnabled(uint256) view returns (bool)","function isAuthorized(address,address) view returns (bool)","function nonce(address) view returns (uint256)",`function idToMarketParams(bytes32) view returns ${Pe}`,"function market(bytes32) view returns (uint128,uint128,uint128,uint128,uint128,uint128)","function position(bytes32,address) view returns (uint256 supplyShares,uint128 borrowShares,uint128 collateral)",`function createMarket(${Pe} marketParams)`,`function accrueInterest(${Pe} marketParams)`,`function setFee(${Pe} marketParams,uint256 newFee)`,"function setAuthorization(address authorized,bool newIsAuthorized)","function setOwner(address newOwner)","function setFeeRecipient(address newFeeRecipient)","function enableIrm(address irm)","function enableLltv(uint256 lltv)",`function liquidate(${Pe} marketParams,address borrower,uint256 seizedAssets,uint256 repaidShares,bytes data) returns (uint256,uint256)`]),Ya=pt(["function price() view returns (uint256)"]),Ja=pt([`function borrowRateView(${Pe} marketParams,(uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee) market) view returns (uint256)`]),oa=["createMarket","accrueInterest","setAuthorization","setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"],Za=new Set(["setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"]);function Ne(e){if(typeof e!="string"||!/^\d+$/.test(e)||e.length>78||BigInt(e)>=1n<<256n)throw new i("Provide a uint256 decimal base-unit string.");return BigInt(e)}function mt(e){return Ee(e,"Provide an explicit account address.",Oe)}var Wt=e=>{async function t(){let n=e.clientFor(f);if(await n.getChainId()!==f)throw new i("Morpho protocol tools require chain 4663.");return n}async function s(n){if(typeof n!="string"||!j(n))throw new i("Choose a market in Oak\u2019s verified registry.");let l=await t(),a=await l.readContract({address:_,abi:O,functionName:"idToMarketParams",args:[n]}),o={loanToken:a[0],collateralToken:a[1],oracle:a[2],irm:a[3],lltv:a[4]};if(!R(ke({...o,lltv:o.lltv.toString()}),n))throw new i("On-chain Morpho parameters do not match the selected market.");return{rpc:l,params:o,marketId:n}}let r=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Morpho protocol argument.");return await o(u,c)}catch(m){throw new i(e.plainError(m))}}});return{tools:[r("morpho_protocol",{authorized:{type:"string",description:"Optional address to check whether it is authorized to manage the Oak wallet's Morpho positions."}},[],async(n,l)=>{let a=await t(),[o,u,c]=await Promise.all([a.readContract({address:_,abi:O,functionName:"owner"}),a.readContract({address:_,abi:O,functionName:"feeRecipient"}),a.readContract({address:_,abi:O,functionName:"nonce",args:[l]})]),m=n.authorized===void 0?void 0:mt(n.authorized);return{chainId:f,morpho:_,owner:o,feeRecipient:u,nonce:c.toString(),...m?{authorized:m,isAuthorized:await a.readContract({address:_,abi:O,functionName:"isAuthorized",args:[l,m]})}:{}}}),r("morpho_manage",{operation:{enum:oa,description:"Protocol action: createMarket, accrueInterest, setAuthorization, setOwner, setFeeRecipient, enableIrm, enableLltv or setFee. Owner-only except accrueInterest, setAuthorization and createMarket."},marketId:{type:"string",description:"Verified market id (0x + 64 hex digits). Used by accrueInterest and setFee."},marketParams:{type:"object",description:"For createMarket only: loanToken, collateralToken, oracle, irm addresses and lltv as a decimal string (18 decimals)."},account:{type:"string",description:"Address argument: authorized account for setAuthorization, new owner, new fee recipient, or IRM to enable."},enabled:{type:"boolean",description:"For setAuthorization: true grants the account control of all your Morpho positions, false revokes it."},value:A("18-decimal wad in base units: for setFee the fee (max 0.25e18 = 25 percent), for enableLltv the LLTV (below 1e18; 0.8e18 = 80 percent).")},["operation"],async(n,l)=>{if(typeof n.operation!="string"||!oa.includes(n.operation))throw new i("Choose a documented Morpho protocol operation.");let a=n.operation,o=await t(),u=a==="createMarket"?["operation","marketParams"]:a==="accrueInterest"?["operation","marketId"]:a==="setFee"?["operation","marketId","value"]:a==="enableLltv"?["operation","value"]:a==="setAuthorization"?["operation","account","enabled"]:["operation","account"];if(Object.keys(n).some(p=>!u.includes(p)))throw new i("Unexpected fields for this Morpho operation.");if(Za.has(a)){let p=await o.readContract({address:_,abi:O,functionName:"owner"});if(aa(p)!==aa(l))throw new i("This wallet does not hold the Morpho owner role.")}let c;if(a==="createMarket"){if(!n.marketParams||typeof n.marketParams!="object"||Array.isArray(n.marketParams)||Object.keys(n.marketParams).some(w=>!["loanToken","collateralToken","oracle","irm","lltv"].includes(w)))throw new i("Provide only the five documented market parameter fields.");let p=je(n.marketParams),[b,h]=await Promise.all([o.readContract({address:_,abi:O,functionName:"isIrmEnabled",args:[p.irm]}),o.readContract({address:_,abi:O,functionName:"isLltvEnabled",args:[p.lltv]})]);if(!b||!h)throw new i("The new market\u2019s IRM and LLTV must first be enabled by the Morpho owner.");c=be({abi:O,functionName:"createMarket",args:[p]})}else if(a==="accrueInterest"||a==="setFee"){let{params:p}=await s(n.marketId);if(a==="setFee"){let b=Ne(n.value);if(b>250000000000000000n)throw new i("Morpho market fee cannot exceed 25% (0.25e18).");c=be({abi:O,functionName:"setFee",args:[p,b]})}else c=be({abi:O,functionName:"accrueInterest",args:[p]})}else if(a==="enableLltv"){let p=Ne(n.value);if(p>=10n**18n)throw new i("Morpho LLTV must be below 1e18.");c=be({abi:O,functionName:"enableLltv",args:[p]})}else{let p=mt(n.account);if(a==="setAuthorization"){if(typeof n.enabled!="boolean")throw new i("Provide enabled as a boolean.");c=be({abi:O,functionName:"setAuthorization",args:[p,n.enabled]})}else if(a==="setOwner"||a==="enableIrm"||a==="setFeeRecipient")c=be({abi:O,functionName:a,args:[p]});else throw new i("Unsupported Morpho operation.")}let m=`Morpho ${a}: ${JSON.stringify(n)}. ${a==="setAuthorization"&&n.enabled?"This account can manage all your Morpho positions, including borrowing and withdrawals. There is no amount cap.":""}${a==="setOwner"&&n.account===Xa?"Setting the owner to zero permanently relinquishes protocol administration.":""}${a==="createMarket"?"New market creation does not add it to Oak\u2019s verified action registry.":""}`,d=[e.unsignedTx({to:_,data:c,value:"0",chainId:f,description:m})];return{txs:d,preview:await e.preview(d,l),summary:m}}),r("morpho_liquidate",{marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits) holding the unhealthy position."},borrower:{type:"string",description:"Address of the unhealthy borrower to liquidate."},repaidShares:A("Borrow shares to repay, in share base units (read the borrower position); cannot exceed their debt shares."),maxAssets:A('Most loan token you will pay, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minCollateral:A("Least collateral you must receive, in collateral token units (base units, read its decimals); checked in simulation only.")},["marketId","borrower","repaidShares","maxAssets","minCollateral"],async(n,l)=>{let{rpc:a,params:o,marketId:u}=await s(n.marketId),c=mt(n.borrower),m=Ne(n.repaidShares),d=Ne(n.maxAssets),p=Ne(n.minCollateral),[b,h,w,y]=await Promise.all([a.readContract({address:_,abi:O,functionName:"market",args:[u]}),a.readContract({address:_,abi:O,functionName:"position",args:[u,c]}),a.readContract({address:o.oracle,abi:Ya,functionName:"price"}),a.getBlock()]);if(m===0n||m>h[1]||w===0n)throw new i("Liquidation shares must fit the current debt and the oracle must be valid.");let k={totalSupplyAssets:b[0],totalSupplyShares:b[1],totalBorrowAssets:b[2],totalBorrowShares:b[3],lastUpdate:b[4],fee:b[5]},g=await a.readContract({address:o.irm,abi:Ja,functionName:"borrowRateView",args:[o,k]}),T=Qe(k,g,y.timestamp);if(se(h[1],T,b[3])<=Ae(h[2],w,o.lltv))throw new i("This borrower is healthy; liquidation is unavailable.");let x=se(m,Qe(k,g,y.timestamp+120n),b[3]);if(x>d)throw new i("Liquidation funding exceeds maxAssets.");if(await a.readContract({address:o.loanToken,abi:Qa,functionName:"balanceOf",args:[l]})<x)throw new i("Top up the loan token before liquidating.");let C=`Liquidate ${m} debt shares of ${c} on ${u}; exact approval ${x} loan-token base units; preview minimum ${p} collateral units. No callbacks; the wallet funds repayment. Approval can leave interest-buffer dust; revoke it afterward.`,P=[e.approval(o.loanToken,_,x.toString(),f),e.unsignedTx({to:_,data:be({abi:O,functionName:"liquidate",args:[o,c,0n,m,"0x"]}),value:"0",chainId:f,description:C})],I=await e.preview(P,l),E=Z=>I.changes.filter(H=>H.token.chainId===f&&R(H.token.address,Z)).reduce((H,F)=>H+BigInt(F.amount),0n);if(-E(o.loanToken)<=0n||-E(o.loanToken)>x||E(o.collateralToken)<p||E(o.collateralToken)<=0n)throw new i("Liquidation preview does not match the funding limit and collateral minimum.");return{txs:P,preview:I,requiredAssets:x.toString(),summary:`${C} MinCollateral is a local simulation check, not an on-chain floor.`}})]}};export{O as a,Wt as b,we as c,$t as d,Y as e,ha as f,Ot as g,wa as h,Et as i,ka as j,Ht as k,De as l,Aa as m,$ as n,xa as o,Ia as p,me as q,Ta as r,Ma as s,lt as t,j as u,Ue as v,Ua as w,$a as x,ut as y,se as z,Ae as A,Ba as B,je as C,ke as D,Xt as E,Qe as F,Ka as G,Ko as H,et as I,vt as J,N as K,io as L};
18
+ }`,{chainId:f,wallet:t}),n=r.marketPositions?.items;if(!Array.isArray(n)||r.marketPositions?.pageInfo?.countTotal!==n.length)throw new i("Morpho GraphQL returned an incomplete wallet position list.");return n.map(l=>Qt(l.market?.marketId))}function Ft(e){let t=e;return!t||typeof t.address!="string"||!Fe(t.address,{strict:!1})?null:{address:D(t.address),symbol:Xt(t.symbol),decimals:typeof t.decimals=="number"?t.decimals:null}}function Vt(e){return typeof e=="string"&&Fe(e,{strict:!1})?D(e):null}function zt(e,t){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new i(`Morpho ${t} filter must be a token address or symbol.`);let s=e.trim().toLowerCase();return r=>!!r&&(String(r.address).toLowerCase()===s||typeof r.symbol=="string"&&r.symbol.toLowerCase()===s.replace(/^\$/,""))}async function zo(e,t){if(t.marketId!==void 0||t.marketParams!==void 0||t.includeGraphql!==void 0)throw new i("Use discover without marketId, marketParams or includeGraphql.");let s=t.limit===void 0?20:Number(t.limit);if(!Number.isSafeInteger(s)||s<1||s>100)throw new i("Morpho discover limit must be an integer from 1 to 100.");let r=zt(t.loanToken,"loanToken"),n=zt(t.collateralToken,"collateralToken"),l=W("verifiedOnly",t.verifiedOnly)===!0,o=await oo(e),a=o.map(c=>{let m=c.marketId.toLowerCase(),d=c.state??{},p=Ft(c.loanAsset),h=Ft(c.collateralAsset),b=Array.isArray(c.warnings)?c.warnings.map(w=>({type:String(w?.type??"").slice(0,64),level:String(w?.level??"").slice(0,16)})):[];return{marketId:m,listed:c.listed===!0,warnings:b,loanToken:p,collateralToken:h,lltv:typeof c.lltv=="string"||typeof c.lltv=="number"?String(c.lltv):null,oracle:Vt(c.oracle?.address),irm:Vt(c.irmAddress),state:{supplyAssets:d.supplyAssets===void 0?null:String(d.supplyAssets),borrowAssets:d.borrowAssets===void 0?null:String(d.borrowAssets),liquidityAssets:d.liquidityAssets===void 0?null:String(d.liquidityAssets),supplyApy:typeof d.supplyApy=="number"?d.supplyApy:null,borrowApy:typeof d.borrowApy=="number"?d.borrowApy:null},oak:ct(m)}}).filter(c=>(!l||c.oak.actions==="enabled")&&(!r||r(c.loanToken))&&(!n||n(c.collateralToken))),u=c=>{try{return BigInt(c.state.liquidityAssets??"0")}catch{return 0n}};return a.sort((c,m)=>{let d=+(m.oak.actions==="enabled")-+(c.oak.actions==="enabled");if(d)return d;let p=u(m)-u(c);return p>0n?1:p<0n?-1:0}),{chainId:f,morphoBlue:B,source:"Morpho API market inventory; token symbols, rates and liquidity are indexer data, not chain reads.",totalMatching:a.length,inventoryTotal:o.length,markets:a.slice(0,s),next:'Re-read a market with morpho_status {"marketId":"<id>"} before acting. Only oak.actions "enabled" markets accept Oak transactions.'}}async function Wo(e,t,s){let r=e.clientFor(f),n=s??t.wallet,l=n&&Fe(n,{strict:!1})?D(n):void 0;if(W("discover",t.discover)===!0)return zo(e,t);for(let c of["loanToken","collateralToken","verifiedOnly","limit"])if(t[c]!==void 0)throw new i(`Morpho ${c} is a discover filter; pass discover:true with it.`);let o=W("includeGraphql",t.includeGraphql)===!0,a=t.marketId||t.marketParams?[t]:vo.map(c=>({marketId:c})),u=await Promise.all(a.map(async c=>{let{marketId:m,marketParams:d,marketState:p}=await fe(r,c),[h,b,w,k,y,g]=await Promise.all([Q(r,d.loanToken,f),Q(r,d.collateralToken,f),Ke(r,d.oracle),$e(r,d,p),l?Te(r,m,l):Promise.resolve(void 0),o?Fo(e,m):Promise.resolve(void 0)]),I=p.totalSupplyAssets>p.totalBorrowAssets?p.totalSupplyAssets-p.totalBorrowAssets:0n,x;if(y){let T=y.borrowShares>0n?se(y.borrowShares,k.totalBorrowAssets,p.totalBorrowShares):0n,P=y.supplyShares>0n?ut(y.supplyShares,p.totalSupplyAssets,p.totalSupplyShares):0n,C=Ae(y.collateral,w,d.lltv),L=T>0n?e.formatAmount((C*Se/T).toString(),18):null;x={supplyShares:y.supplyShares.toString(),supplyAssets:P.toString(),borrowShares:y.borrowShares.toString(),borrowAssets:T.toString(),collateralAssets:y.collateral.toString(),maxBorrowAssets:C.toString(),healthFactor:L}}return{marketId:m,marketParams:pe(d),loanToken:h,collateralToken:b,state:{totalSupplyAssets:p.totalSupplyAssets.toString(),totalSupplyShares:p.totalSupplyShares.toString(),totalBorrowAssets:p.totalBorrowAssets.toString(),totalBorrowShares:p.totalBorrowShares.toString(),availableLiquidity:I.toString(),lastUpdate:p.lastUpdate.toString(),fee:p.fee.toString()},oraclePrice:w.toString(),borrowRatePerSecond:k.rate.toString(),oak:ct(m),...x?{position:x}:{},...o?{graphql:g??null}:{}}}));return{chainId:f,morphoBlue:B,adaptiveCurveIrm:To,markets:u}}async function jo(e,t,s,r){let[n,l]=await Promise.all([Yt(t,s),Jt(t,s)]),[o,a,u,c]=await Promise.all([Q(t,n.loanToken,f),Q(t,n.collateralToken,f),Ke(t,n.oracle),$e(t,n,l)]),m=[];r.collateral>0n&&m.push({token:a,amount:r.collateral.toString()});let d=r.supplyShares>0n?ut(r.supplyShares,l.totalSupplyAssets,l.totalSupplyShares):0n;d>0n&&m.push({token:o,amount:d.toString()});let p=r.borrowShares>0n?se(r.borrowShares,c.totalBorrowAssets,l.totalBorrowShares):0n,h=Ae(r.collateral,u,n.lltv),b=e.formatAmount(r.collateral.toString(),a.decimals),w=e.formatAmount(p.toString(),o.decimals);return{module:De,id:s,chainId:f,assets:m,economics:{principal:[...r.collateral>0n?[Je("collateral",{token:a,amount:r.collateral.toString(),source:"morpho.collateral"})]:[],...d>0n?[Je("redeemable",{token:o,amount:d.toString(),source:"morpho.supplyAssets"})]:[]],debt:p>0n?[St({token:o,amount:p.toString(),source:"morpho.borrowAssets"})]:[],rewards:[],backing:[],coverage:{complete:!0}},description:`Morpho Blue market ${s}: collateral=${b} ${a.symbol} (${r.collateral.toString()}), debt=${w} ${o.symbol} (${p.toString()}, shares=${r.borrowShares.toString()}), maxBorrow=${h.toString()}${r.supplyShares>0n?`, lent=${e.formatAmount(d.toString(),o.decimals)} ${o.symbol} (supplyShares=${r.supplyShares.toString()})`:""}.${j(s)?"":" Read-only: not in Oak's verified market registry, so Oak cannot build exits here."}`}}async function Ko(e,t){q(t);let s=D(t),r=e.clientFor(f),n=[],l=new Set(lt.map(d=>d.marketId)),o;try{for(let d of await Vo(e,s))l.add(d)}catch(d){o=ie(d)}let a=[...l],u=[],c=[];if(typeof r.multicall=="function")try{let d=await r.multicall({multicallAddress:ft,batchSize:0,allowFailure:!0,contracts:a.map(p=>({address:B,abi:X,functionName:"position",args:[p,s]}))});if(d.length!==a.length)throw new i("Morpho multicall returned an incomplete position list.");d.forEach((p,h)=>{let b=a[h];if(p.status!=="success"){c.push({marketId:b,reason:ie(p.error)});return}let[w,k,y]=p.result;u.push({marketId:b,position:{supplyShares:w,borrowShares:k,collateral:y}})})}catch(d){c.push(...a.map(p=>({marketId:p,reason:ie(d)})))}else for(let d=0;d<a.length;d+=qt)u.push(...await Promise.all(a.slice(d,d+qt).map(async p=>({marketId:p,position:await Te(r,p,s).catch(h=>{c.push({marketId:p,reason:ie(h)})})}))));c.length&&n.push({module:De,id:"morpho-market-reads-incomplete",chainId:f,assets:[],incomplete:!0,description:`Morpho could not read ${c.length} of ${a.length} markets. ${[...new Set(c.map(d=>d.reason))].slice(0,3).join(" ")} Example market IDs: ${c.slice(0,3).map(d=>d.marketId).join(", ")}. Retry positions or check a known market with morpho_status {"marketId":"<id>"}; other readable markets are retained.`});let m=u.filter(d=>d.position!==void 0&&(d.position.supplyShares>0n||d.position.borrowShares>0n||d.position.collateral>0n));for(let{marketId:d,position:p}of m)try{n.push(await jo(e,r,d,p))}catch(h){let b=j(d)!==void 0;n.push({module:De,id:d,chainId:f,assets:[],incomplete:!0,description:`Unreadable ${b?"verified":"unverified"} Morpho market ${d}: the wallet holds supplyShares=${p.supplyShares.toString()}, borrowShares=${p.borrowShares.toString()}, collateral=${p.collateral.toString()} base units, but its token or oracle reads failed (${ie(h)}). Retry morpho_status {"marketId":"${d}"}.${b?"":" Read-only in Oak."}`})}return o!==void 0&&n.push({module:De,id:"morpho-discovery-unavailable",incomplete:!0,chainId:f,assets:[],description:`Incomplete: Morpho API position discovery failed (${o}). Only Oak's ${lt.length} verified markets were checked on chain; check any other market with morpho_status {"marketId":"<id>"}.`}),n}var ce="Morpho Blue market id: 0x followed by 64 hex digits (bytes32). Provide this or marketParams.",ue="Market parameters object with loanToken, collateralToken, oracle, irm (addresses) and lltv (decimal string, 18 decimals). Provide this or marketId.",ge="Position owner address. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",st="Address receiving the tokens. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",ae=()=>`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,He=`Amount of the market's collateral token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,Qo=e=>({tools:[{name:"morpho_supply_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(He),amount:A(He),collateralToken:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$",description:"Optional collateral token address (0x + 40 hex); must match the market collateral token, or be the native ETH sentinel to wrap."},wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the token supplied is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Go(e,s,r)},{name:"morpho_withdraw_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(He),amount:A(He),withdrawAll:{type:"boolean",description:"true withdraws the full collateral balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>_o(e,s,r)},{name:"morpho_borrow",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ro(e,s,r)},{name:"morpho_repay",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),shares:A("Borrow shares to repay, in share base units exactly as your position reports them (not loan-token units). Use instead of assets or amount."),repayAll:{type:"boolean",description:"true repays the entire debt; do not combine with assets, amount or shares."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>eo(e,s,r)},{name:"morpho_supply",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the market loan token is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Ho(e,s,r)},{name:"morpho_withdraw",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),withdrawAll:{type:"boolean",description:"true withdraws the full supplied balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>qo(e,s,r)},{name:"morpho_status",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},includeGraphql:{type:"boolean",description:"true also fetches Morpho API (GraphQL) market data alongside on-chain reads."},discover:{type:"boolean",description:"List the Morpho API market inventory with Oak action eligibility instead of reading markets on chain."},loanToken:{type:"string",description:"discover filter: loan token address or symbol."},collateralToken:{type:"string",description:"discover filter: collateral token address or symbol."},verifiedOnly:{type:"boolean",description:"discover filter: only markets Oak can act on."},limit:{type:"integer",minimum:1,maximum:100,description:"discover page size, default 20."}}},execute:(s,r)=>Wo(e,s,r)}].map(s=>{let r=new Set(Object.keys(s.inputSchema.properties));if(r.add("wallet"),s.name!=="morpho_status")for(let l of["onBehalf","receiver","data"])r.add(l);let n=new Set(["loanToken","collateralToken","oracle","irm","lltv"]);return{...s,execute:async(l,o)=>{for(let a of Object.keys(l))if(!r.has(a))throw new i(`Unknown argument ${Ye(a)} for ${s.name}; remove it and retry.`);if(l.marketParams&&typeof l.marketParams=="object"){for(let a of Object.keys(l.marketParams))if(!n.has(a))throw new i(`Unknown Morpho marketParams field ${Ye(a)}; remove it and retry.`)}return s.execute(l,o)}}}),positions:s=>Ko(e,s)}),Qa=e=>bt(De,[Qo(e),Tt(e),Wt(e),Ht(e),$t(e)]);var _=z[f].morpho.morpho_blue.address,Pe="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",E=pt(["function owner() view returns (address)","function feeRecipient() view returns (address)","function isIrmEnabled(address) view returns (bool)","function isLltvEnabled(uint256) view returns (bool)","function isAuthorized(address,address) view returns (bool)","function nonce(address) view returns (uint256)",`function idToMarketParams(bytes32) view returns ${Pe}`,"function market(bytes32) view returns (uint128,uint128,uint128,uint128,uint128,uint128)","function position(bytes32,address) view returns (uint256 supplyShares,uint128 borrowShares,uint128 collateral)",`function createMarket(${Pe} marketParams)`,`function accrueInterest(${Pe} marketParams)`,`function setFee(${Pe} marketParams,uint256 newFee)`,"function setAuthorization(address authorized,bool newIsAuthorized)","function setOwner(address newOwner)","function setFeeRecipient(address newFeeRecipient)","function enableIrm(address irm)","function enableLltv(uint256 lltv)",`function liquidate(${Pe} marketParams,address borrower,uint256 seizedAssets,uint256 repaidShares,bytes data) returns (uint256,uint256)`]),Jo=pt(["function price() view returns (uint256)"]),Zo=pt([`function borrowRateView(${Pe} marketParams,(uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee) market) view returns (uint256)`]),ro=["createMarket","accrueInterest","setAuthorization","setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"],ea=new Set(["setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"]);function Be(e){if(typeof e!="string"||!/^\d+$/.test(e)||e.length>78||BigInt(e)>=1n<<256n)throw new i("Provide a uint256 decimal base-unit string.");return BigInt(e)}function mt(e){return Oe(e,"Provide an explicit account address.",Ne)}var Wt=e=>{async function t(){let n=e.clientFor(f);if(await n.getChainId()!==f)throw new i("Morpho protocol tools require chain 4663.");return n}async function s(n){if(typeof n!="string"||!j(n))throw new i("Choose a market in Oak\u2019s verified registry.");let l=await t(),o=await l.readContract({address:_,abi:E,functionName:"idToMarketParams",args:[n]}),a={loanToken:o[0],collateralToken:o[1],oracle:o[2],irm:o[3],lltv:o[4]};if(!R(ke({...a,lltv:a.lltv.toString()}),n))throw new i("On-chain Morpho parameters do not match the selected market.");return{rpc:l,params:a,marketId:n}}let r=(n,l,o,a)=>({name:n,inputSchema:{type:"object",properties:l,required:o,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Morpho protocol argument.");return await a(u,c)}catch(m){throw new i(e.plainError(m))}}});return{tools:[r("morpho_protocol",{authorized:{type:"string",description:"Optional address to check whether it is authorized to manage the Oak wallet's Morpho positions."}},[],async(n,l)=>{let o=await t(),[a,u,c]=await Promise.all([o.readContract({address:_,abi:E,functionName:"owner"}),o.readContract({address:_,abi:E,functionName:"feeRecipient"}),o.readContract({address:_,abi:E,functionName:"nonce",args:[l]})]),m=n.authorized===void 0?void 0:mt(n.authorized);return{chainId:f,morpho:_,owner:a,feeRecipient:u,nonce:c.toString(),...m?{authorized:m,isAuthorized:await o.readContract({address:_,abi:E,functionName:"isAuthorized",args:[l,m]})}:{}}}),r("morpho_manage",{operation:{enum:ro,description:"Protocol action: createMarket, accrueInterest, setAuthorization, setOwner, setFeeRecipient, enableIrm, enableLltv or setFee. Owner-only except accrueInterest, setAuthorization and createMarket."},marketId:{type:"string",description:"Verified market id (0x + 64 hex digits). Used by accrueInterest and setFee."},marketParams:{type:"object",description:"For createMarket only: loanToken, collateralToken, oracle, irm addresses and lltv as a decimal string (18 decimals)."},account:{type:"string",description:"Address argument: authorized account for setAuthorization, new owner, new fee recipient, or IRM to enable."},enabled:{type:"boolean",description:"For setAuthorization: true grants the account control of all your Morpho positions, false revokes it."},value:A("18-decimal wad in base units: for setFee the fee (max 0.25e18 = 25 percent), for enableLltv the LLTV (below 1e18; 0.8e18 = 80 percent).")},["operation"],async(n,l)=>{if(typeof n.operation!="string"||!ro.includes(n.operation))throw new i("Choose a documented Morpho protocol operation.");let o=n.operation,a=await t(),u=o==="createMarket"?["operation","marketParams"]:o==="accrueInterest"?["operation","marketId"]:o==="setFee"?["operation","marketId","value"]:o==="enableLltv"?["operation","value"]:o==="setAuthorization"?["operation","account","enabled"]:["operation","account"];if(Object.keys(n).some(p=>!u.includes(p)))throw new i("Unexpected fields for this Morpho operation.");if(ea.has(o)){let p=await a.readContract({address:_,abi:E,functionName:"owner"});if(ao(p)!==ao(l))throw new i("This wallet does not hold the Morpho owner role.")}let c;if(o==="createMarket"){if(!n.marketParams||typeof n.marketParams!="object"||Array.isArray(n.marketParams)||Object.keys(n.marketParams).some(w=>!["loanToken","collateralToken","oracle","irm","lltv"].includes(w)))throw new i("Provide only the five documented market parameter fields.");let p=je(n.marketParams),[h,b]=await Promise.all([a.readContract({address:_,abi:E,functionName:"isIrmEnabled",args:[p.irm]}),a.readContract({address:_,abi:E,functionName:"isLltvEnabled",args:[p.lltv]})]);if(!h||!b)throw new i("The new market\u2019s IRM and LLTV must first be enabled by the Morpho owner.");c=be({abi:E,functionName:"createMarket",args:[p]})}else if(o==="accrueInterest"||o==="setFee"){let{params:p}=await s(n.marketId);if(o==="setFee"){let h=Be(n.value);if(h>250000000000000000n)throw new i("Morpho market fee cannot exceed 25% (0.25e18).");c=be({abi:E,functionName:"setFee",args:[p,h]})}else c=be({abi:E,functionName:"accrueInterest",args:[p]})}else if(o==="enableLltv"){let p=Be(n.value);if(p>=10n**18n)throw new i("Morpho LLTV must be below 1e18.");c=be({abi:E,functionName:"enableLltv",args:[p]})}else{let p=mt(n.account);if(o==="setAuthorization"){if(typeof n.enabled!="boolean")throw new i("Provide enabled as a boolean.");c=be({abi:E,functionName:"setAuthorization",args:[p,n.enabled]})}else if(o==="setOwner"||o==="enableIrm"||o==="setFeeRecipient")c=be({abi:E,functionName:o,args:[p]});else throw new i("Unsupported Morpho operation.")}let m=`Morpho ${o}: ${JSON.stringify(n)}. ${o==="setAuthorization"&&n.enabled?"This account can manage all your Morpho positions, including borrowing and withdrawals. There is no amount cap.":""}${o==="setOwner"&&n.account===Yo?"Setting the owner to zero permanently relinquishes protocol administration.":""}${o==="createMarket"?"New market creation does not add it to Oak\u2019s verified action registry.":""}`,d=[e.unsignedTx({to:_,data:c,value:"0",chainId:f,description:m})];return{txs:d,preview:await e.preview(d,l),summary:m}}),r("morpho_liquidate",{marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits) holding the unhealthy position."},borrower:{type:"string",description:"Address of the unhealthy borrower to liquidate."},repaidShares:A("Borrow shares to repay, in share base units (read the borrower position); cannot exceed their debt shares."),maxAssets:A('Most loan token you will pay, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minCollateral:A("Least collateral you must receive, in collateral token units (base units, read its decimals); checked in simulation only.")},["marketId","borrower","repaidShares","maxAssets","minCollateral"],async(n,l)=>{let{rpc:o,params:a,marketId:u}=await s(n.marketId),c=mt(n.borrower),m=Be(n.repaidShares),d=Be(n.maxAssets),p=Be(n.minCollateral),[h,b,w,k]=await Promise.all([o.readContract({address:_,abi:E,functionName:"market",args:[u]}),o.readContract({address:_,abi:E,functionName:"position",args:[u,c]}),o.readContract({address:a.oracle,abi:Jo,functionName:"price"}),o.getBlock()]);if(m===0n||m>b[1]||w===0n)throw new i("Liquidation shares must fit the current debt and the oracle must be valid.");let y={totalSupplyAssets:h[0],totalSupplyShares:h[1],totalBorrowAssets:h[2],totalBorrowShares:h[3],lastUpdate:h[4],fee:h[5]},g=await o.readContract({address:a.irm,abi:Zo,functionName:"borrowRateView",args:[a,y]}),I=Qe(y,g,k.timestamp);if(se(b[1],I,h[3])<=Ae(b[2],w,a.lltv))throw new i("This borrower is healthy; liquidation is unavailable.");let x=se(m,Qe(y,g,k.timestamp+120n),h[3]);if(x>d)throw new i("Liquidation funding exceeds maxAssets.");if(await o.readContract({address:a.loanToken,abi:Xo,functionName:"balanceOf",args:[l]})<x)throw new i("Top up the loan token before liquidating.");let P=`Liquidate ${m} debt shares of ${c} on ${u}; exact approval ${x} loan-token base units; preview minimum ${p} collateral units. No callbacks; the wallet funds repayment. Approval can leave interest-buffer dust; revoke it afterward.`,C=[e.approval(a.loanToken,_,x.toString(),f),e.unsignedTx({to:_,data:be({abi:E,functionName:"liquidate",args:[a,c,0n,m,"0x"]}),value:"0",chainId:f,description:P})],L=await e.preview(C,l),v=Z=>L.changes.filter(H=>H.token.chainId===f&&R(H.token.address,Z)).reduce((H,F)=>H+BigInt(F.amount),0n);if(-v(a.loanToken)<=0n||-v(a.loanToken)>x||v(a.collateralToken)<p||v(a.collateralToken)<=0n)throw new i("Liquidation preview does not match the funding limit and collateral minimum.");return{txs:C,preview:L,requiredAssets:x.toString(),summary:`${P} MinCollateral is a local simulation check, not an on-chain floor.`}})]}};export{E as a,Wt as b,we as c,$t as d,Y as e,ko as f,Ot as g,yo as h,Et as i,go as j,Ht as k,De as l,Io as m,B as n,To as o,Mo as p,me as q,vo as r,Po as s,lt as t,j as u,qe as v,Bo as w,No as x,ut as y,se as z,Ae as A,Oo as B,je as C,ke as D,Xt as E,Qe as F,Ka as G,Qo as H,Qa as I,et as J,vt as K,O as L,la as M};