@oakagentkit/core 0.1.9 → 0.2.1
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.
- package/build/dist/api/deployments.d.ts +26 -0
- package/build/dist/api/deployments.js +1 -0
- package/build/dist/api/history.js +1 -1
- package/build/dist/api/modules/beefy/clm.js +1 -1
- package/build/dist/api/modules/beefy/guard.js +1 -1
- package/build/dist/api/modules/beefy/index.js +1 -1
- package/build/dist/api/modules/beefy/liquidity.js +1 -1
- package/build/dist/api/modules/clanker/index.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
- package/build/dist/api/modules/hoodlock/fee.js +1 -1
- package/build/dist/api/modules/hoodlock/guard.js +1 -1
- package/build/dist/api/modules/hoodlock/index.js +1 -1
- package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
- package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
- package/build/dist/api/modules/hoodlock/public.js +1 -1
- package/build/dist/api/modules/hookr/actions.js +1 -1
- package/build/dist/api/modules/hookr/addons.js +1 -1
- package/build/dist/api/modules/hookr/contracts.js +1 -1
- package/build/dist/api/modules/hookr/create-cancel.js +1 -1
- package/build/dist/api/modules/hookr/discovery.js +1 -1
- package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
- package/build/dist/api/modules/hookr/index.js +1 -1
- package/build/dist/api/modules/hookr/public-reads.js +1 -1
- package/build/dist/api/modules/hookr/relay.js +1 -1
- package/build/dist/api/modules/kyberswap/index.js +1 -1
- package/build/dist/api/modules/kyberswap/source-pools.d.ts +22 -3
- package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
- package/build/dist/api/modules/longbow/administration.js +1 -1
- package/build/dist/api/modules/longbow/fixed.js +1 -1
- package/build/dist/api/modules/longbow/index.js +1 -1
- package/build/dist/api/modules/meridian/index.js +1 -1
- package/build/dist/api/modules/meridian/rfq.js +1 -1
- package/build/dist/api/modules/morpho/bundles.js +1 -1
- package/build/dist/api/modules/morpho/in-kind.js +1 -1
- package/build/dist/api/modules/morpho/index.js +1 -1
- package/build/dist/api/modules/morpho/local-guard.js +1 -1
- package/build/dist/api/modules/morpho/midnight.js +1 -1
- package/build/dist/api/modules/morpho/protocol.js +1 -1
- package/build/dist/api/modules/morpho/vault-tools.js +1 -1
- package/build/dist/api/modules/netnet/card-plan.js +1 -1
- package/build/dist/api/modules/netnet/card-read.js +1 -1
- package/build/dist/api/modules/netnet/card-recovery.js +1 -1
- package/build/dist/api/modules/netnet/desk-action.js +1 -1
- package/build/dist/api/modules/netnet/financial.js +1 -1
- package/build/dist/api/modules/netnet/index.js +1 -1
- package/build/dist/api/modules/orbio/index.js +1 -1
- package/build/dist/api/modules/pons/claim.js +1 -1
- package/build/dist/api/modules/pons/index.js +1 -1
- package/build/dist/api/modules/pons/launch-status.js +1 -1
- package/build/dist/api/modules/pons/reads.js +1 -1
- package/build/dist/api/modules/pons/trade.js +1 -1
- package/build/dist/api/modules/poolstrade/index.js +1 -1
- package/build/dist/api/modules/priors/coverage.js +1 -1
- package/build/dist/api/modules/priors/discovery.js +1 -1
- package/build/dist/api/modules/priors/index.js +1 -1
- package/build/dist/api/modules/priors/integration.js +1 -1
- package/build/dist/api/modules/priors/stock-swap.js +1 -1
- package/build/dist/api/modules/relay/discovery.js +1 -1
- package/build/dist/api/modules/relay/inbound.js +1 -1
- package/build/dist/api/modules/relay/index.js +1 -1
- package/build/dist/api/modules/relay/outbound-status.js +1 -1
- package/build/dist/api/modules/steakhouse/index.js +1 -1
- package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
- package/build/dist/api/modules/steakhouse/management.js +1 -1
- package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
- package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
- package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
- package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
- package/build/dist/api/modules/tickerspring/guards.js +1 -1
- package/build/dist/api/modules/tickerspring/index.js +1 -1
- package/build/dist/api/modules/tickerspring/journeys.js +1 -1
- package/build/dist/api/modules/tickerspring/ladder.js +1 -1
- package/build/dist/api/modules/tickerspring/maker.js +1 -1
- package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
- package/build/dist/api/modules/tickerspring/research.js +1 -1
- package/build/dist/api/modules/tickerspring/strategies.js +1 -1
- package/build/dist/api/modules/uniswap/auction-create.js +1 -1
- package/build/dist/api/modules/uniswap/auction.js +1 -1
- package/build/dist/api/modules/uniswap/batch.js +1 -1
- package/build/dist/api/modules/uniswap/common.js +1 -1
- package/build/dist/api/modules/uniswap/fees.js +1 -1
- package/build/dist/api/modules/uniswap/index.js +1 -1
- package/build/dist/api/modules/uniswap/local-guard.js +1 -1
- package/build/dist/api/modules/uniswap/oracle.js +1 -1
- package/build/dist/api/modules/uniswap/pool-math.js +1 -1
- package/build/dist/api/modules/uniswap/pools.js +1 -1
- package/build/dist/api/modules/uniswap/position.js +1 -1
- package/build/dist/api/modules/uniswap/protocol.js +1 -1
- package/build/dist/api/modules/uniswap/token-jar.js +1 -1
- package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
- package/build/dist/api/modules/uniswap/trade.js +1 -1
- package/build/dist/api/modules/uniswap/v2.js +1 -1
- package/build/dist/api/modules/uniswap/v3.js +1 -1
- package/build/dist/api/modules/uniswap/v4.js +1 -1
- package/build/dist/api/modules/uniswap/wrap.js +1 -1
- package/build/dist/api/modules/velora/claims.js +1 -1
- package/build/dist/api/modules/velora/index.js +1 -1
- package/build/dist/api/prices.js +1 -1
- package/build/dist/api/routes.d.ts +2 -0
- package/build/dist/api/routes.js +1 -1
- package/build/dist/api/send.js +1 -1
- package/build/dist/api/signing-registry.js +1 -1
- package/build/dist/api/simulate.js +1 -1
- package/build/dist/api/swap.js +1 -1
- package/build/dist/api/tokens.d.ts +4 -0
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/chunks/{ZL3KVABO.js → 22S4SFD5.js} +1 -1
- package/build/dist/chunks/{MWWYIFXJ.js → 2CS3M32D.js} +1 -1
- package/build/dist/chunks/{JVTVOK6P.js → 3R3C3CU5.js} +1 -1
- package/build/dist/chunks/{QOY4AANB.js → 3ZVGHC6S.js} +1 -1
- package/build/dist/chunks/{2EGFALNH.js → 5LQBHXFA.js} +1 -1
- package/build/dist/chunks/{OJP7Y4AM.js → 5RKWSFD2.js} +1 -1
- package/build/dist/chunks/6L6DSMCU.js +1 -0
- package/build/dist/chunks/{FLXID6I3.js → 6LLOTPH2.js} +1 -1
- package/build/dist/chunks/{JOMK32QW.js → 72AWP4BM.js} +1 -1
- package/build/dist/chunks/{C5LR6F4B.js → 7T4BYFD4.js} +1 -1
- package/build/dist/chunks/{W6G2QGYF.js → AZGMF26W.js} +1 -1
- package/build/dist/chunks/{PHXWBC4O.js → BBVKWG65.js} +1 -1
- package/build/dist/chunks/{HYIEQG4X.js → BEPSWFJX.js} +1 -1
- package/build/dist/chunks/{YONRUWN7.js → BG4S6MSN.js} +1 -1
- package/build/dist/chunks/{QH3AL3UN.js → BV3AHLH5.js} +1 -1
- package/build/dist/chunks/CAU44UWP.js +1 -0
- package/build/dist/chunks/{BQLLTY4L.js → D4WURN33.js} +1 -1
- package/build/dist/chunks/{HACP2Q6D.js → D6VP3N27.js} +2 -2
- package/build/dist/chunks/{6SB3FB3P.js → DD7755AW.js} +1 -1
- package/build/dist/chunks/{4CDR7F4I.js → DGGOO4RN.js} +1 -1
- package/build/dist/chunks/{VCWDJQDE.js → DVKDWXEJ.js} +1 -1
- package/build/dist/chunks/{4X6JEMSF.js → E24S22BZ.js} +1 -1
- package/build/dist/chunks/EA6IYKIB.js +1 -0
- package/build/dist/chunks/{SYZ55RCX.js → EYYUWFUR.js} +1 -1
- package/build/dist/chunks/FBQWTWPT.js +1 -0
- package/build/dist/chunks/{P6ELT4ZV.js → FKAA7VUR.js} +1 -1
- package/build/dist/chunks/{NUWL6TJM.js → GECX5U3F.js} +1 -1
- package/build/dist/chunks/{B72Q2EQ2.js → GUBB5P6V.js} +1 -1
- package/build/dist/chunks/{EHVPRQHS.js → I7NUTSSX.js} +1 -1
- package/build/dist/chunks/{ITIIHCZK.js → IAXKPME3.js} +1 -1
- package/build/dist/chunks/{WQZLYX64.js → IRWEY7TQ.js} +1 -1
- package/build/dist/chunks/{2LM5C7FQ.js → IUETZH6I.js} +1 -1
- package/build/dist/chunks/{FL3EF72E.js → JG24LNUI.js} +1 -1
- package/build/dist/chunks/{IKP3Z3RX.js → K7HIKXNT.js} +1 -1
- package/build/dist/chunks/LFN3OODW.js +1 -0
- package/build/dist/chunks/{FYTF2QMS.js → MEMVFR7Z.js} +1 -1
- package/build/dist/chunks/{37QNUNED.js → MNFU7PO3.js} +1 -1
- package/build/dist/chunks/{REGJY5RC.js → N37ZLNCT.js} +1 -1
- package/build/dist/chunks/{UEYFMXV3.js → N3GWFLG6.js} +1 -1
- package/build/dist/chunks/{SEW7UP5U.js → NCEJZWGX.js} +1 -1
- package/build/dist/chunks/{OK3TQFXZ.js → NKY3DT34.js} +1 -1
- package/build/dist/chunks/NMFVXBTL.js +1 -0
- package/build/dist/chunks/{SS7U3CMZ.js → NUTHT4FE.js} +1 -1
- package/build/dist/chunks/{5H3MQWH7.js → O7PQDUVT.js} +1 -1
- package/build/dist/chunks/{CS55ERS3.js → OMTCWXQR.js} +1 -1
- package/build/dist/chunks/{JRZLKIYB.js → PR2QED25.js} +1 -1
- package/build/dist/chunks/{B7V7AA5A.js → Q4RZQCDS.js} +1 -1
- package/build/dist/chunks/{E2IVNGLC.js → QR7ALOR4.js} +1 -1
- package/build/dist/chunks/{SQH7A4O3.js → QXFJZGVB.js} +1 -1
- package/build/dist/chunks/{ZPNGV34U.js → QYHJWU5T.js} +1 -1
- package/build/dist/chunks/{NNZ4SZZ4.js → QZM7CWZW.js} +1 -1
- package/build/dist/chunks/{E2Q5IA67.js → RM5W63LO.js} +1 -1
- package/build/dist/chunks/{Z4LJ2GTX.js → RTBOMWCB.js} +1 -1
- package/build/dist/chunks/T3MGNKA6.js +1 -0
- package/build/dist/chunks/{L2MTPRU7.js → T3NPRRTY.js} +1 -1
- package/build/dist/chunks/{HF2AGJZC.js → TDN3C4IG.js} +1 -1
- package/build/dist/chunks/{WHT45EFX.js → UIIJWIR6.js} +1 -1
- package/build/dist/chunks/{CAYBSVA6.js → ULJ6E4HP.js} +1 -1
- package/build/dist/chunks/{K2LWX3PZ.js → UMK564HS.js} +1 -1
- package/build/dist/chunks/{AIWZGIZ6.js → UPPYXY74.js} +1 -1
- package/build/dist/chunks/{XCFA73P2.js → VJ3W2V3B.js} +1 -1
- package/build/dist/chunks/{RNEMTLQG.js → VY3P34PY.js} +1 -1
- package/build/dist/chunks/{EKGHKEKV.js → WLACEU2Y.js} +1 -1
- package/build/dist/chunks/{KEPQXFHU.js → X6G4BD35.js} +1 -1
- package/build/dist/chunks/{CXMC3T6B.js → XGUKLFBU.js} +1 -1
- package/build/dist/chunks/XUJSQV52.js +1 -0
- package/build/dist/chunks/{LFKSXD3S.js → YMB553OJ.js} +1 -1
- package/build/dist/chunks/{BBQVTEYB.js → ZGXNTWYG.js} +1 -1
- package/package.json +2 -2
- package/build/dist/chunks/2O6A6WEX.js +0 -1
- package/build/dist/chunks/3Z3U4YPA.js +0 -1
- package/build/dist/chunks/74BPMUAG.js +0 -1
- package/build/dist/chunks/E7ASOYQI.js +0 -1
- package/build/dist/chunks/EAEQOS7Y.js +0 -1
- package/build/dist/chunks/HZUWK5B2.js +0 -1
- package/build/dist/chunks/OJMYESQU.js +0 -1
- package/build/dist/chunks/ZQI7B2Z7.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as v,d as N,e as h}from"./
|
|
1
|
+
import{c as v,d as N,e as h}from"./ULJ6E4HP.js";import{a as m}from"./UWOFA6GV.js";import{c as d,f as B,g as p,i as E}from"./73N3TOJL.js";import{a as H}from"./XPFVT2EA.js";import{a as o}from"./5YS5V2LK.js";import{decodeEventLog as W,encodeFunctionData as G,getAddress as V,hashStruct as Y,isHex as J,parseAbi as Q,zeroAddress as k}from"viem";var Z="struct HookrSwapIntent { PoolKey key; bool zeroForOne; int128 amountSpecified; uint128 amountBound; uint160 sqrtPriceLimitX96; address recipient; address relayer; uint256 relayerFee; address engagement; uint256[] campaigns; uint256 nonce; uint256 deadline; }",I=Q(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }",Z,"function execute(HookrSwapIntent intent, address owner, bytes signature) returns (uint256 amountIn, uint256 amountOut)","function hashIntent(HookrSwapIntent intent) pure returns (bytes32)","function pullOf(HookrSwapIntent intent) view returns (address token, uint256 amount, bool feeFromInput)","function isNonceUsed(address owner, uint256 intentNonce) view returns (bool)","function router() view returns (address)","function registry() view returns (address)","function permit2() view returns (address)","event IntentExecuted(bytes32 indexed intentHash,address indexed owner,address indexed relayer,bytes32 poolId,uint256 amountIn,uint256 amountOut,uint256 relayerFee,bool feeFromInput)"]),ee={PoolKey:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],HookrSwapIntent:[{name:"key",type:"PoolKey"},{name:"zeroForOne",type:"bool"},{name:"amountSpecified",type:"int128"},{name:"amountBound",type:"uint128"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"recipient",type:"address"},{name:"relayer",type:"address"},{name:"relayerFee",type:"uint256"},{name:"engagement",type:"address"},{name:"campaigns",type:"uint256[]"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},ne=V("0x000000000022D473030F116dDEE9F6B43aC78BA3"),F={key:{type:"object",properties:{currency0:d,currency1:d,fee:{type:"integer"},tickSpacing:{type:"integer"},hooks:d},required:["currency0","currency1","fee","tickSpacing","hooks"],additionalProperties:!1},zeroForOne:{type:"boolean"},amountSpecified:{type:"string",pattern:"^-?[0-9]+$"},amountBound:m(),sqrtPriceLimitX96:m(),recipient:d,relayer:d,relayerFee:m(),engagement:d,campaigns:{type:"array",items:m(),maxItems:8},nonce:m(),deadline:m()},x={owner:d,signature:{type:"string",pattern:"^0x[0-9a-fA-F]+$"},intent:{type:"object",properties:F,required:Object.keys(F),additionalProperties:!1}};function D(t){return B(t,"Provide a complete trader-signed Hookr intent.")}function y(t,i=256,e=!1){if(typeof t!="string"||!/^-?\d+$/.test(t)||t.length>79)throw new o("Hookr intent amounts, nonce and deadline must be decimal base-unit strings.");let n=BigInt(t);if(e?n<=-(1n<<BigInt(i-1))||n>=1n<<BigInt(i-1):n<0n||n>=1n<<BigInt(i))throw new o("Hookr intent integer is outside its ABI range.");return n}function l(t){return E(t,"Provide valid Hookr intent addresses.")}function j(t,i){if(Object.keys(t).some(s=>!Object.hasOwn(x,s)))throw new o("Provide only owner, intent and the trader signature for Hookr relay.");let e=D(t.intent);if(Object.keys(e).some(s=>!Object.hasOwn(F,s)))throw new o("Hookr intent contains an undocumented field.");let n=D(e.key);if(Object.keys(n).some(s=>!["currency0","currency1","fee","tickSpacing","hooks"].includes(s))||typeof n.fee!="number"||!Number.isInteger(n.fee)||n.fee<0||n.fee>16777215||typeof n.tickSpacing!="number"||!Number.isInteger(n.tickSpacing)||n.tickSpacing<=0||n.tickSpacing>8388607||typeof e.zeroForOne!="boolean")throw new o("Provide a valid canonical v4 pool key and direction.");let a={currency0:l(n.currency0),currency1:l(n.currency1),fee:n.fee,tickSpacing:n.tickSpacing,hooks:l(n.hooks)};if(BigInt(a.currency0)>=BigInt(a.currency1))throw new o("Hookr pool currencies must sort strictly by address.");let r=l(t.owner);if(r===k||p(r,i))throw new o("Hookr relay requires another trader as owner; the relayer funds gas only.");if(!Array.isArray(e.campaigns)||e.campaigns.length>8)throw new o("Provide at most eight Hookr campaign IDs.");let c={key:a,zeroForOne:e.zeroForOne,amountSpecified:y(e.amountSpecified,128,!0),amountBound:y(e.amountBound,128),sqrtPriceLimitX96:y(e.sqrtPriceLimitX96,160),recipient:l(e.recipient),relayer:l(e.relayer),relayerFee:y(e.relayerFee),engagement:l(e.engagement),campaigns:e.campaigns.map(s=>y(s)),nonce:y(e.nonce),deadline:y(e.deadline)};if(c.amountSpecified===0n||c.amountBound===0n)throw new o("Hookr intent input/output amounts and bound must be nonzero.");if([k,h,v].some(s=>p(s,c.recipient)))throw new o("Hookr intent recipient is reserved.");if(c.relayer!==k&&!p(c.relayer,i)||c.relayer===k&&c.relayerFee!==0n)throw new o("Hookr intent names a different relayer or an open relay with a fee.");if(c.engagement===k!=(c.campaigns.length===0))throw new o("Hookr engagement and campaigns must be supplied together.");let f=c.zeroForOne?a.currency0:a.currency1;if(f===k)throw new o("Hookr Permit2 relay cannot pull native ETH input.");if(typeof t.signature!="string"||!J(t.signature,{strict:!0})||t.signature.length<4||t.signature.length%2!==0||t.signature.length>16386)throw new o("Provide the trader-signed Permit2 witness signature, never a private key.");let S=t.signature,w=Y({data:c,primaryType:"HookrSwapIntent",types:ee});return{owner:r,intent:c,signature:S,input:f,intentHash:w}}function q(t,i){let{owner:e,intent:n,signature:a}=j(t,i);return{chainId:H,to:h,value:"0",data:G({abi:I,functionName:"execute",args:[n,e,a]}),description:`Relay Hookr trader ${e} to recipient ${n.recipient}; relayer fee ${n.relayerFee} in pool quote currency. Relayer pays gas; owner supplies Permit2 funds.`}}function ce(t,i,e){let n=q(i,e);if(t.length!==1||t[0].chainId!==n.chainId||!p(t[0].to,n.to)||t[0].value!=="0"||!p(t[0].data,n.data))throw new o("Hookr relay calldata differs from the locally requested signed intent.")}function ue(t){return[{name:"hookr_relay",inputSchema:{type:"object",description:"Preview a trader-signed Permit2 swap for local human-confirmed submission. Relayer pays gas; the trader supplies input. No signature is created by this tool.",properties:x,required:Object.keys(x),additionalProperties:!1},execute:async(i,e)=>{let n=j(i,e),{owner:a,intent:r,signature:c,input:f,intentHash:S}=n,w=t.clientFor(H),s=await w.getBlock();if(typeof s.number!="bigint"||typeof s.timestamp!="bigint"||s.timestamp<=0n||s.timestamp>r.deadline)throw new o("Hookr signed intent expired or the chain timestamp is unavailable.");let g=(X,M=[])=>w.readContract({address:h,abi:I,functionName:X,args:M,blockNumber:s.number}),[_,u,z,K,$,U]=await Promise.all([g("hashIntent",[r]),g("pullOf",[r]),g("isNonceUsed",[a,r.nonce]),g("router"),g("registry"),g("permit2")]);if(_!==S||z!==!1||K!==v||$!==N||U!==ne)throw new o("Hookr intent hash, nonce or forwarder deployment is invalid. Ask the trader for a fresh signed intent.");if(!Array.isArray(u)||u.length!==3||typeof u[0]!="string"||!p(u[0],f)||typeof u[1]!="bigint"||typeof u[2]!="boolean")throw new o("Hookr Permit2 pull could not be verified.");let b=u[2],P=r.amountSpecified<0n?-r.amountSpecified:r.amountBound;if(u[1]!==P+(b?r.relayerFee:0n)||r.amountSpecified>0n&&!b&&r.relayerFee>r.amountSpecified)throw new o("Hookr Permit2 pull or output-side fee differs from the signed terms.");let C=await w.simulateContract({address:h,abi:I,functionName:"execute",args:[r,a,c],account:e,blockNumber:s.number}),[A,R]=C.result,T=r.amountSpecified<0n?r.amountBound:r.amountSpecified-(b?0n:r.relayerFee);if(A>P||R<T)throw new o("Hookr relay simulation did not satisfy the signed input/output bounds.");let O=[t.unsignedTx(q(i,e))],L=await t.preview(O,e);return{txs:O,preview:L,summary:O[0].description,intentHash:S,owner:a,recipient:r.recipient,relayer:e,inputToken:f,maximumPull:u[1].toString(),feeToken:b?f:r.zeroForOne?r.key.currency1:r.key.currency0,relayerFee:r.relayerFee.toString(),feeFromInput:b,minimumOutput:T.toString(),simulatedAmountIn:A.toString(),simulatedAmountOut:R.toString(),note:"Verify IntentExecuted in the receipt and your fee balance after submission."}}},{name:"hookr_relay_receipt",inputSchema:{type:"object",description:"Read the executed intent and fee from a mined Hookr relay receipt.",properties:{transactionHash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}},required:["transactionHash"],additionalProperties:!1},execute:async i=>{if(Object.keys(i).some(a=>a!=="transactionHash")||typeof i.transactionHash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(i.transactionHash))throw new o("Provide a Hookr relay transactionHash.");let e=await t.clientFor(H).getTransactionReceipt({hash:i.transactionHash});if(e.status!=="success")throw new o("Hookr relay reverted. No fee is proven paid.");let n=e.logs.filter(a=>p(a.address,h)).flatMap(a=>{try{let r=W({abi:I,eventName:"IntentExecuted",topics:a.topics,data:a.data});return[{...r.args,amountIn:r.args.amountIn.toString(),amountOut:r.args.amountOut.toString(),relayerFee:r.args.relayerFee.toString()}]}catch{return[]}});if(!n.length)throw new o("Receipt contains no verified Hookr IntentExecuted event.");return{chainId:H,transactionHash:e.transactionHash,blockNumber:e.blockNumber.toString(),intents:n,note:"Event evidence at this mined block; check balances and finality."}}}]}export{I as a,j as b,q as c,ce as d,ue as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as c}from"./
|
|
1
|
+
import{f as c}from"./JG24LNUI.js";import{a,f as p,g as u}from"./IAXKPME3.js";import{a as e}from"./UWOFA6GV.js";import{a as r}from"./XPFVT2EA.js";import{a as n}from"./5YS5V2LK.js";import{encodeFunctionData as d,parseAbi as f}from"viem";var m=f(["function deposit() payable","function withdraw(uint256)"]);function H(i){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{type:"string",enum:["wrap","unwrap"]},amount:e()}},async execute(t,w){if(u(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new n("Choose direction wrap or unwrap.");let o=a(t.amount,"amount"),s=t.direction==="wrap"?d({abi:m,functionName:"deposit"}):d({abi:m,functionName:"withdraw",args:[o]});return p(i,[i.unsignedTx({to:c,data:s,value:t.direction==="wrap"?o.toString():"0",chainId:r,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],w,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{m as a,H as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as P,g as A,m as S}from"./
|
|
1
|
+
import{d as P,g as A,m as S}from"./3R3C3CU5.js";import{N as y,b as h}from"./JG24LNUI.js";import{a as I,b as k,f as N,g as v}from"./IAXKPME3.js";import{a as b}from"./UWOFA6GV.js";import{c as w,g}from"./73N3TOJL.js";import{a as m}from"./XPFVT2EA.js";import{a as r}from"./5YS5V2LK.js";import{encodeFunctionData as f,parseAbi as T,zeroAddress as _}from"viem";var i=T(["function ownerOf(uint256) view returns (address)","function getApproved(uint256) view returns (address)","function getPositionLiquidity(uint256) view returns (uint128)","function safeTransferFrom(address from,address to,uint256 tokenId)","function approve(address spender,uint256 tokenId)","function burn(uint256 tokenId)"]),q={version:{type:"string",enum:["v3","v4"]},tokenId:b(),operation:{type:"string",enum:["transfer","approve","revoke","burn"]},target:w};function D(s){return{tools:[!1,!0].map(c=>({name:c?"uniswap_position_manage":"uniswap_position_status",inputSchema:{type:"object",additionalProperties:!1,required:c?["version","tokenId","operation"]:["version","tokenId"],properties:q},async execute(e,p){if(e.version!=="v3"&&e.version!=="v4")throw new r("Specify position version v3 or v4.");let o=I(e.tokenId,"tokenId"),a=e.version==="v3"?P.positionManager:h,d=s.clientFor(m),l=await d.readContract({address:a,abi:i,functionName:"ownerOf",args:[o]});if(!c){v(e,["version","tokenId"]);let n=await d.readContract({address:a,abi:i,functionName:"getApproved",args:[o]});return{version:e.version,tokenId:o.toString(),manager:a,owner:l,approved:n}}if(!g(l,p))throw new r("Only manage a Uniswap NFT owned by the signing wallet.");let t=e.operation;v(e,["version","tokenId","operation",...["transfer","approve"].includes(String(t))?["target"]:[]]);let u;if(t==="transfer"||t==="approve"){let n=k(e.target);if(n===_)throw new r("Choose a nonzero target, or operation revoke to clear approval.");u=t==="transfer"?f({abi:i,functionName:"safeTransferFrom",args:[p,n,o]}):f({abi:i,functionName:"approve",args:[n,o]})}else if(t==="revoke")u=f({abi:i,functionName:"approve",args:[_,o]});else if(t==="burn"){if(e.version==="v4"){if(await d.readContract({address:a,abi:i,functionName:"getPositionLiquidity",args:[o]})!==0n)throw new r("Remove all liquidity before burning an empty position.");return y(s).tools.find(O=>O.name==="uniswap_remove").execute({version:"v4",tokenId:o.toString(),liquidity:"all",amount0Min:"0",amount1Min:"0"},p)}let n=S(await d.readContract({address:a,abi:A,functionName:"positions",args:[o]}));if(n.liquidity!==0n||n.tokensOwed0!==0n||n.tokensOwed1!==0n)throw new r("Remove liquidity and collect all owed tokens before burning a v3 NFT.");u=f({abi:i,functionName:"burn",args:[o]})}else throw new r("Choose transfer, approve, revoke or burn. Operator-wide approvals are not exact approvals.");return N(s,[s.unsignedTx({to:a,data:u,value:"0",chainId:m,description:`${t} Uniswap ${e.version} NFT #${o}${e.target?` with target ${e.target}`:""}.`})],p,"Position ownership or exact per-NFT approval changes. A transferred position includes its liquidity and accrued rights; burn requires an empty NFT.")}}))}}export{i as a,D as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{q as m}from"./BBVKWG65.js";import{c as u,f as h}from"./QRUC7EFE.js";import{d as p,f}from"./3ZVGHC6S.js";import{i as g,j as k}from"./IUETZH6I.js";import{a as d}from"./AXYOJBX6.js";import{g as l}from"./73N3TOJL.js";import{a as i}from"./5YS5V2LK.js";var w=["hoodlock_lock","hoodlock_burn","hoodlock_airdrop_create","hoodlock_airdrop_claim",...p,...u];async function H(e,r,t,s){if(!w.includes(e))throw new i("Unknown HoodLock action; nothing was signed.");let o=async()=>{throw new i("HoodLock does not require a swap for this action.")},n=d({clientFor:()=>s,http:fetch,preview:async a=>({txs:a,changes:[],summary:"Locally reconstructed HoodLock intent."}),quoteSwap:o,buildSwap:o}),c=await[g(n),k(n),...m(n).tools,...f(n).tools,...h(n).tools].find(a=>a.name===e).execute(r,t);if(!Array.isArray(c.txs)||c.txs.length===0)throw new i("HoodLock action has no transactions; use the read route.");return c.txs.map(a=>({...a}))}function I(e,r){if(!r.length||e.length!==r.length||e.some((t,s)=>{let o=r[s];return t.chainId!==o.chainId||!l(t.to,o.to)||!l(t.data,o.data)||t.value!==o.value}))throw new i("HoodLock transaction differs from the locally reconstructed request; nothing was signed.")}export{w as a,H as b,I as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as m,h as t}from"./73N3TOJL.js";import{b as E}from"./IWALIX7Q.js";import{i as C}from"./XPFVT2EA.js";import{a as v,b as g}from"./5YS5V2LK.js";import{keccak256 as j,parseAbi as D}from"viem";var A=Object.freeze({robinswapV2:Object.freeze({factory:"0xa95DA9b9fCef09A07F99444fE9304457d6ECdccA",kind:"v2",kyberswap:"robinswap-v2",velora:void 0}),uniswapV2:Object.freeze({factory:"0x8BcEAA40b9aCDfAedf85ADf4fF01f5ad6517937F",kind:"v2",kyberswap:"uniswap",velora:"uniswapv2"}),uniswapV3:Object.freeze({factory:C[4663].uniswap.v3_factory.address,kind:"v3",kyberswap:"uniswapv3",velora:"uniswapv3"})}),L=Object.freeze(Object.fromEntries(Object.entries(A).map(([r,n])=>[r,n.factory])));function V(r){return Object.values(A).flatMap(n=>n[r]??[])}var P=D(["function token0() view returns (address)","function token1() view returns (address)","function factory() view returns (address)","function fee() view returns (uint24)"]),S=D(["function getPair(address,address) view returns (address)","function getPool(address,address,uint24) view returns (address)"]),a=new Map;function M(r,n,i){let d=a.get(j(i));return!!d&&d.expires>Date.now()&&t(d.token,r)&&d.pools.some(u=>t(u,n))}async function B(r,n,i,d,u,z){let w=[...new Set(d.filter(o=>!t(o,u)).map(o=>o.toLowerCase()))];if(!w.length)return;let k=j(z);a.delete(k);let f=await r.getBlockNumber();for(let o of w){let s=e=>new v(`KyberSwap source receiver ${o} is not a verified input pool: ${e}.`),l=Array.isArray(n)?n.map(e=>Array.isArray(e)?e[0]:void 0).find(e=>m(e)&&t(e.pool,o)&&t(e.tokenIn,i)):void 0;if(!m(l)||typeof l.tokenOut!="string")throw s("not named as an input hop in the accepted route");let O=await r.getCode({address:o,blockNumber:f});if(!O||O==="0x")throw s("no deployed code");try{let[e,p,y]=await Promise.all(["token0","token1","factory"].map(c=>r.readContract({address:o,abi:P,functionName:c,blockNumber:f}))),h=t(e,i)?p:t(p,i)?e:void 0;if(!h||!t(h,l.tokenOut))throw s("tokens do not match the input route");let x=Object.values(A).find(c=>t(y,c.factory));if(!x)throw s("factory is not pinned");let b;if(x.kind==="v2")b=await r.readContract({address:y,abi:S,functionName:"getPair",args:[e,p],blockNumber:f});else{let c=await r.readContract({address:o,abi:P,functionName:"fee",blockNumber:f});b=await r.readContract({address:y,abi:S,functionName:"getPool",args:[e,p,c],blockNumber:f})}if(!t(b,o))throw s("not registered by the pinned factory")}catch(e){throw e instanceof v||E(e)?e:g(e,3)?s("pool token or factory read reverted; this pool interface is not supported by Oak"):s("on-chain verification unavailable")}}for(let[o,s]of a)s.expires<=Date.now()&&a.delete(o);a.size>=1e3&&a.delete(a.keys().next().value),a.set(k,{token:i,pools:w,expires:Date.now()+6e4})}export{A as a,L as b,V as c,M as d,B as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as g,d as H,m as M}from"./
|
|
1
|
+
import{c as g,d as H,m as M}from"./DD7755AW.js";import{d,e as s,y as C}from"./JG24LNUI.js";import{f as _,g as k}from"./IAXKPME3.js";import{g as h}from"./73N3TOJL.js";import{a as w}from"./XPFVT2EA.js";import{a as t}from"./5YS5V2LK.js";import{decodeFunctionData as b,encodeFunctionData as B,erc20Abi as $,getAddress as O}from"viem";function K(u){return{tools:[{name:"uniswap_swap_batch",inputSchema:{type:"object",additionalProperties:!1,required:["routes"],properties:{routes:{type:"array",minItems:1,maxItems:20,items:{type:"object",description:"Complete uniswap_swap arguments, including an absolute minAmountOut or maxAmountIn."}}}},async execute(n,v){if(k(n,["routes"]),!Array.isArray(n.routes)||n.routes.length<1||n.routes.length>20)throw new t("Provide 1 to 20 explicit bounded Uniswap routes.");let c=new Map,i="0x",A=0n,a,m=[],y=new Set;for(let e of n.routes){if(!e||typeof e!="object"||Array.isArray(e))throw new t("Each route must contain uniswap_swap arguments.");let I=await M(u,e,v,!1);if(!("txs"in I))throw new t("Route did not build swap transactions.");let E=I.txs;for(let r of E.slice(0,-1))if(h(r.to,d)){let[o,D,N,S]=b({abi:H,data:r.data}).args;if(D!==s)throw new t("Unexpected route approval spender.");let T=o.toLowerCase(),p=c.get(T),U=(p?.amount??0n)+N;if(U>=1n<<160n)throw new t("Combined input approvals exceed uint160.");c.set(T,{token:o,amount:U,expiration:p&&p.expiration<BigInt(S)?p.expiration:BigInt(S)})}else{let o=b({abi:$,data:r.data});if(o.functionName!=="approve"||!h(o.args[0],d))throw new t("Unexpected route prerequisite.")}let f=E.at(-1);if(f.to!==s)throw new t("Route does not use the pinned Universal Router.");A+=BigInt(f.value);let[j,x,P]=b({abi:g,data:f.data}).args,R=j.slice(2).match(/../g)??[];if(R.length!==x.length)throw new t("Unexpected route command/parameter count.");R.forEach((r,o)=>{r==="04"?y.add(x[o]):(i=`${i}${r}`,m.push(x[o]))}),a=a===void 0||P<a?P:a}for(let e of y)i=`${i}04`,m.push(e);let l=[];for(let e of c.values())l.push(u.approval(O(e.token),d,e.amount.toString(),w),C(e.token,s,e.amount.toString(),e.expiration.toString()));return l.push(u.unsignedTx({to:s,data:B({abi:g,functionName:"execute",args:[i,m,a]}),value:A.toString(),chainId:w,description:`Atomically execute ${n.routes.length} caller-selected v2/v3/v4 routes, preserving each route's trade bound.`})),_(u,l,v,"Explicit mixed-version/split routes; every route must meet its own bound. No automatic best-route search or allow-revert branch. The wallet must fund each independently previewed route.")}}]}}export{K as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ae}from"./3CCBUYUM.js";import{a as bt,d as wt,e as ht}from"./L24EOVLT.js";import{a as Ne}from"./7MR37STI.js";import{a as We,b as Be,d as pt}from"./EC5W3UZD.js";import{b as ut,c as mt,d as ft}from"./HZUWK5B2.js";import{d as ct,e as te}from"./EAEQOS7Y.js";import{a as dt}from"./XCFA73P2.js";import{b as lt}from"./AXYOJBX6.js";import{a as q}from"./6IM6A5VA.js";import{a as A,d as z}from"./UWOFA6GV.js";import{d as De,g as E,i as Ue}from"./73N3TOJL.js";import{a as Me}from"./RETS2ZEK.js";import{j as it}from"./IWALIX7Q.js";import{a as p,i as V}from"./XPFVT2EA.js";import{a as i,d as se}from"./5YS5V2LK.js";import{a as ze}from"./JXOEJPJ4.js";import{encodeFunctionData as me,erc20Abi as Ha,getAddress as Kt,parseAbi as st,zeroAddress as qa}from"viem";import{decodeAbiParameters as aa,encodeFunctionData as oa,getAddress as ie,parseAbiParameters as ra,zeroAddress as fe,zeroHash as It}from"viem";import{decodeAbiParameters as Xt,encodeFunctionData as Yt,erc20Abi as Jt,getAddress as St,parseAbi as Zt,parseAbiParameters as ea,zeroHash as kt}from"viem";var Ke=St("0xCE29862924756584BBD0D75CA1249d22007E2813"),At="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",ta="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",yt=Zt(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${At}[] marketParamsList,uint256 exitAssets,${ta} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var gt=(e,t)=>e<t?e:t;async function Za(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),d=e.clientFor(p),m=await pt(d,t,s),c=(S,B,Te,ee=[])=>d.readContract({address:S,abi:B,functionName:Te,args:ee,blockNumber:m.blockNumber}),[f,b,w,h]=await Promise.all([d.getBlock({blockNumber:m.blockNumber}),c(Ke,yt,"BLUE"),c(t,Jt,"balanceOf",[n]),c(t,We,"previewRedeem",[a])]);if(typeof b!="string"||St(b)!==U)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<f.timestamp||u>f.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Be(w))throw new i("maxShares exceeds the wallet share balance.");let y=gt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&W(S.id)),g=l-y,T=k[0]?.penalty??0n,I=g*10n**18n/(10n**18n+T);if(g>0n&&I===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(I===0n)break;let B=gt(S.supplied,I);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),I-=B}if(I>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Be(h))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let v=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],G=(await Promise.all(v.map(S=>c(t,We,"previewWithdraw",[S])))).reduce((S,B)=>S+Be(B),0n);if(G===0n||G>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>Xt(ea(At),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${G} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,P=Yt({abi:yt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:kt,s:kt},u]}),D=[e.approval(t,Ke,G.toString(),p),e.unsignedTx({to:Ke,data:P,value:"0",chainId:p,description:F})],$=await e.preview(D,n),j=-$.changes.filter(S=>S.token.chainId===p&&E(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(j<=0n||j>G)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:D,preview:$,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var pe=ie("0x53A1eB6589861F686af7c531211E35Aefe30210f"),xt=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],Qe={kind:0,data:"0x"},Oe={nonce:0n,deadline:0n,signature:{v:0,r:It,s:It}},na=ra("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),Tt=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:xt},marketId:{type:"string"},destinationMarketId:{type:"string"},assets:A(),collateralAssets:A(),shares:A(),maxRepayAssets:A(),maxLtv:A(),deadline:A(),allocations:{type:"array",maxItems:4,items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string"},sourceMarketId:{type:"string"},assets:A(),maxPenaltyAssets:A()}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(p);if(await n.getChainId()!==p||typeof r!="string"||!xt.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(P=>!l.includes(P)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,d]=await Promise.all([n.readContract({address:pe,abi:Ne,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:pe,abi:Ne,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(ie(u)!==U||ie(d)!==bt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async P=>{if(typeof P!="string"||!W(P))throw new i("Choose a verified Morpho market with a supported exit.");let D=await n.readContract({address:U,abi:O,functionName:"idToMarketParams",args:[P],blockNumber:a.number}),$={loanToken:ie(D[0]),collateralToken:ie(D[1]),oracle:ie(D[2]),irm:ie(D[3]),lltv:D[4]};if(!E(be({...$,lltv:String($.lltv)}),P))throw new i("Blue bundle market identity mismatch.");return $},c=await m(t.marketId),f=r==="migrateBorrowPosition"?await m(t.destinationMarketId):c;if(c.loanToken!==f.loanToken||c.collateralToken!==f.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:U,abi:O,functionName:"isAuthorized",args:[s,pe],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${pe}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),w=t.shares===void 0?0n:N(t.shares,!0),h=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>f.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(w===0n)||r==="supplyCollateralAndBorrow"&&h===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&w>0n||b===0n&&w===0n&&h===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],I=0n;for(let P of k){if(!P||typeof P!="object"||Array.isArray(P)||Object.keys(P).some(Ve=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Ve)))throw new i("Unsupported bundled allocation input.");let D=P,$=await wt(e,{vault:D.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has($.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add($.definition.vault.toLowerCase());let j=N(D.assets),S=N(D.maxPenaltyAssets,!0);if(!$.permission||j>=1n<<128n||j>$.headroom||$.penalty>10n**18n||$.asset.address!==f.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(j*$.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");I+=B;let Te=D.sourceMarketId===void 0,ee=Te?void 0:$.sources.find(Ve=>E(Ve.id,String(D.sourceMarketId)));if(Te?!$.canIdle||j>$.data.idle:!ee||!ee.canPull||j>ee.capacity||j>$.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:$.definition.vault,adapter:$.target.adapter,marketParams:$.params,sourceAdapter:ee?.adapter??fe,sourceMarketParams:ee?aa(na,ee.data)[0]:$.params,assets:j,penalty:$.penalty,fromIdle:Te})}let M,C,v,x=0n;if(r==="supply")M="blueBundlesV1Supply",v=c.loanToken,x=b,C=[c,b,Qe,0n,fe,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[c,b,w,Oe,T,0n,fe,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",v=c.collateralToken,x=h,I>=b&&I>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[c,h,b,y,Qe,Oe,T,0n,fe,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",v=c.loanToken,x=N(t.maxRepayAssets,!0),b>x||w>0n&&x===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[c,b,w,x,h,y,Qe,Oe,0n,fe,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[c,f,y,Oe,T,0n,fe,o];let G=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${I} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${x}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...v&&x?[e.approval(v,pe,x.toString(),p)]:[],e.unsignedTx({to:pe,data:oa({abi:Ne,functionName:M,args:C}),value:"0",chainId:p,description:G})],H=await e.preview(Z,s),F=new Map;for(let P of H.changes)if(BigInt(P.amount)<0n){let D=P.token.address.toLowerCase();F.set(D,(F.get(D)??0n)-BigInt(P.amount))}if([...F].some(([P,D])=>!v||P!==v.toLowerCase()||D>x))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:G}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Mt,decodeAbiParameters as sa,encodeAbiParameters as $t,encodeFunctionData as Xe,erc20Abi as Pt,getAddress as K,keccak256 as Je,zeroAddress as we,zeroHash as ia}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),la=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),Ze=ae.find(e=>e.name==="take"),vt=[Ze.inputs[0]],da=[Ze.inputs[0].components[0]];function Ct(e){let t=Je(Mt(["0x600b380380600b5f395ff3",$t(da,[e])]));return Je(Mt(["0xff",e.midnight,ia,t]))}var le=10n**18n,Lt=(e,t)=>(e+(t-1n)/2n)/t;function Dt(e){if(e<0n)return 10n**36n/Dt(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*le),l=n*r/(3n*le);return le+r+n+l<<s}function ca(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Lt(Lt(10n**36n,le+Dt(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function Ge(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function Ye(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ua=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ut=e=>{async function t(n,l){let a=Ge(n,32),o=e.clientFor(p);if(await o.getChainId()!==p)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),d=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await d("toMarket",[a]);if(m.chainId!==BigInt(p)||K(m.midnight)!==Y||!E(Ct(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![V[p].tokens.USDG.address,V[p].tokens.WETH.address].some(k=>E(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[f,b,w,h]=await Promise.all([d("position",[a,l]),d("updatePositionView",[m,a,l]),d("marketState",[a]),d("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Pt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Pt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:p}};return{id:a,rpc:o,block:u,market:m,read:d,token:y,loan:await y(m.loanToken),position:Ye(f,6),updated:Ye(b,3),state:Ye(w,13),healthy:h}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,d)=>{try{if(q(d),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,d)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string"}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,c)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(c)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],d=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,c)=>[m,K(String(d[c]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:p,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ua(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string"},units:A(),maxAssets:A(),minAssets:A()},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=Ge(n.offer),[o]=sa(vt,a);if(!E($t(vt,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Ct(o.market),l),d=N(n.units),m=N(n.maxAssets,!0),c=N(n.minAssets,!0),f=Ge(n.ratifierData);if(d>=1n<<128n||E(o.maker,l)||o.callback!==we||o.callbackData!=="0x"||!la.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==we||!o.buy&&o.receiverIfMakerIsSeller===we)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&d>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),w=ca(o.tick);if(b>w&&o.buy)throw new i("Settlement fee exceeds the offer price.");let h=o.buy?w-b:w,y=h+b,k=P=>o.buy?P/le:(P+le-1n)/le,g=k(d*y),T=k(d*h);if(o.buy?T<c||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let I=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||I+(o.maxAssets?o.buy?g:T:d)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[Ze.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],v=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,f,l],blockNumber:u.block.number});if(M!==!0||v!==Je(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let x=Xe({abi:ae,functionName:"take",args:[o,f,d,l,o.buy?l:we,we,"0x"]}),G=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${d} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),p)],e.unsignedTx({to:Y,data:x,value:"0",chainId:p,description:G})],H=await r(Z,l,G),F=H.preview.changes.filter(P=>P.token.chainId===p&&E(P.token.address,u.loan.address)).reduce((P,D)=>P+BigInt(D.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string"},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"]},amount:A(),collateralIndex:{type:"integer",minimum:0,maximum:127}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,d,m=a.loan,c=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(c=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,c,l]}else{if(c=N(n.amount),c>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let w=BigInt(String(n.collateralIndex)),h=await a.token(a.market.collateralParams[Number(w)].token);if(m=h,o==="withdrawCollateral"&&c>await a.read("collateral",[a.id,l,w]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,w,c,l]:[a.market,w,c,l,l],o==="supplyCollateral"&&(d=h)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&c>a.position[4]||o==="withdraw"&&(c>a.updated[0]||c>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,c,l,we,"0x"]:[a.market,c,l,l],o==="repay"&&(d=a.loan)}}let f=`Midnight ${o}: ${c} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...d?[e.approval(d.address,Y,c.toString(),p)]:[],e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:String(o),args:u}),value:"0",chainId:p,description:f})];return r(b,l,f)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"]},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(f=>f.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let d=e.clientFor(p);if(await d.getChainId()!==p)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((f,b)=>{let w=n.values[b];if(f.type==="bool"){if(typeof w!="boolean")throw new i("Use boolean management values.");return w}if(f.type==="address")return Ue(w,"Use explicit management addresses.",De);if(f.type==="bytes32")return Ge(w,32);if(/^uint/.test(f.type)){let h=N(w,!0);if(h>=1n<<BigInt(f.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return h}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!E(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let f=await d.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof f!="string"||K(f)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let c=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:o,args:m}),value:"0",chainId:p,description:c})],l,c)})]}};import{decodeAbiParameters as oe,encodeAbiParameters as ma,encodeFunctionData as R,erc20Abi as et,getAddress as L,isAddress as Re,keccak256 as fa,parseAbi as Ee,parseAbiParameters as J}from"viem";var Pe="morpho",pa="https://api.morpho.org/graphql",U=L(V[p].morpho.morpho_blue.address),ba=L(V[p].morpho.adaptive_curve_irm.address),wa=L(V[p].morpho.USDG.address),de=L(V[p].morpho.WETH.address),ha=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],ka={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},tt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],ya=new Map(tt.map(e=>[e.marketId.toLowerCase(),e]));function W(e){return ya.get(e.toLowerCase())}function ot(e){let t=W(e);return t?{actions:"enabled",label:t.label,source:ka[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var Bt=20,ve=120n,_e=1000000n,He=1n,he=10n**18n,ga=10n**36n,Et=(1n<<128n)-1n,Sa=(1n<<256n)-1n,X=Ee(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),Aa=Ee(["function price() view returns (uint256)"]),Ia=Ee(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_t=Ee(["function deposit() payable"]);function ce(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ce(e,t){return e===0n?0n:(e+t-1n)/t}function xa(e,t,s){return e*(s+_e)/(t+He)}function Ta(e,t,s){return Ce(e*(s+_e),t+He)}function rt(e,t,s){return e*(t+He)/(s+_e)}function ne(e,t,s){return Ce(e*(t+He),s+_e)}function ke(e,t,s){return e*t/ga*s/he}function Ma(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function ye(e,t){let s=[],r={};for(let n of t.changes){let l=Ma(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Ht(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function qe(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Re(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Me(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=he)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function be(e){let t=qe(e),s=ma(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return fa(s)}function at(e){let t=e.toLowerCase();return t===dt.toLowerCase()||t===ct.toLowerCase()||t===te.toLowerCase()}function ge(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function re(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function qt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=p){if(q(t),at(t))return{...ut,chainId:s};let r=L(t),n=r.toLowerCase();if(s===p){if(n===wa.toLowerCase())return mt;if(n===de.toLowerCase())return ft}let[l,a]=await Promise.all([re(e,r,R({abi:et,functionName:"symbol"})),re(e,r,R({abi:et,functionName:"decimals"}))]),[o]=oe(J("string"),l),[u]=oe(J("uint8"),a);return{address:r,symbol:qt(o),decimals:Number(u),chainId:s}}async function Ft(e,t){let s=await re(e,U,R({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=oe(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function jt(e,t){let s=await re(e,U,R({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=oe(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Se(e,t,s){let r=await re(e,U,R({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=oe(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Fe(e,t){let s=await re(e,L(t),R({abi:Aa,functionName:"price"})),[r]=oe(J("uint256"),s);return r}async function Pa(e,t,s){if(t.irm===te)return 0n;let r=await re(e,L(t.irm),R({abi:Ia,functionName:"borrowRateView",args:[t,s]})),[n]=oe(J("uint256"),r);return n}function je(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ce(n*n,2n*he),a=Ce(l*n,3n*he);return e.totalBorrowAssets+Ce(e.totalBorrowAssets*(n+l+a),he)}async function Le(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Pa(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:je(s,l,o),accruedThrough:o,rate:l}}async function Vt(e,t,s){let r=await re(e,L(t),R({abi:et,functionName:"balanceOf",args:[L(s)]})),[n]=oe(J("uint256"),r);return n}async function ue(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?qe(n):void 0,a=l?be(l):void 0,o=r!==void 0?Ht(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!W(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[d,m]=await Promise.all([Ft(e,u),jt(e,u)]);if(d.loanToken===te||d.collateralToken===te||d.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${p}.`);let c=be(d);if(c.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${c}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===d.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===d.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===d.oracle.toLowerCase()&&l.irm.toLowerCase()===d.irm.toLowerCase()&&l.lltv===d.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:d,marketState:m}}function Ae(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Me(t);if(s<=0n||s>Et)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function Ie(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function va(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p),{marketId:a,marketParams:o}=await ue(l,t,!0),u=await Q(l,o.collateralToken,p),d=o.collateralToken.toLowerCase()===de.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,c=z("wrapNative",t.wrapNative)===!0||m!==void 0&&at(m);if(m&&!at(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(c&&!d)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let f=Ae(t),b=f.toString(),w=e.formatAmount(b,u.decimals),h=[];c&&h.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:b,description:`Wrap ${w} ETH into WETH at ${de}.`})),h.push(e.approval(o.collateralToken,U,b,p)),h.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supplyCollateral",args:[o,f,n,"0x"]}),value:"0",description:`Supply ${w} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply_collateral",chainId:p,marketId:a,marketParams:ce(o),collateralToken:u,assets:b,formattedAssets:w,onBehalf:n,txs:h,summary:`${c?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ca(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.loanToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=Ae(t),h=w.toString(),y=e.formatAmount(h,m.decimals),k=d.totalSupplyAssets>d.totalBorrowAssets?d.totalSupplyAssets-d.totalBorrowAssets:0n;if(w>k)throw new i(`Insufficient market liquidity: requested ${h} base units, available ${k.toString()} base units.`);let g=ke(c.collateral,f,u.lltv),T=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(c.collateral===0n||T+w>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+w).toString()} exceeds max borrow ${g.toString()} base units.`);let I=Ta(w,b.totalBorrowAssets,d.totalBorrowShares),C=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"borrow",args:[u,w,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${h} base units) from Morpho market ${o}.`})],v=await e.preview(C,r),{formattedChanges:x,formattedNetOutflows:G}=ye(e,v);return{action:"morpho_borrow",chainId:p,marketId:o,marketParams:ce(u),loanToken:m,assets:h,formattedAssets:y,borrowShares:I.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:v,formattedChanges:x,formattedNetOutflows:G}}async function La(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p);if(t.shares!==void 0){let x=Me(t.shares);if(x<=0n||x===Sa||x>Et)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(z("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await ue(l,t,!0),[d,m,c]=await Promise.all([Q(l,o.loanToken,p),Se(l,a,n),Vt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let f=0n,b=0n;if(z("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let x=Me(t.shares);if(x>m.borrowShares)throw new i(`Repay shares (${x.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=x}else f=Ae(t);let w=b>0n?await Le(l,o,u,ve):void 0,h=b>0n?ne(b,w.totalBorrowAssets,u.totalBorrowShares):f;if(c<h)throw new i(`Insufficient loan token balance for repayment: wallet holds ${c.toString()} base units, but ${h.toString()} base units are required (including accrued interest).`);let y=h.toString(),k=e.formatAmount(y,d.decimals),g=e.approval(o.loanToken,U,y,p),T=e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"repay",args:[o,f,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${d.symbol}) on Morpho market ${a}.`:`Repay ${k} ${d.symbol} (${f.toString()} base units) on Morpho market ${a}.`}),I=[g,T],M=await e.preview(I,r),{formattedChanges:C,formattedNetOutflows:v}=ye(e,M);return{action:"morpho_repay",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,repayAssets:f.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:ve.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:I,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${d.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${ve} seconds.`:`Repay ${k} ${d.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:v}}async function $a(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.collateralToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=z("withdrawAll",t.withdrawAll)===!0?c.collateral:Ae(t);if(w<=0n||w>c.collateral)throw new i(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${c.collateral.toString()} base units.`);if(c.borrowShares>0n){let C=c.collateral-w,v=ke(C,f,u.lltv),x=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(x>v)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${v.toString()} would fall below current debt ${x.toString()} base units.`)}let h=w.toString(),y=e.formatAmount(h,m.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdrawCollateral",args:[u,w,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${h} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw_collateral",chainId:p,marketId:o,marketParams:ce(u),collateralToken:m,assets:h,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function Da(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),{marketId:l,marketParams:a,marketState:o}=await ue(n,t,!0),u=z("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==de.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let d=Ae(t),m=d.toString(),[c,f]=await Promise.all([Q(n,a.loanToken,p),u?Promise.resolve(d):Vt(n,a.loanToken,r)]);if(f<d)throw new i(`Insufficient ${c.symbol} balance to lend: wallet holds ${f.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,c.decimals),w=[];u&&w.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${de}.`})),w.push(e.approval(a.loanToken,U,m,p)),w.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supply",args:[a,d,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${c.symbol} (${m} base units) to Morpho market ${l}.`}));let h=xa(d,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply",chainId:p,marketId:l,marketParams:ce(a),loanToken:c,assets:m,formattedAssets:b,supplySharesEstimated:h.toString(),onBehalf:r,oak:ot(l),txs:w,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${c.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ua(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),l=z("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await ue(n,t,!0),[d,m]=await Promise.all([Q(n,o.loanToken,p),Se(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${d.symbol} on Morpho market ${a}.`);let c=rt(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),f=l?0n:Ae(t),b=l?m.supplyShares:0n;if(!l&&f>c)throw new i(`Withdrawal exceeds the lent balance: requested ${f.toString()} base units, position holds about ${c.toString()}. Use withdrawAll for a full exit.`);let w=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,h=l?c:f;if(h>w)throw new i(`Insufficient market liquidity: withdrawing ${h.toString()} base units needs idle assets, but only ${w.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(h.toString(),d.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdraw",args:[o,f,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${d.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${d.symbol} (${f.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,withdrawAssets:f.toString(),withdrawShares:b.toString(),estimatedAssets:h.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${d.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${d.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function zt(e,t,s){let r=await e.http(pa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function Wt(e){let t=`query Markets($chainId: Int!) {
|
|
1
|
+
import{a as ae}from"./3CCBUYUM.js";import{a as bt,d as wt,e as ht}from"./L24EOVLT.js";import{a as Ne}from"./7MR37STI.js";import{a as We,b as Be,d as pt}from"./EC5W3UZD.js";import{b as ut,c as mt,d as ft}from"./T3MGNKA6.js";import{d as ct,e as te}from"./CAU44UWP.js";import{a as dt}from"./VJ3W2V3B.js";import{b as lt}from"./AXYOJBX6.js";import{a as q}from"./6IM6A5VA.js";import{a as A,d as z}from"./UWOFA6GV.js";import{d as De,g as E,i as Ue}from"./73N3TOJL.js";import{a as Me}from"./RETS2ZEK.js";import{j as it}from"./IWALIX7Q.js";import{a as p,i as V}from"./XPFVT2EA.js";import{a as i,d as se}from"./5YS5V2LK.js";import{a as ze}from"./JXOEJPJ4.js";import{encodeFunctionData as me,erc20Abi as Ha,getAddress as Kt,parseAbi as st,zeroAddress as qa}from"viem";import{decodeAbiParameters as aa,encodeFunctionData as oa,getAddress as ie,parseAbiParameters as ra,zeroAddress as fe,zeroHash as It}from"viem";import{decodeAbiParameters as Xt,encodeFunctionData as Yt,erc20Abi as Jt,getAddress as St,parseAbi as Zt,parseAbiParameters as ea,zeroHash as kt}from"viem";var Ke=St("0xCE29862924756584BBD0D75CA1249d22007E2813"),At="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",ta="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",yt=Zt(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${At}[] marketParamsList,uint256 exitAssets,${ta} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var gt=(e,t)=>e<t?e:t;async function Za(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),d=e.clientFor(p),m=await pt(d,t,s),c=(S,B,Te,ee=[])=>d.readContract({address:S,abi:B,functionName:Te,args:ee,blockNumber:m.blockNumber}),[f,b,w,h]=await Promise.all([d.getBlock({blockNumber:m.blockNumber}),c(Ke,yt,"BLUE"),c(t,Jt,"balanceOf",[n]),c(t,We,"previewRedeem",[a])]);if(typeof b!="string"||St(b)!==U)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<f.timestamp||u>f.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Be(w))throw new i("maxShares exceeds the wallet share balance.");let y=gt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&W(S.id)),g=l-y,T=k[0]?.penalty??0n,I=g*10n**18n/(10n**18n+T);if(g>0n&&I===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(I===0n)break;let B=gt(S.supplied,I);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),I-=B}if(I>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Be(h))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let v=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],G=(await Promise.all(v.map(S=>c(t,We,"previewWithdraw",[S])))).reduce((S,B)=>S+Be(B),0n);if(G===0n||G>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>Xt(ea(At),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${G} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,P=Yt({abi:yt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:kt,s:kt},u]}),D=[e.approval(t,Ke,G.toString(),p),e.unsignedTx({to:Ke,data:P,value:"0",chainId:p,description:F})],$=await e.preview(D,n),j=-$.changes.filter(S=>S.token.chainId===p&&E(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(j<=0n||j>G)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:D,preview:$,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var pe=ie("0x53A1eB6589861F686af7c531211E35Aefe30210f"),xt=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],Qe={kind:0,data:"0x"},Oe={nonce:0n,deadline:0n,signature:{v:0,r:It,s:It}},na=ra("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),Tt=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:xt},marketId:{type:"string"},destinationMarketId:{type:"string"},assets:A(),collateralAssets:A(),shares:A(),maxRepayAssets:A(),maxLtv:A(),deadline:A(),allocations:{type:"array",maxItems:4,items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string"},sourceMarketId:{type:"string"},assets:A(),maxPenaltyAssets:A()}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(p);if(await n.getChainId()!==p||typeof r!="string"||!xt.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(P=>!l.includes(P)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,d]=await Promise.all([n.readContract({address:pe,abi:Ne,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:pe,abi:Ne,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(ie(u)!==U||ie(d)!==bt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async P=>{if(typeof P!="string"||!W(P))throw new i("Choose a verified Morpho market with a supported exit.");let D=await n.readContract({address:U,abi:O,functionName:"idToMarketParams",args:[P],blockNumber:a.number}),$={loanToken:ie(D[0]),collateralToken:ie(D[1]),oracle:ie(D[2]),irm:ie(D[3]),lltv:D[4]};if(!E(be({...$,lltv:String($.lltv)}),P))throw new i("Blue bundle market identity mismatch.");return $},c=await m(t.marketId),f=r==="migrateBorrowPosition"?await m(t.destinationMarketId):c;if(c.loanToken!==f.loanToken||c.collateralToken!==f.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:U,abi:O,functionName:"isAuthorized",args:[s,pe],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${pe}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),w=t.shares===void 0?0n:N(t.shares,!0),h=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>f.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(w===0n)||r==="supplyCollateralAndBorrow"&&h===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&w>0n||b===0n&&w===0n&&h===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],I=0n;for(let P of k){if(!P||typeof P!="object"||Array.isArray(P)||Object.keys(P).some(Ve=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Ve)))throw new i("Unsupported bundled allocation input.");let D=P,$=await wt(e,{vault:D.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has($.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add($.definition.vault.toLowerCase());let j=N(D.assets),S=N(D.maxPenaltyAssets,!0);if(!$.permission||j>=1n<<128n||j>$.headroom||$.penalty>10n**18n||$.asset.address!==f.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(j*$.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");I+=B;let Te=D.sourceMarketId===void 0,ee=Te?void 0:$.sources.find(Ve=>E(Ve.id,String(D.sourceMarketId)));if(Te?!$.canIdle||j>$.data.idle:!ee||!ee.canPull||j>ee.capacity||j>$.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:$.definition.vault,adapter:$.target.adapter,marketParams:$.params,sourceAdapter:ee?.adapter??fe,sourceMarketParams:ee?aa(na,ee.data)[0]:$.params,assets:j,penalty:$.penalty,fromIdle:Te})}let M,C,v,x=0n;if(r==="supply")M="blueBundlesV1Supply",v=c.loanToken,x=b,C=[c,b,Qe,0n,fe,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[c,b,w,Oe,T,0n,fe,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",v=c.collateralToken,x=h,I>=b&&I>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[c,h,b,y,Qe,Oe,T,0n,fe,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",v=c.loanToken,x=N(t.maxRepayAssets,!0),b>x||w>0n&&x===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[c,b,w,x,h,y,Qe,Oe,0n,fe,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[c,f,y,Oe,T,0n,fe,o];let G=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${I} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${x}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...v&&x?[e.approval(v,pe,x.toString(),p)]:[],e.unsignedTx({to:pe,data:oa({abi:Ne,functionName:M,args:C}),value:"0",chainId:p,description:G})],H=await e.preview(Z,s),F=new Map;for(let P of H.changes)if(BigInt(P.amount)<0n){let D=P.token.address.toLowerCase();F.set(D,(F.get(D)??0n)-BigInt(P.amount))}if([...F].some(([P,D])=>!v||P!==v.toLowerCase()||D>x))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:G}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Mt,decodeAbiParameters as sa,encodeAbiParameters as $t,encodeFunctionData as Xe,erc20Abi as Pt,getAddress as K,keccak256 as Je,zeroAddress as we,zeroHash as ia}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),la=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),Ze=ae.find(e=>e.name==="take"),vt=[Ze.inputs[0]],da=[Ze.inputs[0].components[0]];function Ct(e){let t=Je(Mt(["0x600b380380600b5f395ff3",$t(da,[e])]));return Je(Mt(["0xff",e.midnight,ia,t]))}var le=10n**18n,Lt=(e,t)=>(e+(t-1n)/2n)/t;function Dt(e){if(e<0n)return 10n**36n/Dt(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*le),l=n*r/(3n*le);return le+r+n+l<<s}function ca(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Lt(Lt(10n**36n,le+Dt(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function Ge(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function Ye(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ua=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ut=e=>{async function t(n,l){let a=Ge(n,32),o=e.clientFor(p);if(await o.getChainId()!==p)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),d=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await d("toMarket",[a]);if(m.chainId!==BigInt(p)||K(m.midnight)!==Y||!E(Ct(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![V[p].tokens.USDG.address,V[p].tokens.WETH.address].some(k=>E(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[f,b,w,h]=await Promise.all([d("position",[a,l]),d("updatePositionView",[m,a,l]),d("marketState",[a]),d("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Pt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Pt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:p}};return{id:a,rpc:o,block:u,market:m,read:d,token:y,loan:await y(m.loanToken),position:Ye(f,6),updated:Ye(b,3),state:Ye(w,13),healthy:h}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,d)=>{try{if(q(d),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,d)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string"}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,c)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(c)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],d=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,c)=>[m,K(String(d[c]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:p,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ua(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string"},units:A(),maxAssets:A(),minAssets:A()},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=Ge(n.offer),[o]=sa(vt,a);if(!E($t(vt,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Ct(o.market),l),d=N(n.units),m=N(n.maxAssets,!0),c=N(n.minAssets,!0),f=Ge(n.ratifierData);if(d>=1n<<128n||E(o.maker,l)||o.callback!==we||o.callbackData!=="0x"||!la.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==we||!o.buy&&o.receiverIfMakerIsSeller===we)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&d>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),w=ca(o.tick);if(b>w&&o.buy)throw new i("Settlement fee exceeds the offer price.");let h=o.buy?w-b:w,y=h+b,k=P=>o.buy?P/le:(P+le-1n)/le,g=k(d*y),T=k(d*h);if(o.buy?T<c||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let I=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||I+(o.maxAssets?o.buy?g:T:d)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[Ze.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],v=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,f,l],blockNumber:u.block.number});if(M!==!0||v!==Je(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let x=Xe({abi:ae,functionName:"take",args:[o,f,d,l,o.buy?l:we,we,"0x"]}),G=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${d} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),p)],e.unsignedTx({to:Y,data:x,value:"0",chainId:p,description:G})],H=await r(Z,l,G),F=H.preview.changes.filter(P=>P.token.chainId===p&&E(P.token.address,u.loan.address)).reduce((P,D)=>P+BigInt(D.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string"},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"]},amount:A(),collateralIndex:{type:"integer",minimum:0,maximum:127}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,d,m=a.loan,c=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(c=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,c,l]}else{if(c=N(n.amount),c>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let w=BigInt(String(n.collateralIndex)),h=await a.token(a.market.collateralParams[Number(w)].token);if(m=h,o==="withdrawCollateral"&&c>await a.read("collateral",[a.id,l,w]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,w,c,l]:[a.market,w,c,l,l],o==="supplyCollateral"&&(d=h)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&c>a.position[4]||o==="withdraw"&&(c>a.updated[0]||c>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,c,l,we,"0x"]:[a.market,c,l,l],o==="repay"&&(d=a.loan)}}let f=`Midnight ${o}: ${c} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...d?[e.approval(d.address,Y,c.toString(),p)]:[],e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:String(o),args:u}),value:"0",chainId:p,description:f})];return r(b,l,f)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"]},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(f=>f.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let d=e.clientFor(p);if(await d.getChainId()!==p)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((f,b)=>{let w=n.values[b];if(f.type==="bool"){if(typeof w!="boolean")throw new i("Use boolean management values.");return w}if(f.type==="address")return Ue(w,"Use explicit management addresses.",De);if(f.type==="bytes32")return Ge(w,32);if(/^uint/.test(f.type)){let h=N(w,!0);if(h>=1n<<BigInt(f.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return h}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!E(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let f=await d.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof f!="string"||K(f)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let c=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:o,args:m}),value:"0",chainId:p,description:c})],l,c)})]}};import{decodeAbiParameters as oe,encodeAbiParameters as ma,encodeFunctionData as R,erc20Abi as et,getAddress as L,isAddress as Re,keccak256 as fa,parseAbi as Ee,parseAbiParameters as J}from"viem";var Pe="morpho",pa="https://api.morpho.org/graphql",U=L(V[p].morpho.morpho_blue.address),ba=L(V[p].morpho.adaptive_curve_irm.address),wa=L(V[p].morpho.USDG.address),de=L(V[p].morpho.WETH.address),ha=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],ka={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},tt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],ya=new Map(tt.map(e=>[e.marketId.toLowerCase(),e]));function W(e){return ya.get(e.toLowerCase())}function ot(e){let t=W(e);return t?{actions:"enabled",label:t.label,source:ka[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var Bt=20,ve=120n,_e=1000000n,He=1n,he=10n**18n,ga=10n**36n,Et=(1n<<128n)-1n,Sa=(1n<<256n)-1n,X=Ee(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),Aa=Ee(["function price() view returns (uint256)"]),Ia=Ee(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_t=Ee(["function deposit() payable"]);function ce(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ce(e,t){return e===0n?0n:(e+t-1n)/t}function xa(e,t,s){return e*(s+_e)/(t+He)}function Ta(e,t,s){return Ce(e*(s+_e),t+He)}function rt(e,t,s){return e*(t+He)/(s+_e)}function ne(e,t,s){return Ce(e*(t+He),s+_e)}function ke(e,t,s){return e*t/ga*s/he}function Ma(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function ye(e,t){let s=[],r={};for(let n of t.changes){let l=Ma(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Ht(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function qe(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Re(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Me(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=he)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function be(e){let t=qe(e),s=ma(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return fa(s)}function at(e){let t=e.toLowerCase();return t===dt.toLowerCase()||t===ct.toLowerCase()||t===te.toLowerCase()}function ge(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function re(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function qt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=p){if(q(t),at(t))return{...ut,chainId:s};let r=L(t),n=r.toLowerCase();if(s===p){if(n===wa.toLowerCase())return mt;if(n===de.toLowerCase())return ft}let[l,a]=await Promise.all([re(e,r,R({abi:et,functionName:"symbol"})),re(e,r,R({abi:et,functionName:"decimals"}))]),[o]=oe(J("string"),l),[u]=oe(J("uint8"),a);return{address:r,symbol:qt(o),decimals:Number(u),chainId:s}}async function Ft(e,t){let s=await re(e,U,R({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=oe(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function jt(e,t){let s=await re(e,U,R({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=oe(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Se(e,t,s){let r=await re(e,U,R({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=oe(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Fe(e,t){let s=await re(e,L(t),R({abi:Aa,functionName:"price"})),[r]=oe(J("uint256"),s);return r}async function Pa(e,t,s){if(t.irm===te)return 0n;let r=await re(e,L(t.irm),R({abi:Ia,functionName:"borrowRateView",args:[t,s]})),[n]=oe(J("uint256"),r);return n}function je(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ce(n*n,2n*he),a=Ce(l*n,3n*he);return e.totalBorrowAssets+Ce(e.totalBorrowAssets*(n+l+a),he)}async function Le(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Pa(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:je(s,l,o),accruedThrough:o,rate:l}}async function Vt(e,t,s){let r=await re(e,L(t),R({abi:et,functionName:"balanceOf",args:[L(s)]})),[n]=oe(J("uint256"),r);return n}async function ue(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?qe(n):void 0,a=l?be(l):void 0,o=r!==void 0?Ht(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!W(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[d,m]=await Promise.all([Ft(e,u),jt(e,u)]);if(d.loanToken===te||d.collateralToken===te||d.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${p}.`);let c=be(d);if(c.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${c}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===d.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===d.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===d.oracle.toLowerCase()&&l.irm.toLowerCase()===d.irm.toLowerCase()&&l.lltv===d.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:d,marketState:m}}function Ae(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Me(t);if(s<=0n||s>Et)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function Ie(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function va(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p),{marketId:a,marketParams:o}=await ue(l,t,!0),u=await Q(l,o.collateralToken,p),d=o.collateralToken.toLowerCase()===de.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,c=z("wrapNative",t.wrapNative)===!0||m!==void 0&&at(m);if(m&&!at(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(c&&!d)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let f=Ae(t),b=f.toString(),w=e.formatAmount(b,u.decimals),h=[];c&&h.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:b,description:`Wrap ${w} ETH into WETH at ${de}.`})),h.push(e.approval(o.collateralToken,U,b,p)),h.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supplyCollateral",args:[o,f,n,"0x"]}),value:"0",description:`Supply ${w} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply_collateral",chainId:p,marketId:a,marketParams:ce(o),collateralToken:u,assets:b,formattedAssets:w,onBehalf:n,txs:h,summary:`${c?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ca(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.loanToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=Ae(t),h=w.toString(),y=e.formatAmount(h,m.decimals),k=d.totalSupplyAssets>d.totalBorrowAssets?d.totalSupplyAssets-d.totalBorrowAssets:0n;if(w>k)throw new i(`Insufficient market liquidity: requested ${h} base units, available ${k.toString()} base units.`);let g=ke(c.collateral,f,u.lltv),T=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(c.collateral===0n||T+w>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+w).toString()} exceeds max borrow ${g.toString()} base units.`);let I=Ta(w,b.totalBorrowAssets,d.totalBorrowShares),C=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"borrow",args:[u,w,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${h} base units) from Morpho market ${o}.`})],v=await e.preview(C,r),{formattedChanges:x,formattedNetOutflows:G}=ye(e,v);return{action:"morpho_borrow",chainId:p,marketId:o,marketParams:ce(u),loanToken:m,assets:h,formattedAssets:y,borrowShares:I.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:v,formattedChanges:x,formattedNetOutflows:G}}async function La(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p);if(t.shares!==void 0){let x=Me(t.shares);if(x<=0n||x===Sa||x>Et)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(z("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await ue(l,t,!0),[d,m,c]=await Promise.all([Q(l,o.loanToken,p),Se(l,a,n),Vt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let f=0n,b=0n;if(z("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let x=Me(t.shares);if(x>m.borrowShares)throw new i(`Repay shares (${x.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=x}else f=Ae(t);let w=b>0n?await Le(l,o,u,ve):void 0,h=b>0n?ne(b,w.totalBorrowAssets,u.totalBorrowShares):f;if(c<h)throw new i(`Insufficient loan token balance for repayment: wallet holds ${c.toString()} base units, but ${h.toString()} base units are required (including accrued interest).`);let y=h.toString(),k=e.formatAmount(y,d.decimals),g=e.approval(o.loanToken,U,y,p),T=e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"repay",args:[o,f,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${d.symbol}) on Morpho market ${a}.`:`Repay ${k} ${d.symbol} (${f.toString()} base units) on Morpho market ${a}.`}),I=[g,T],M=await e.preview(I,r),{formattedChanges:C,formattedNetOutflows:v}=ye(e,M);return{action:"morpho_repay",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,repayAssets:f.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:ve.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:I,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${d.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${ve} seconds.`:`Repay ${k} ${d.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:v}}async function $a(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.collateralToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=z("withdrawAll",t.withdrawAll)===!0?c.collateral:Ae(t);if(w<=0n||w>c.collateral)throw new i(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${c.collateral.toString()} base units.`);if(c.borrowShares>0n){let C=c.collateral-w,v=ke(C,f,u.lltv),x=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(x>v)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${v.toString()} would fall below current debt ${x.toString()} base units.`)}let h=w.toString(),y=e.formatAmount(h,m.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdrawCollateral",args:[u,w,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${h} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw_collateral",chainId:p,marketId:o,marketParams:ce(u),collateralToken:m,assets:h,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function Da(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),{marketId:l,marketParams:a,marketState:o}=await ue(n,t,!0),u=z("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==de.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let d=Ae(t),m=d.toString(),[c,f]=await Promise.all([Q(n,a.loanToken,p),u?Promise.resolve(d):Vt(n,a.loanToken,r)]);if(f<d)throw new i(`Insufficient ${c.symbol} balance to lend: wallet holds ${f.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,c.decimals),w=[];u&&w.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${de}.`})),w.push(e.approval(a.loanToken,U,m,p)),w.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supply",args:[a,d,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${c.symbol} (${m} base units) to Morpho market ${l}.`}));let h=xa(d,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply",chainId:p,marketId:l,marketParams:ce(a),loanToken:c,assets:m,formattedAssets:b,supplySharesEstimated:h.toString(),onBehalf:r,oak:ot(l),txs:w,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${c.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ua(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),l=z("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await ue(n,t,!0),[d,m]=await Promise.all([Q(n,o.loanToken,p),Se(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${d.symbol} on Morpho market ${a}.`);let c=rt(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),f=l?0n:Ae(t),b=l?m.supplyShares:0n;if(!l&&f>c)throw new i(`Withdrawal exceeds the lent balance: requested ${f.toString()} base units, position holds about ${c.toString()}. Use withdrawAll for a full exit.`);let w=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,h=l?c:f;if(h>w)throw new i(`Insufficient market liquidity: withdrawing ${h.toString()} base units needs idle assets, but only ${w.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(h.toString(),d.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdraw",args:[o,f,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${d.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${d.symbol} (${f.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,withdrawAssets:f.toString(),withdrawShares:b.toString(),estimatedAssets:h.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${d.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${d.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function zt(e,t,s){let r=await e.http(pa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function Wt(e){let t=`query Markets($chainId: Int!) {
|
|
2
2
|
markets(first: 1000, where: { chainId_in: [$chainId] }) {
|
|
3
3
|
items {
|
|
4
4
|
marketId chain { id } lltv listed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as N}from"./XW7RH7YY.js";import{a as E}from"./
|
|
1
|
+
import{a as N}from"./XW7RH7YY.js";import{a as E}from"./XUJSQV52.js";import{b as q,c as _,d as O,e as R}from"./DVKDWXEJ.js";import{a as I}from"./JRVTSGAT.js";import{c as M}from"./EC5W3UZD.js";import{b as G}from"./AXYOJBX6.js";import{a as b}from"./6IM6A5VA.js";import{a as x}from"./RETS2ZEK.js";import{a as o,d as P,i as U,j as y}from"./XPFVT2EA.js";import{a as r}from"./5YS5V2LK.js";import{encodeFunctionData as g,erc20Abi as k,parseAbi as L}from"viem";var i=U[o].vaults.steakhouse.address,j=(1n<<256n)-1n,l=L(["function asset() view returns (address)","function totalAssets() view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256 assets)","function previewWithdraw(uint256 assets) view returns (uint256 shares)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]);function A(e){if(typeof e!="bigint"||e<0n||e>j)throw new r("The vault returned an invalid base-unit amount.");return e}function T(e){if(typeof e!="string")throw new r("Amount must be an integer string in base units.");let c=x(e);if(c===0n)throw new r("Amount must be positive.");if(c>j)throw new r("Amount exceeds the uint256 range.");return c}function D(e,c,h=!1){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(w=>!c||!["amount",...h?["force","maxPenaltyAssets","minAmountOut"]:[]].includes(w)))throw new r("Unexpected Steakhouse argument.")}var W=e=>{async function c(t){try{return await t()}catch(s){throw new r(e.plainError(s))}}async function h(){let t=e.clientFor(o);if(await t.getChainId()!==o)throw new r("Steakhouse requires chain 4663.");let s=await t.readContract({address:i,abi:l,functionName:"asset"});if(typeof s!="string"||s.toLowerCase()!==y.toLowerCase())throw new r("The Steakhouse vault asset does not match USDG on chain 4663.");let[a,n]=await Promise.all([t.readContract({address:y,abi:k,functionName:"decimals"}),t.readContract({address:i,abi:k,functionName:"decimals"})]);if(a!==P||!Number.isInteger(n)||n<0||n>255)throw new r("The vault returned invalid asset or share decimals.");return{client:t,asset:{address:y,symbol:"USDG",decimals:a,chainId:o},shares:{address:i,symbol:"steakUSDG",decimals:n,chainId:o}}}async function w(t,s){return A(await t.readContract({address:i,abi:k,functionName:"balanceOf",args:[s]}))}async function C(t,s,a){let n=await e.preview(t,s);if(n.changes.length===0)throw new r("The Steakhouse simulation returned no token balance changes.");let u=n.changes.map(({token:m,amount:d})=>{let f=d.startsWith("-"),p=e.formatAmount(f?d.slice(1):d,m.decimals);return`${f?"-":""}${p} ${m.symbol} (${m.address}, chain ${m.chainId}, decimals ${m.decimals})`});return{txs:t,summary:`${a} ${n.summary} Changes: ${u.join("; ")}.`}}return{tools:[_(e,"steakhouse_details",i),I(e,"steakhouse_analytics",i),E(e,"steakhouse_manage",i),...N(e,"steakhouse",i),{name:"steakhouse_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async t=>c(async()=>{D(t,!1);let{client:s,asset:a,shares:n}=await h(),u=A(await s.readContract({address:i,abi:l,functionName:"totalAssets"}));return[{name:"Steakhouse USDG",vault:n,asset:a,totalAssets:{token:a,amount:u.toString()}}]})},{name:"steakhouse_deposit",inputSchema:$(!1),execute:async(t,s)=>c(async()=>{D(t,!0);let a=T(t.amount);b(s);let{asset:n}=await h(),u=[e.approval(n.address,i,a.toString(),o),e.unsignedTx({to:i,data:g({abi:l,functionName:"deposit",args:[a,s]}),value:"0",chainId:o,description:`Deposit ${e.formatAmount(a.toString(),n.decimals)} USDG into Steakhouse.`})];return C(u,s,"Approve the exact USDG amount, then deposit into Steakhouse.")})},{name:"steakhouse_withdraw",inputSchema:{...$(!0),properties:{...$(!0).properties,force:{type:"boolean",description:"Explicitly plan a full Morpho V2 force exit with penalty disclosure."},maxPenaltyAssets:{type:"string",pattern:"^[0-9]+$"},minAmountOut:{type:"string",pattern:"^[0-9]+$"}}},execute:async(t,s)=>c(async()=>{D(t,!0,!0);let a=t.amount==="max"?null:T(t.amount);b(s);let{client:n,asset:u,shares:m}=await h(),d=await w(n,s);if(d===0n)throw new r("The wallet has no Steakhouse shares to withdraw.");if(t.force!==void 0&&typeof t.force!="boolean")throw new r("force must be a boolean.");if(t.force===!0){if(a!==null)throw new r("Force exit currently requires amount max.");let p=M(t.maxPenaltyAssets),F=T(t.minAmountOut),v=await q(e,n,i,s,d,p),S=await e.preview([v.tx],s);return R(S.changes,i,d,F),{txs:[v.tx],preview:S,summary:`${O(v.plan)} ${S.summary}`}}if(t.maxPenaltyAssets!==void 0||t.minAmountOut!==void 0)throw new r("Penalty and output limits require force true.");let f;if(a===null)f=e.unsignedTx({to:i,data:g({abi:l,functionName:"redeem",args:[d,s,s]}),value:"0",chainId:o,description:`Redeem all ${e.formatAmount(d.toString(),m.decimals)} steakUSDG shares.`});else{let p=A(await n.readContract({address:i,abi:l,functionName:"previewWithdraw",args:[a]}));if(p===0n||p>d)throw new r("The withdrawal exceeds the available share balance or has an invalid share quote.");f=e.unsignedTx({to:i,data:g({abi:l,functionName:"withdraw",args:[a,s,s]}),value:"0",chainId:o,description:`Withdraw ${e.formatAmount(a.toString(),u.decimals)} USDG from Steakhouse.`})}return C([f],s,a===null?"Redeem the current full share balance from Steakhouse.":"Withdraw the requested USDG amount from Steakhouse.")})}],positions:t=>c(async()=>{b(t);let{client:s,asset:a,shares:n}=await h(),u=await w(s,t);if(u===0n)return[];let m=A(await s.readContract({address:i,abi:l,functionName:"convertToAssets",args:[u]}));return[{module:"steakhouse",id:`${o}:${i.toLowerCase()}`,chainId:o,assets:[{token:a,amount:m.toString()}],description:`${e.formatAmount(u.toString(),n.decimals)} steakUSDG shares (${i}, chain ${o}, decimals ${n.decimals}); USDG conversion is indicative, not guaranteed exit liquidity.`}]})}};function $(e){return{type:"object",additionalProperties:!1,required:["amount"],properties:{amount:{type:"string",pattern:e?"^(?:[0-9]+|max)$":"^[0-9]+$",description:`USDG base-unit integer string (6 decimals)${e?", or max to redeem every share":""}.`}}}}var te=e=>G("steakhouse",[W(e)]);export{W as a,te as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as M}from"./NCQFWPAW.js";import{a as v}from"./65QFM4JU.js";import{K as A}from"./5H3MQWH7.js";import{c as k}from"./HZUWK5B2.js";import{a as $}from"./6IM6A5VA.js";import{a as x}from"./UWOFA6GV.js";import{d as F,g as U,i as _}from"./73N3TOJL.js";import{a as N}from"./XPFVT2EA.js";import{a as n}from"./5YS5V2LK.js";import{encodeFunctionData as H,erc20Abi as P,getAddress as y,zeroAddress as q}from"viem";var B={genesis:y("0x575b7B7c97Ef3E21C82DAeB427899d583e1E913f"),bond:y("0xff32a969A0c567129eECD926D04657728E1980C1"),inverse:y("0x92166e94Eea5B7799b761653881692f881dFC4C9"),treasury:y("0x04822Ea321A0DEE6F40656172F29312104855d66"),pteam:y("0x650F58079dAa17ee28928c2F92d22291d038B2B0"),rwa:y("0x99B6eE6eDe47d9a8a9bfd03F728a99B789df1961"),premium:y("0x346e1a31171A0f7aC73909010b5435768d3B5462"),tax:y("0x086C58400b8708Ef993f256E12e752dcF0AC918e")},j=y("0x59F95461E68e0c77605299791E1449f175165B54"),D={genesis:["purchase","finalize","refund","claim"],bond:["deposit","redeem"],inverse:["swap"],treasury:["rebalanceToMorpho","rebalanceFromMorpho","mintNet","spendUsdg"],pteam:["exercise"],rwa:["redeem","depositInventory","pokeHwm","setDiscount","setInventoryMax","setHalt","setMenu","skim"],premium:["execute"],tax:["convert"]},G={genesis:["wired","finalized","finalizeTime","saleStart","saleDeadline","raisedRaw","totalRaised","registryLength"],bond:["wired","enabled","startTime","marketCount"],inverse:["active","price","capacityRemaining","spreadBps"],treasury:["wired","rfv","backingPerToken","liquidUsdg","morphoAssets","polRfv","morphoCapBps","morphoVault","canonicalPair"],pteam:["wired","holder","vestedFraction","exercisableNow","exercised","strikeWad","capBps","circulatingSupply","excludedFromFloat"],rwa:["manager","halted","inventory","inventoryMax","owedNet","bHwm","deskDiscountBps","VEST","MAX_DISCOUNT_BPS","INVENTORY_HARD_CAP","menu","routerSource","sleeve"],premium:["active","clipSize","lastExecuteAt","premiumThresholdWad","router","pairContract"],tax:["wired","pendingNet","teamBps","treasuryBps","teamWallet","router","pairContract"]},T=b=>JSON.parse(JSON.stringify(b,(S,I)=>typeof I=="bigint"?I.toString():I));function h(b){return _(b,"Provide a checksummed address.",F)}var ne=b=>{async function S(t){if(typeof t!="string"||!Object.hasOwn(B,t))throw new n("Choose a published NetNet financial product.");let c=t,e=B[c],d=M[c],m=b.clientFor(N);if(await m.getChainId()!==N)throw new n("NetNet requires chain 4663.");let a=await m.getBlock(),s=(g,E=[])=>m.readContract({address:e,abi:d,functionName:g,args:E,blockNumber:a.number}),[i,o,p,f]=await Promise.all([s("net"),s("usdg"),m.readContract({address:v.address,abi:P,functionName:"decimals",blockNumber:a.number}),m.readContract({address:k.address,abi:P,functionName:"decimals",blockNumber:a.number})]);if(h(i)!==v.address||h(o)!==k.address||p!==v.decimals||f!==k.decimals)throw new n("NetNet financial token pins or decimals do not match the deployment.");return{product:c,contract:e,abi:d,rpc:m,block:a,read:s}}let I=(t,c,e,d)=>({name:t,inputSchema:{type:"object",properties:c,required:e,additionalProperties:!1},execute:async(m,a)=>{try{if($(a),Object.keys(m).some(s=>!Object.hasOwn(c,s)))throw new n("Unsupported NetNet financial argument.");return await d(m,a)}catch(s){throw new n(b.plainError(s))}}}),C={type:"string",enum:Object.keys(B)};return{tools:[I("netnet_financial_status",{product:C,offset:{type:"integer",minimum:0},limit:{type:"integer",minimum:1,maximum:50}},["product"],async(t,c)=>{let e=await S(t.product),d=G[e.product],m=t.offset??0,a=t.limit??20;if(!Number.isSafeInteger(m)||Number(m)<0||!Number.isSafeInteger(a)||Number(a)<1||Number(a)>50)throw new n("Use a nonnegative offset and limit 1..50.");let s=await Promise.all(d.map(async o=>{try{return[o,{value:T(await e.read(o))}]}catch(p){return[o,{unavailable:b.plainError(p)}]}})),i={};if(e.product==="genesis")for(let o of["purchasedRaw","purchasedNetOf","claimedNet","claimableNetOf"])i[o]=T(await e.read(o,[c]));if(e.product==="bond"||e.product==="rwa"){i.pending=T(await e.read("pendingFor",[c]));let o=await e.read("noteCount",[c]);if(typeof o!="bigint"||o<0n)throw new n("Invalid NetNet note count.");let p=o<BigInt(Number(m)+Number(a))?o:BigInt(Number(m)+Number(a));i.noteCount=o.toString(),i.notes=await Promise.all(Array.from({length:Math.max(0,Number(p-BigInt(Number(m))))},async(f,g)=>({id:String(Number(m)+g),note:T(await e.read(e.product==="bond"?"notes":"noteAt",[c,BigInt(Number(m)+g)]))}))),i.nextOffset=p<o?p.toString():null,e.product==="bond"&&(i.markets=await Promise.all([0n,1n].map(async f=>{try{return{id:f.toString(),quoteToken:h(await e.read("quoteToken",[f])),priceWad:String(await e.read("bondPrice",[f]))}}catch(g){return{id:f.toString(),unavailable:b.plainError(g)}}})))}return e.product==="treasury"&&(i.isMinter=await e.read("isMinter",[c]),i.isSpender=await e.read("isSpender",[c])),{chainId:N,contract:e.contract,product:e.product,blockNumber:String(e.block.number),tokens:[v,k],metrics:Object.fromEntries(s),wallet:i,units:"Raw token amounts use each token\u2019s decimals. Prices, NAV, reserve values and capacityRemaining use 18-decimal USDG WAD. Note timestamps are Unix seconds.",operations:D[e.product],caveat:"An unavailable metric is not zero. Formulaic eligibility, oracle liveness, caps and vesting are checked by the action preview. RWA entry/router calldata and initial deployment wiring remain unsupported."}}),I("netnet_financial_action",{product:C,operation:{type:"string",enum:[...new Set(Object.values(D).flat())]},amount:x(),minAmountOut:x(),maxPriceWad:x(),maxPayment:x(),marketId:{type:"integer",enum:[0,1]},recipient:{type:"string"},halted:{type:"boolean"},token:{type:"string"},noteIds:{type:"array",maxItems:50,items:x()},menu:{type:"array",maxItems:32,items:{type:"object"}}},["product","operation"],async(t,c)=>{let e=await S(t.product),d=t.operation;if(typeof d!="string"||!D[e.product].includes(d))throw new n("This operation is not supported by the selected financial product.");let m=new Set(["product","operation"]),a=[],s,i=0n,o="",p=(...r)=>r.forEach(u=>m.add(u)),f=()=>(p("amount"),A(t.amount)),g=()=>(p("minAmountOut"),A(t.minAmountOut));if(e.product==="genesis"){if(d==="purchase"&&(i=f(),s=k,a=[i],o="Founding subscription; NET is claimable only after successful finalization and vesting. A failed sale requires refund."),d==="claim"&&await e.read("claimableNetOf",[c])===0n)throw new n("No vested founding NET is claimable by this wallet.")}else if(e.product==="bond")if(d==="deposit"){if(p("marketId","maxPriceWad"),t.marketId!==0&&t.marketId!==1)throw new n("Bond marketId must be 0 (USDG) or 1 (canonical LP).");let r=BigInt(t.marketId);if(h(await e.read("quoteToken",[r]))!==(r===0n?k.address:j))throw new n("Bond quote token is not the pinned USDG or canonical LP.");i=f(),s=r===0n?k:{address:j,decimals:18,symbol:"NET/USDG LP",chainId:N};let l=A(t.maxPriceWad),w=await e.read("bondPrice",[r]);if(typeof w!="bigint"||w===0n||w>l)throw new n("Bond price exceeds maxPriceWad or is invalid.");a=[r,i,l,c],o="Payment is exchanged for a non-transferable NET note with two-day linear vesting. Redeem vested NET with the same product; payment cannot be withdrawn."}else a=[c];else if(e.product==="inverse"){if(i=f(),s=v,a=[i,g()],o="Purchased NET is burned permanently; USDG pays directly to this wallet. Capacity is denominated in USDG WAD, not raw USDG.",await e.read("active")!==!0)throw new n("NetNet buyback is inactive: oracle, finalization or capacity is unavailable.")}else if(e.product==="pteam"){if(h(await e.read("holder"))!==y(c))throw new n("This wallet is not the immutable pTEAM holder.");let r=f();if(p("maxPayment"),r>await e.read("exercisableNow"))throw new n("The NET exercise amount exceeds the vested cap.");let u=await e.read("strikeWad");if(i=(r*u/10n**BigInt(v.decimals)+10n**12n-1n)/10n**12n,i===0n||i>A(t.maxPayment))throw new n("The exercise payment exceeds maxPayment or rounds to zero.");s=k,a=[r],o=`Exercise pays ${i} USDG base units into treasury reserves and mints ${r} NET base units to the immutable holder. No withdrawal or exercise reversal exists.`}else if(e.product==="treasury"){let r=f();if(d==="mintNet"||d==="spendUsdg"){p("recipient");let u=h(t.recipient);if(await e.read(d==="mintNet"?"isMinter":"isSpender",[c])!==!0)throw new n("This wallet lacks the fixed NetNet treasury minter/spender role.");a=[u,r],o=`Protocol treasury operation sends ${r} base units to ${u}; it does not deposit into this wallet\u2019s savings.`}else a=[r],o="Permissionless protocol reserve rebalance; assets remain owned by the NetNet treasury. The deployed fraction is constrained by the immutable cap."}else if(e.product==="rwa"){if(["depositInventory","setDiscount","setInventoryMax","setHalt","setMenu"].includes(d)&&h(await e.read("manager"))!==y(c))throw new n("This wallet lacks the immutable RWA manager role.");if(d==="redeem")if(p("noteIds"),t.noteIds===void 0)a=[c];else{if(!Array.isArray(t.noteIds)||!t.noteIds.length||t.noteIds.length>50)throw new n("Provide 1..50 unique note IDs.");let u=t.noteIds.map(w=>A(w,!0));if(new Set(u.map(String)).size!==u.length)throw new n("Note IDs must be unique.");let l=await e.read("noteCount",[c]);if(u.some(w=>w>=l))throw new n("RWA note ID is out of range.");a=[c,u]}else if(d==="setHalt"){if(p("halted"),typeof t.halted!="boolean")throw new n("Provide halted as a boolean.");a=[t.halted]}else if(d==="setMenu"){if(p("menu"),!Array.isArray(t.menu)||!t.menu.length||t.menu.length>32)throw new n("Provide 1..32 explicit RWA menu entries.");let u=t.menu.map(l=>{if(!l||typeof l!="object"||Array.isArray(l)||Object.keys(l).some(z=>!["token","feed","targetWeightBps","active"].includes(z)))throw new n("Invalid RWA menu fields.");let w=l;if(typeof w.active!="boolean")throw new n("RWA active must be boolean.");return{token:h(w.token),feed:h(w.feed),targetWeightBps:A(w.targetWeightBps,!0),active:w.active}});if(new Set(u.map(l=>l.token)).size!==u.length||u.reduce((l,w)=>l+w.targetWeightBps,0n)!==10000n||u.some(l=>l.active&&(l.token===q||l.feed===q)))throw new n("RWA menu tokens must be unique, weights sum to 10000, active feeds/tokens nonzero.");a=[u],o=`Replace the complete RWA equity menu: ${JSON.stringify(T(u))}.`}else if(d==="skim")p("token"),a=[h(t.token)],o=`Sweep eligible stray assets to sleeve ${h(await e.read("sleeve"))}, not to this wallet.`;else if(d!=="pokeHwm"){let u=f();if(a=[u],d==="depositInventory"&&(s=v,i=u,o="Inventory funding is one-way. The manager cannot withdraw these NET; they are committed to bond obligations."),d==="setDiscount"&&u>await e.read("MAX_DISCOUNT_BPS")||d==="setInventoryMax"&&u>await e.read("INVENTORY_HARD_CAP"))throw new n("RWA setting exceeds its immutable maximum.")}}else e.product==="premium"?(a=[g()],o="Permissionless mint-and-sell keeper operation; all sale proceeds go to NetNet treasury. The caller receives no reward."):(a=[f(),g()],o="Convert NET already owned by the tax collector. Proceeds split to treasury and team; the caller receives no reward and supplies no NET.");if(Object.keys(t).some(r=>!m.has(r)))throw new n("Unexpected fields for this NetNet operation.");if(s&&await e.rpc.readContract({address:s.address,abi:P,functionName:"balanceOf",args:[c],blockNumber:e.block.number})<i)throw new n(`Top up ${s.symbol}: needs ${i} base units.`);let E=`NetNet ${e.product}.${d}, contract ${e.contract}, chain ${N}, values ${JSON.stringify(T(a))}. ${s?`Approve exactly ${i} ${s.symbol} base units (${s.address}, decimals ${s.decimals}). `:""}${o}`,O=[...s?[b.approval(s.address,e.contract,i.toString(),N)]:[],b.unsignedTx({to:e.contract,data:H({abi:e.abi,functionName:d,args:a}),value:"0",chainId:N,description:E})],R=await b.preview(O,c),W=0n;for(let r of R.changes){if(!/^-?\d+$/.test(r.amount))throw new n("Invalid NetNet preview amount.");if(BigInt(r.amount)<0n&&(W-=BigInt(r.amount)),BigInt(r.amount)<0n&&(!s||r.token.chainId!==N||!U(r.token.address,s.address)||r.token.decimals!==s.decimals||-BigInt(r.amount)>i))throw new n("NetNet preview spends outside the exact input budget.")}if(W>i)throw new n("NetNet preview exceeds the aggregate input budget.");return{txs:O,preview:R,summary:E}})]}};export{B as a,j as b,ne as c};
|
|
1
|
+
import{a as M}from"./NCQFWPAW.js";import{a as v}from"./65QFM4JU.js";import{K as A}from"./O7PQDUVT.js";import{c as k}from"./T3MGNKA6.js";import{a as $}from"./6IM6A5VA.js";import{a as x}from"./UWOFA6GV.js";import{d as F,g as U,i as _}from"./73N3TOJL.js";import{a as N}from"./XPFVT2EA.js";import{a as n}from"./5YS5V2LK.js";import{encodeFunctionData as H,erc20Abi as P,getAddress as y,zeroAddress as q}from"viem";var B={genesis:y("0x575b7B7c97Ef3E21C82DAeB427899d583e1E913f"),bond:y("0xff32a969A0c567129eECD926D04657728E1980C1"),inverse:y("0x92166e94Eea5B7799b761653881692f881dFC4C9"),treasury:y("0x04822Ea321A0DEE6F40656172F29312104855d66"),pteam:y("0x650F58079dAa17ee28928c2F92d22291d038B2B0"),rwa:y("0x99B6eE6eDe47d9a8a9bfd03F728a99B789df1961"),premium:y("0x346e1a31171A0f7aC73909010b5435768d3B5462"),tax:y("0x086C58400b8708Ef993f256E12e752dcF0AC918e")},j=y("0x59F95461E68e0c77605299791E1449f175165B54"),D={genesis:["purchase","finalize","refund","claim"],bond:["deposit","redeem"],inverse:["swap"],treasury:["rebalanceToMorpho","rebalanceFromMorpho","mintNet","spendUsdg"],pteam:["exercise"],rwa:["redeem","depositInventory","pokeHwm","setDiscount","setInventoryMax","setHalt","setMenu","skim"],premium:["execute"],tax:["convert"]},G={genesis:["wired","finalized","finalizeTime","saleStart","saleDeadline","raisedRaw","totalRaised","registryLength"],bond:["wired","enabled","startTime","marketCount"],inverse:["active","price","capacityRemaining","spreadBps"],treasury:["wired","rfv","backingPerToken","liquidUsdg","morphoAssets","polRfv","morphoCapBps","morphoVault","canonicalPair"],pteam:["wired","holder","vestedFraction","exercisableNow","exercised","strikeWad","capBps","circulatingSupply","excludedFromFloat"],rwa:["manager","halted","inventory","inventoryMax","owedNet","bHwm","deskDiscountBps","VEST","MAX_DISCOUNT_BPS","INVENTORY_HARD_CAP","menu","routerSource","sleeve"],premium:["active","clipSize","lastExecuteAt","premiumThresholdWad","router","pairContract"],tax:["wired","pendingNet","teamBps","treasuryBps","teamWallet","router","pairContract"]},T=b=>JSON.parse(JSON.stringify(b,(S,I)=>typeof I=="bigint"?I.toString():I));function h(b){return _(b,"Provide a checksummed address.",F)}var ne=b=>{async function S(t){if(typeof t!="string"||!Object.hasOwn(B,t))throw new n("Choose a published NetNet financial product.");let c=t,e=B[c],d=M[c],m=b.clientFor(N);if(await m.getChainId()!==N)throw new n("NetNet requires chain 4663.");let a=await m.getBlock(),s=(g,E=[])=>m.readContract({address:e,abi:d,functionName:g,args:E,blockNumber:a.number}),[i,o,p,f]=await Promise.all([s("net"),s("usdg"),m.readContract({address:v.address,abi:P,functionName:"decimals",blockNumber:a.number}),m.readContract({address:k.address,abi:P,functionName:"decimals",blockNumber:a.number})]);if(h(i)!==v.address||h(o)!==k.address||p!==v.decimals||f!==k.decimals)throw new n("NetNet financial token pins or decimals do not match the deployment.");return{product:c,contract:e,abi:d,rpc:m,block:a,read:s}}let I=(t,c,e,d)=>({name:t,inputSchema:{type:"object",properties:c,required:e,additionalProperties:!1},execute:async(m,a)=>{try{if($(a),Object.keys(m).some(s=>!Object.hasOwn(c,s)))throw new n("Unsupported NetNet financial argument.");return await d(m,a)}catch(s){throw new n(b.plainError(s))}}}),C={type:"string",enum:Object.keys(B)};return{tools:[I("netnet_financial_status",{product:C,offset:{type:"integer",minimum:0},limit:{type:"integer",minimum:1,maximum:50}},["product"],async(t,c)=>{let e=await S(t.product),d=G[e.product],m=t.offset??0,a=t.limit??20;if(!Number.isSafeInteger(m)||Number(m)<0||!Number.isSafeInteger(a)||Number(a)<1||Number(a)>50)throw new n("Use a nonnegative offset and limit 1..50.");let s=await Promise.all(d.map(async o=>{try{return[o,{value:T(await e.read(o))}]}catch(p){return[o,{unavailable:b.plainError(p)}]}})),i={};if(e.product==="genesis")for(let o of["purchasedRaw","purchasedNetOf","claimedNet","claimableNetOf"])i[o]=T(await e.read(o,[c]));if(e.product==="bond"||e.product==="rwa"){i.pending=T(await e.read("pendingFor",[c]));let o=await e.read("noteCount",[c]);if(typeof o!="bigint"||o<0n)throw new n("Invalid NetNet note count.");let p=o<BigInt(Number(m)+Number(a))?o:BigInt(Number(m)+Number(a));i.noteCount=o.toString(),i.notes=await Promise.all(Array.from({length:Math.max(0,Number(p-BigInt(Number(m))))},async(f,g)=>({id:String(Number(m)+g),note:T(await e.read(e.product==="bond"?"notes":"noteAt",[c,BigInt(Number(m)+g)]))}))),i.nextOffset=p<o?p.toString():null,e.product==="bond"&&(i.markets=await Promise.all([0n,1n].map(async f=>{try{return{id:f.toString(),quoteToken:h(await e.read("quoteToken",[f])),priceWad:String(await e.read("bondPrice",[f]))}}catch(g){return{id:f.toString(),unavailable:b.plainError(g)}}})))}return e.product==="treasury"&&(i.isMinter=await e.read("isMinter",[c]),i.isSpender=await e.read("isSpender",[c])),{chainId:N,contract:e.contract,product:e.product,blockNumber:String(e.block.number),tokens:[v,k],metrics:Object.fromEntries(s),wallet:i,units:"Raw token amounts use each token\u2019s decimals. Prices, NAV, reserve values and capacityRemaining use 18-decimal USDG WAD. Note timestamps are Unix seconds.",operations:D[e.product],caveat:"An unavailable metric is not zero. Formulaic eligibility, oracle liveness, caps and vesting are checked by the action preview. RWA entry/router calldata and initial deployment wiring remain unsupported."}}),I("netnet_financial_action",{product:C,operation:{type:"string",enum:[...new Set(Object.values(D).flat())]},amount:x(),minAmountOut:x(),maxPriceWad:x(),maxPayment:x(),marketId:{type:"integer",enum:[0,1]},recipient:{type:"string"},halted:{type:"boolean"},token:{type:"string"},noteIds:{type:"array",maxItems:50,items:x()},menu:{type:"array",maxItems:32,items:{type:"object"}}},["product","operation"],async(t,c)=>{let e=await S(t.product),d=t.operation;if(typeof d!="string"||!D[e.product].includes(d))throw new n("This operation is not supported by the selected financial product.");let m=new Set(["product","operation"]),a=[],s,i=0n,o="",p=(...r)=>r.forEach(u=>m.add(u)),f=()=>(p("amount"),A(t.amount)),g=()=>(p("minAmountOut"),A(t.minAmountOut));if(e.product==="genesis"){if(d==="purchase"&&(i=f(),s=k,a=[i],o="Founding subscription; NET is claimable only after successful finalization and vesting. A failed sale requires refund."),d==="claim"&&await e.read("claimableNetOf",[c])===0n)throw new n("No vested founding NET is claimable by this wallet.")}else if(e.product==="bond")if(d==="deposit"){if(p("marketId","maxPriceWad"),t.marketId!==0&&t.marketId!==1)throw new n("Bond marketId must be 0 (USDG) or 1 (canonical LP).");let r=BigInt(t.marketId);if(h(await e.read("quoteToken",[r]))!==(r===0n?k.address:j))throw new n("Bond quote token is not the pinned USDG or canonical LP.");i=f(),s=r===0n?k:{address:j,decimals:18,symbol:"NET/USDG LP",chainId:N};let l=A(t.maxPriceWad),w=await e.read("bondPrice",[r]);if(typeof w!="bigint"||w===0n||w>l)throw new n("Bond price exceeds maxPriceWad or is invalid.");a=[r,i,l,c],o="Payment is exchanged for a non-transferable NET note with two-day linear vesting. Redeem vested NET with the same product; payment cannot be withdrawn."}else a=[c];else if(e.product==="inverse"){if(i=f(),s=v,a=[i,g()],o="Purchased NET is burned permanently; USDG pays directly to this wallet. Capacity is denominated in USDG WAD, not raw USDG.",await e.read("active")!==!0)throw new n("NetNet buyback is inactive: oracle, finalization or capacity is unavailable.")}else if(e.product==="pteam"){if(h(await e.read("holder"))!==y(c))throw new n("This wallet is not the immutable pTEAM holder.");let r=f();if(p("maxPayment"),r>await e.read("exercisableNow"))throw new n("The NET exercise amount exceeds the vested cap.");let u=await e.read("strikeWad");if(i=(r*u/10n**BigInt(v.decimals)+10n**12n-1n)/10n**12n,i===0n||i>A(t.maxPayment))throw new n("The exercise payment exceeds maxPayment or rounds to zero.");s=k,a=[r],o=`Exercise pays ${i} USDG base units into treasury reserves and mints ${r} NET base units to the immutable holder. No withdrawal or exercise reversal exists.`}else if(e.product==="treasury"){let r=f();if(d==="mintNet"||d==="spendUsdg"){p("recipient");let u=h(t.recipient);if(await e.read(d==="mintNet"?"isMinter":"isSpender",[c])!==!0)throw new n("This wallet lacks the fixed NetNet treasury minter/spender role.");a=[u,r],o=`Protocol treasury operation sends ${r} base units to ${u}; it does not deposit into this wallet\u2019s savings.`}else a=[r],o="Permissionless protocol reserve rebalance; assets remain owned by the NetNet treasury. The deployed fraction is constrained by the immutable cap."}else if(e.product==="rwa"){if(["depositInventory","setDiscount","setInventoryMax","setHalt","setMenu"].includes(d)&&h(await e.read("manager"))!==y(c))throw new n("This wallet lacks the immutable RWA manager role.");if(d==="redeem")if(p("noteIds"),t.noteIds===void 0)a=[c];else{if(!Array.isArray(t.noteIds)||!t.noteIds.length||t.noteIds.length>50)throw new n("Provide 1..50 unique note IDs.");let u=t.noteIds.map(w=>A(w,!0));if(new Set(u.map(String)).size!==u.length)throw new n("Note IDs must be unique.");let l=await e.read("noteCount",[c]);if(u.some(w=>w>=l))throw new n("RWA note ID is out of range.");a=[c,u]}else if(d==="setHalt"){if(p("halted"),typeof t.halted!="boolean")throw new n("Provide halted as a boolean.");a=[t.halted]}else if(d==="setMenu"){if(p("menu"),!Array.isArray(t.menu)||!t.menu.length||t.menu.length>32)throw new n("Provide 1..32 explicit RWA menu entries.");let u=t.menu.map(l=>{if(!l||typeof l!="object"||Array.isArray(l)||Object.keys(l).some(z=>!["token","feed","targetWeightBps","active"].includes(z)))throw new n("Invalid RWA menu fields.");let w=l;if(typeof w.active!="boolean")throw new n("RWA active must be boolean.");return{token:h(w.token),feed:h(w.feed),targetWeightBps:A(w.targetWeightBps,!0),active:w.active}});if(new Set(u.map(l=>l.token)).size!==u.length||u.reduce((l,w)=>l+w.targetWeightBps,0n)!==10000n||u.some(l=>l.active&&(l.token===q||l.feed===q)))throw new n("RWA menu tokens must be unique, weights sum to 10000, active feeds/tokens nonzero.");a=[u],o=`Replace the complete RWA equity menu: ${JSON.stringify(T(u))}.`}else if(d==="skim")p("token"),a=[h(t.token)],o=`Sweep eligible stray assets to sleeve ${h(await e.read("sleeve"))}, not to this wallet.`;else if(d!=="pokeHwm"){let u=f();if(a=[u],d==="depositInventory"&&(s=v,i=u,o="Inventory funding is one-way. The manager cannot withdraw these NET; they are committed to bond obligations."),d==="setDiscount"&&u>await e.read("MAX_DISCOUNT_BPS")||d==="setInventoryMax"&&u>await e.read("INVENTORY_HARD_CAP"))throw new n("RWA setting exceeds its immutable maximum.")}}else e.product==="premium"?(a=[g()],o="Permissionless mint-and-sell keeper operation; all sale proceeds go to NetNet treasury. The caller receives no reward."):(a=[f(),g()],o="Convert NET already owned by the tax collector. Proceeds split to treasury and team; the caller receives no reward and supplies no NET.");if(Object.keys(t).some(r=>!m.has(r)))throw new n("Unexpected fields for this NetNet operation.");if(s&&await e.rpc.readContract({address:s.address,abi:P,functionName:"balanceOf",args:[c],blockNumber:e.block.number})<i)throw new n(`Top up ${s.symbol}: needs ${i} base units.`);let E=`NetNet ${e.product}.${d}, contract ${e.contract}, chain ${N}, values ${JSON.stringify(T(a))}. ${s?`Approve exactly ${i} ${s.symbol} base units (${s.address}, decimals ${s.decimals}). `:""}${o}`,O=[...s?[b.approval(s.address,e.contract,i.toString(),N)]:[],b.unsignedTx({to:e.contract,data:H({abi:e.abi,functionName:d,args:a}),value:"0",chainId:N,description:E})],R=await b.preview(O,c),W=0n;for(let r of R.changes){if(!/^-?\d+$/.test(r.amount))throw new n("Invalid NetNet preview amount.");if(BigInt(r.amount)<0n&&(W-=BigInt(r.amount)),BigInt(r.amount)<0n&&(!s||r.token.chainId!==N||!U(r.token.address,s.address)||r.token.decimals!==s.decimals||-BigInt(r.amount)>i))throw new n("NetNet preview spends outside the exact input budget.")}if(W>i)throw new n("NetNet preview exceeds the aggregate input budget.");return{txs:O,preview:R,summary:E}})]}};export{B as a,j as b,ne as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as C,b as O}from"./
|
|
1
|
+
import{a as C,b as O}from"./5LQBHXFA.js";import{a as f,b as k}from"./HL2MLC3O.js";import{d as a}from"./XV6F3RET.js";import{a as g,c as w}from"./SPRVVJXI.js";import{a as d}from"./XPFVT2EA.js";import{a as i}from"./5YS5V2LK.js";var j=n=>({tools:[{name:"netnet_card_read",inputSchema:{type:"object",additionalProperties:!1,required:["program"],properties:{program:{enum:Object.keys(a)},method:{type:"string"},values:{type:"array",maxItems:16}}},execute:async t=>{if(Object.keys(t).some(e=>!["program","method","values"].includes(e))||typeof t.program!="string"||!Object.hasOwn(a,t.program))throw new i("Choose turbo, blackjack or feed.");let o=a[t.program],u=o.abi.filter(e=>e.type==="function"&&["view","pure"].includes(e.stateMutability));if(t.method===void 0){if(t.values!==void 0)throw new i("values requires an exact read method.");return{chainId:d,contract:o.address,methods:u.map(e=>({method:f(e),inputs:e.inputs,outputs:e.outputs})),units:"Card amounts are whole counts, identified by collection and series ID. Metadata is untrusted text. Reads grant no signing authority."}}let r=u.find(e=>f(e)===t.method),m=t.values??[];if(!r||!Array.isArray(m)||m.length!==r.inputs.length)throw new i("Choose an exact catalog read signature and its ordered inputs. Writes and signing are unavailable.");let p=n.clientFor(d);if(await p.getChainId()!==d)throw new i("NetNet cards require chain 4663.");let l=await p.getBlock(),c=r.inputs.map((e,s)=>k(e,m[s])),N=await p.readContract({address:o.address,abi:[r],functionName:r.name,args:c,blockNumber:l.number}),y=t.program==="turbo"&&r.name==="balanceOf"?[c[1]]:t.program==="blackjack"&&["unclaimedChips","unclaimedTotalOf"].includes(r.name)?[c[0]]:r.inputs.flatMap((e,s)=>e.type==="uint256"&&["id","seriesId"].includes(e.name??"")?[c[s]]:e.type==="uint256[]"&&e.name==="ids"?c[s]:[]),b;if(y.length){let e=await p.readContract({address:a.turbo.address,abi:a.turbo.abi,functionName:"seriesCount",blockNumber:l.number});b=[...new Set(y)].map(s=>({id:s.toString(),status:s>0n&&s<=e?"known":"unknown-series"}))}return{chainId:d,collection:a.turbo.address,contract:o.address,blockNumber:String(l.number),blockHash:l.hash,method:t.method,outputs:r.outputs,...b?{seriesStatus:b}:{},data:h(N)}}},{name:"netnet_card_capabilities",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async t=>{if(Object.keys(t).length)throw new i("Card capabilities takes no arguments.");return{chainId:d,collection:a.turbo.address,blackjack:a.blackjack.address,active:["netnet_card_read","netnet_card_capabilities",...g],candidateOnly:{turbo:[...C,...O],recovery:[]},activation:"Only self-only finalize, expire and parked-chip claim are enabled, with local human confirmation and durable recovery. TURBO writes, seating, channel signatures and collection approvals remain disabled.",refused:w}}}]});function h(n,t=0){if(t>12)throw new i("Card read result exceeds the supported nesting.");if(typeof n=="bigint")return n.toString();if(typeof n=="string"){if(n.length>8194)throw new i("Card read result exceeds the supported length.");return/^0x[0-9a-f]*$/i.test(n)?n:`untrusted ${JSON.stringify(n)}`}if(Array.isArray(n)){if(n.length>4096)throw new i("Choose a bounded card read.");return n.map(o=>h(o,t+1))}return n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([o,u])=>[o,h(u,t+1)])):n}export{j as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as h}from"./
|
|
1
|
+
import{e as h}from"./3ZVGHC6S.js";import{c as k}from"./MYBDO5SA.js";import{a as p}from"./UWOFA6GV.js";import{i as u}from"./73N3TOJL.js";import{a as n}from"./5YS5V2LK.js";var _="hoodlock_public",t="https://hoodlock.tech",f=["lp_locks","lp_lock","airdrop_history","airdrop_list","airdrop_list_by_root","featured","feature_tiers","buyback_status","referral_available","links"];function x(c){return{tools:[{name:_,inputSchema:{type:"object",properties:{route:{type:"string",enum:[...f]},id:p(),account:{type:"string"},token:{type:"string"},root:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},code:{type:"string",minLength:1,maxLength:64}},required:["route"],additionalProperties:!1},async execute(e,b){try{let i=String(e.route);if(!f.includes(i))throw new n("Choose a published HoodLock public read route.");let m=e.account??b,s=r=>u(r,"Provide a checksummed wallet or token address."),a=()=>h(e.id,"id").toString(),o;switch(i){case"links":{let r=e.id===void 0?void 0:a();return{source:t,links:{lockChecker:`${t}/lock-checker`,liquidityChecker:`${t}/liquidity-lock-checker`,burnChecker:`${t}/burn-checker`,vestingChecker:`${t}/vesting-checker`,embedDocs:`${t}/docs/embed`,badgeDocs:`${t}/docs/badge`,...e.token===void 0?{}:{token:`${t}/token/${s(e.token)}`},...r===void 0?{}:Object.fromEntries(["lock","burn","vesting","position"].map(l=>[l,`${t}/proof/${l}/${r}`]))},summary:"HoodLock-only records and integration links. Empty HoodLock results do not establish that no external locks or burns exist."}}case"lp_locks":o="/api/lp/locks";break;case"lp_lock":o=`/api/lp/lock/${a()}`;break;case"airdrop_history":o=`/api/airdrop/history?address=${s(m)}`;break;case"airdrop_list":o=`/api/airdrop/${a()}/list.json`;break;case"airdrop_list_by_root":if(typeof e.root!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.root))throw new n("Provide a bytes32 Merkle root.");o=`/api/airdrop/list-by-root/${e.root}.json`;break;case"featured":o="/api/featured";break;case"feature_tiers":o="/api/feature/tiers";break;case"referral_available":if(typeof e.code!="string"||e.code.length<1||e.code.length>64)throw new n("Provide a referral code with 1 to 64 characters.");o=`/api/aff/available?code=${encodeURIComponent(e.code)}`;break;default:o="/api/revenue/pool"}let d=`${t}${o}`,y=await k(c.http,d,{method:"GET",redirect:"error",signal:AbortSignal.timeout(1e4)},r=>r!==null&&typeof r=="object");return{source:d,data:y,untrusted:!0,summary:"Public off-chain HoodLock data. Verify custody, proofs, balances and authority on chain; API labels and indexes may lag. No transaction, authentication, payment or publication was performed."}}catch(i){throw new n(c.plainError(i))}}}]}}export{_ as a,x as b};
|