@oakagentkit/core 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/build/dist/api/modules/fobo/client.js +1 -1
  2. package/build/dist/api/modules/fobo/index.js +1 -1
  3. package/build/dist/api/modules/fobo/intent.js +1 -1
  4. package/build/dist/api/modules/fobo/steps.js +1 -1
  5. package/build/dist/api/modules/fobo/verify.js +1 -1
  6. package/build/dist/api/modules/longbow/administration.js +1 -1
  7. package/build/dist/api/modules/longbow/fixed.js +1 -1
  8. package/build/dist/api/modules/longbow/index.js +1 -1
  9. package/build/dist/api/modules/merkl/discovery.js +1 -1
  10. package/build/dist/api/modules/merkl/index.js +1 -1
  11. package/build/dist/api/modules/merkl/manage.js +1 -1
  12. package/build/dist/api/modules/morpho/bundles.js +1 -1
  13. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  14. package/build/dist/api/modules/morpho/index.d.ts +2 -1
  15. package/build/dist/api/modules/morpho/index.js +1 -1
  16. package/build/dist/api/modules/morpho/local-guard.d.ts +2 -2
  17. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  18. package/build/dist/api/modules/morpho/midnight.js +1 -1
  19. package/build/dist/api/modules/morpho/protocol.js +1 -1
  20. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  21. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  22. package/build/dist/api/modules/netnet/card-read.js +1 -1
  23. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  24. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  25. package/build/dist/api/modules/netnet/financial.js +1 -1
  26. package/build/dist/api/modules/netnet/index.js +1 -1
  27. package/build/dist/chunks/{NDSNE6PS.js → 3UQXTZ5R.js} +1 -1
  28. package/build/dist/chunks/{NTUXDIY6.js → 5CPB33XA.js} +1 -1
  29. package/build/dist/chunks/{MQ37QX6U.js → 72EV7TGI.js} +1 -1
  30. package/build/dist/chunks/{M7CQPTRK.js → CXH46MHJ.js} +1 -1
  31. package/build/dist/chunks/{UYULQHZJ.js → FSYYD3OM.js} +1 -1
  32. package/build/dist/chunks/{Z2QV6EZY.js → HPY2ONAS.js} +1 -1
  33. package/build/dist/chunks/{AIYNFIG6.js → I3ZBOSSH.js} +1 -1
  34. package/build/dist/chunks/{AG2G7BHH.js → NCAV7Q4C.js} +1 -1
  35. package/build/dist/chunks/{M6SQPOOL.js → OFWTO4N6.js} +1 -1
  36. package/build/dist/chunks/{OLDQV43V.js → PHGHJ7SN.js} +1 -1
  37. package/build/dist/chunks/{QHV5GORV.js → SO6O7JK2.js} +1 -1
  38. package/build/dist/chunks/{HQIS3QI7.js → SVKG4JOY.js} +2 -2
  39. package/build/dist/chunks/{HOBIXKGO.js → UCHJYWGU.js} +1 -1
  40. package/build/dist/chunks/{4NDIYRH5.js → WCI3FHWT.js} +1 -1
  41. package/build/dist/chunks/{W7OCS4AM.js → X5I5EJ5T.js} +1 -1
  42. package/build/dist/chunks/{AXHFNE6L.js → XKLXVTSE.js} +3 -3
  43. package/build/dist/chunks/{2JWAFLJU.js → YAVWSW3G.js} +1 -1
  44. package/package.json +1 -1
@@ -1 +1 @@
1
- import{a as q}from"./NCQFWPAW.js";import{a as v}from"./RUTSEGGD.js";import{K as A}from"./AXHFNE6L.js";import{c as k}from"./W7QNSNOH.js";import{a as $}from"./43LI5NKJ.js";import{a as I}from"./66F5ZH34.js";import{d as M,g as F,i as G,m as U}from"./NWNYJ26T.js";import{b as y}from"./TI727O2H.js";import{a as o}from"./XSD5NL7J.js";import{encodeFunctionData as L,erc20Abi as R,getAddress as N,zeroAddress as j}from"viem";var C={genesis:N("0x575b7B7c97Ef3E21C82DAeB427899d583e1E913f"),bond:N("0xff32a969A0c567129eECD926D04657728E1980C1"),inverse:N("0x92166e94Eea5B7799b761653881692f881dFC4C9"),treasury:N("0x04822Ea321A0DEE6F40656172F29312104855d66"),pteam:N("0x650F58079dAa17ee28928c2F92d22291d038B2B0"),rwa:N("0x99B6eE6eDe47d9a8a9bfd03F728a99B789df1961"),premium:N("0x346e1a31171A0f7aC73909010b5435768d3B5462"),tax:N("0x086C58400b8708Ef993f256E12e752dcF0AC918e")},z=N("0x59F95461E68e0c77605299791E1449f175165B54"),O={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"]},V={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=h=>JSON.parse(JSON.stringify(h,(P,S)=>typeof S=="bigint"?S.toString():S));function g(h){return G(h,"Provide a checksummed address.",M)}var oe=h=>{async function P(t){if(typeof t!="string"||!Object.hasOwn(C,t))throw new o("Choose a published NetNet financial product.");let c=t,e=C[c],r=q[c],u=h.clientFor(y);if(await u.getChainId()!==y)throw new o("NetNet requires chain 4663.");let n=await u.getBlock(),a=(w,x=[])=>u.readContract({address:e,abi:r,functionName:w,args:x,blockNumber:n.number}),[i,s,l,p]=await Promise.all([a("net"),a("usdg"),u.readContract({address:v.address,abi:R,functionName:"decimals",blockNumber:n.number}),u.readContract({address:k.address,abi:R,functionName:"decimals",blockNumber:n.number})]);if(g(i)!==v.address||g(s)!==k.address||l!==v.decimals||p!==k.decimals)throw new o("NetNet financial token pins or decimals do not match the deployment.");return{product:c,contract:e,abi:r,rpc:u,block:n,read:a}}async function S(t){$(t);let c=(e,r)=>({module:"netnet",id:`4663:${C.bond.toLowerCase()}:${e}`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond notes unreadable: ${h.plainError(r)} Use netnet_financial_status with product bond to inspect notes.`});try{let e=await P("bond"),r=U(await e.read("noteCount",[t]),"Invalid NetNet bond note count."),u=r<50n?Number(r):50,n=[];for(let a=0;a<u;a++)try{let i=await e.read("notes",[t,BigInt(a)]);if(!Array.isArray(i)||i.length!==4)throw new o("Invalid NetNet bond note.");let[s,l,p,w]=i.map(B=>U(B,"Invalid NetNet bond note amount or timestamp."));if(l>s||w<=p||w>=1n<<64n)throw new o("Invalid NetNet bond note vesting or claimed amount.");let x=s-l;if(x===0n)continue;let E=e.block.timestamp>=w?s:e.block.timestamp<=p?0n:s*(e.block.timestamp-p)/(w-p),D=E>l?E-l:0n;n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:${a}`,chainId:y,matured:e.block.timestamp>=w,assets:[{token:v,amount:x.toString()}],description:`NetNet bond note ${a}: ${x} NET base units outstanding; ${D} claimable now, vesting ends at Unix ${w}. Redeem vested NET with netnet_financial_action product bond operation redeem. Payment cannot be withdrawn. Block ${e.block.number}.`})}catch(i){n.push(c(String(a),i))}return r>BigInt(u)&&n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:coverage`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond positions checked the first ${u} of ${r} notes. Use netnet_financial_status product bond offset ${u} to read the remaining notes.`}),n}catch(e){return[c("unreadable",e)]}}let _=(t,c,e,r)=>({name:t,inputSchema:{type:"object",properties:c,required:e,additionalProperties:!1},execute:async(u,n)=>{try{if($(n),Object.keys(u).some(a=>!Object.hasOwn(c,a)))throw new o("Unsupported NetNet financial argument.");return await r(u,n)}catch(a){throw new o(h.plainError(a))}}}),W={type:"string",enum:Object.keys(C),description:"NetNet financial product: genesis (founding sale), bond, inverse (NET buyback), treasury, pteam (team option), rwa (equity desk), premium (premium keeper) or tax (tax collector)."};return{positions:S,tools:[_("netnet_financial_status",{product:W,offset:{type:"integer",minimum:0,description:"Index of the first wallet note to return (bond and rwa products only). Default 0."},limit:{type:"integer",minimum:1,maximum:50,description:"Maximum notes to return, 1 to 50 (default 20; bond and rwa products only)."}},["product"],async(t,c)=>{let e=await P(t.product),r=V[e.product],u=t.offset??0,n=t.limit??20;if(!Number.isSafeInteger(u)||Number(u)<0||!Number.isSafeInteger(n)||Number(n)<1||Number(n)>50)throw new o("Use a nonnegative offset and limit 1..50.");let a=await Promise.all(r.map(async s=>{try{return[s,{value:T(await e.read(s))}]}catch(l){return[s,{unavailable:h.plainError(l)}]}})),i={};if(e.product==="genesis")for(let s of["purchasedRaw","purchasedNetOf","claimedNet","claimableNetOf"])i[s]=T(await e.read(s,[c]));if(e.product==="bond"||e.product==="rwa"){i.pending=T(await e.read("pendingFor",[c]));let s=await e.read("noteCount",[c]);if(typeof s!="bigint"||s<0n)throw new o("Invalid NetNet note count.");let l=s<BigInt(Number(u)+Number(n))?s:BigInt(Number(u)+Number(n));i.noteCount=s.toString(),i.notes=await Promise.all(Array.from({length:Math.max(0,Number(l-BigInt(Number(u))))},async(p,w)=>({id:String(Number(u)+w),note:T(await e.read(e.product==="bond"?"notes":"noteAt",[c,BigInt(Number(u)+w)]))}))),i.nextOffset=l<s?l.toString():null,e.product==="bond"&&(i.markets=await Promise.all([0n,1n].map(async p=>{try{return{id:p.toString(),quoteToken:g(await e.read("quoteToken",[p])),priceWad:String(await e.read("bondPrice",[p]))}}catch(w){return{id:p.toString(),unavailable:h.plainError(w)}}})))}return e.product==="treasury"&&(i.isMinter=await e.read("isMinter",[c]),i.isSpender=await e.read("isSpender",[c])),{chainId:y,contract:e.contract,product:e.product,blockNumber:String(e.block.number),tokens:[v,k],metrics:Object.fromEntries(a),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:O[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."}}),_("netnet_financial_action",{product:W,operation:{type:"string",enum:[...new Set(Object.values(O).flat())],description:"Action to run; it must be one the chosen product supports, for example bond deposit or redeem, genesis purchase or claim, inverse swap."},amount:I('Amount in base units of the token the operation spends or moves: USDG has 6 decimals, NET 9 ("1000000" = 1 USDG, "1000000000" = 1 NET).'),minAmountOut:I('Least output you must receive, in base units of the output token (USDG 6 decimals, NET 9). Example: "1000000" = 1 USDG.'),maxPriceWad:I("Highest bond price you accept, as an 18-decimal wad of USDG per NET in base units (1e18 = 1 USDG). Bond deposit only."),maxPayment:I('Most USDG you will pay to exercise, in USDG base units (6 decimals). Example: "1000000" = 1 USDG. pteam exercise only.'),marketId:{type:"integer",enum:[0,1],description:"Bond market: 0 pays with USDG, 1 pays with the canonical NET/USDG LP token. Bond deposit only."},recipient:{type:"string",description:"Address that receives the minted NET or spent USDG. Treasury mintNet and spendUsdg only; use the intended address."},halted:{type:"boolean",description:"rwa setHalt only: true halts the desk, false resumes it."},token:{type:"string",description:"Address of the stray token to sweep (0x + 40 hex digits). rwa skim only."},noteIds:{type:"array",maxItems:50,description:"Bond note ids to redeem, unique decimal strings (rwa redeem only); omit to redeem every vested note.",items:I('Note id (index of the wallet note), as a decimal string. Example: "0".')},menu:{type:"array",maxItems:32,description:"Complete replacement RWA equity menu (rwa setMenu only): up to 32 entries; target weights must sum to 10000 basis points.",items:{type:"object",description:"Menu entry with token and feed addresses, targetWeightBps (10000 = 100%) and active (boolean)."}}},["product","operation"],async(t,c)=>{let e=await P(t.product),r=t.operation;if(typeof r!="string"||!O[e.product].includes(r))throw new o("This operation is not supported by the selected financial product.");let u=new Set(["product","operation"]),n=[],a,i=0n,s="",l=(...d)=>d.forEach(m=>u.add(m)),p=()=>(l("amount"),A(t.amount)),w=()=>(l("minAmountOut"),A(t.minAmountOut));if(e.product==="genesis"){if(r==="purchase"&&(i=p(),a=k,n=[i],s="Founding subscription; NET is claimable only after successful finalization and vesting. A failed sale requires refund."),r==="claim"&&await e.read("claimableNetOf",[c])===0n)throw new o("No vested founding NET is claimable by this wallet.")}else if(e.product==="bond")if(r==="deposit"){if(l("marketId","maxPriceWad"),t.marketId!==0&&t.marketId!==1)throw new o("Bond marketId must be 0 (USDG) or 1 (canonical LP).");let d=BigInt(t.marketId);if(g(await e.read("quoteToken",[d]))!==(d===0n?k.address:z))throw new o("Bond quote token is not the pinned USDG or canonical LP.");i=p(),a=d===0n?k:{address:z,decimals:18,symbol:"NET/USDG LP",chainId:y};let f=A(t.maxPriceWad),b=await e.read("bondPrice",[d]);if(typeof b!="bigint"||b===0n||b>f)throw new o("Bond price exceeds maxPriceWad or is invalid.");n=[d,i,f,c],s="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 n=[c];else if(e.product==="inverse"){if(i=p(),a=v,n=[i,w()],s="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 o("NetNet buyback is inactive: oracle, finalization or capacity is unavailable.")}else if(e.product==="pteam"){if(g(await e.read("holder"))!==N(c))throw new o("This wallet is not the immutable pTEAM holder.");let d=p();if(l("maxPayment"),d>await e.read("exercisableNow"))throw new o("The NET exercise amount exceeds the vested cap.");let m=await e.read("strikeWad");if(i=(d*m/10n**BigInt(v.decimals)+10n**12n-1n)/10n**12n,i===0n||i>A(t.maxPayment))throw new o("The exercise payment exceeds maxPayment or rounds to zero.");a=k,n=[d],s=`Exercise pays ${i} USDG base units into treasury reserves and mints ${d} NET base units to the immutable holder. No withdrawal or exercise reversal exists.`}else if(e.product==="treasury"){let d=p();if(r==="mintNet"||r==="spendUsdg"){l("recipient");let m=g(t.recipient);if(await e.read(r==="mintNet"?"isMinter":"isSpender",[c])!==!0)throw new o("This wallet lacks the fixed NetNet treasury minter/spender role.");n=[m,d],s=`Protocol treasury operation sends ${d} base units to ${m}; it does not deposit into this wallet\u2019s savings.`}else n=[d],s="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(r)&&g(await e.read("manager"))!==N(c))throw new o("This wallet lacks the immutable RWA manager role.");if(r==="redeem")if(l("noteIds"),t.noteIds===void 0)n=[c];else{if(!Array.isArray(t.noteIds)||!t.noteIds.length||t.noteIds.length>50)throw new o("Provide 1..50 unique note IDs.");let m=t.noteIds.map(b=>A(b,!0));if(new Set(m.map(String)).size!==m.length)throw new o("Note IDs must be unique.");let f=await e.read("noteCount",[c]);if(m.some(b=>b>=f))throw new o("RWA note ID is out of range.");n=[c,m]}else if(r==="setHalt"){if(l("halted"),typeof t.halted!="boolean")throw new o("Provide halted as a boolean.");n=[t.halted]}else if(r==="setMenu"){if(l("menu"),!Array.isArray(t.menu)||!t.menu.length||t.menu.length>32)throw new o("Provide 1..32 explicit RWA menu entries.");let m=t.menu.map(f=>{if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(H=>!["token","feed","targetWeightBps","active"].includes(H)))throw new o("Invalid RWA menu fields.");let b=f;if(typeof b.active!="boolean")throw new o("RWA active must be boolean.");return{token:g(b.token),feed:g(b.feed),targetWeightBps:A(b.targetWeightBps,!0),active:b.active}});if(new Set(m.map(f=>f.token)).size!==m.length||m.reduce((f,b)=>f+b.targetWeightBps,0n)!==10000n||m.some(f=>f.active&&(f.token===j||f.feed===j)))throw new o("RWA menu tokens must be unique, weights sum to 10000, active feeds/tokens nonzero.");n=[m],s=`Replace the complete RWA equity menu: ${JSON.stringify(T(m))}.`}else if(r==="skim")l("token"),n=[g(t.token)],s=`Sweep eligible stray assets to sleeve ${g(await e.read("sleeve"))}, not to this wallet.`;else if(r!=="pokeHwm"){let m=p();if(n=[m],r==="depositInventory"&&(a=v,i=m,s="Inventory funding is one-way. The manager cannot withdraw these NET; they are committed to bond obligations."),r==="setDiscount"&&m>await e.read("MAX_DISCOUNT_BPS")||r==="setInventoryMax"&&m>await e.read("INVENTORY_HARD_CAP"))throw new o("RWA setting exceeds its immutable maximum.")}}else e.product==="premium"?(n=[w()],s="Permissionless mint-and-sell keeper operation; all sale proceeds go to NetNet treasury. The caller receives no reward."):(n=[p(),w()],s="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(d=>!u.has(d)))throw new o("Unexpected fields for this NetNet operation.");if(a&&await e.rpc.readContract({address:a.address,abi:R,functionName:"balanceOf",args:[c],blockNumber:e.block.number})<i)throw new o(`Top up ${a.symbol}: needs ${i} base units.`);let x=`NetNet ${e.product}.${r}, contract ${e.contract}, chain ${y}, values ${JSON.stringify(T(n))}. ${a?`Approve exactly ${i} ${a.symbol} base units (${a.address}, decimals ${a.decimals}). `:""}${s}`,E=[...a?[h.approval(a.address,e.contract,i.toString(),y)]:[],h.unsignedTx({to:e.contract,data:L({abi:e.abi,functionName:r,args:n}),value:"0",chainId:y,description:x})],D=await h.preview(E,c),B=0n;for(let d of D.changes){if(!/^-?\d+$/.test(d.amount))throw new o("Invalid NetNet preview amount.");if(BigInt(d.amount)<0n&&(B-=BigInt(d.amount)),BigInt(d.amount)<0n&&(!a||d.token.chainId!==y||!F(d.token.address,a.address)||d.token.decimals!==a.decimals||-BigInt(d.amount)>i))throw new o("NetNet preview spends outside the exact input budget.")}if(B>i)throw new o("NetNet preview exceeds the aggregate input budget.");return{txs:E,preview:D,summary:x}})]}};export{C as a,z as b,oe as c};
1
+ import{a as q}from"./NCQFWPAW.js";import{a as v}from"./RUTSEGGD.js";import{L as A}from"./XKLXVTSE.js";import{c as k}from"./W7QNSNOH.js";import{a as $}from"./43LI5NKJ.js";import{a as I}from"./66F5ZH34.js";import{d as M,g as F,i as G,m as U}from"./NWNYJ26T.js";import{b as y}from"./TI727O2H.js";import{a as o}from"./XSD5NL7J.js";import{encodeFunctionData as L,erc20Abi as R,getAddress as N,zeroAddress as j}from"viem";var C={genesis:N("0x575b7B7c97Ef3E21C82DAeB427899d583e1E913f"),bond:N("0xff32a969A0c567129eECD926D04657728E1980C1"),inverse:N("0x92166e94Eea5B7799b761653881692f881dFC4C9"),treasury:N("0x04822Ea321A0DEE6F40656172F29312104855d66"),pteam:N("0x650F58079dAa17ee28928c2F92d22291d038B2B0"),rwa:N("0x99B6eE6eDe47d9a8a9bfd03F728a99B789df1961"),premium:N("0x346e1a31171A0f7aC73909010b5435768d3B5462"),tax:N("0x086C58400b8708Ef993f256E12e752dcF0AC918e")},z=N("0x59F95461E68e0c77605299791E1449f175165B54"),O={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"]},V={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=h=>JSON.parse(JSON.stringify(h,(P,S)=>typeof S=="bigint"?S.toString():S));function g(h){return G(h,"Provide a checksummed address.",M)}var oe=h=>{async function P(t){if(typeof t!="string"||!Object.hasOwn(C,t))throw new o("Choose a published NetNet financial product.");let c=t,e=C[c],r=q[c],u=h.clientFor(y);if(await u.getChainId()!==y)throw new o("NetNet requires chain 4663.");let n=await u.getBlock(),a=(w,x=[])=>u.readContract({address:e,abi:r,functionName:w,args:x,blockNumber:n.number}),[i,s,l,p]=await Promise.all([a("net"),a("usdg"),u.readContract({address:v.address,abi:R,functionName:"decimals",blockNumber:n.number}),u.readContract({address:k.address,abi:R,functionName:"decimals",blockNumber:n.number})]);if(g(i)!==v.address||g(s)!==k.address||l!==v.decimals||p!==k.decimals)throw new o("NetNet financial token pins or decimals do not match the deployment.");return{product:c,contract:e,abi:r,rpc:u,block:n,read:a}}async function S(t){$(t);let c=(e,r)=>({module:"netnet",id:`4663:${C.bond.toLowerCase()}:${e}`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond notes unreadable: ${h.plainError(r)} Use netnet_financial_status with product bond to inspect notes.`});try{let e=await P("bond"),r=U(await e.read("noteCount",[t]),"Invalid NetNet bond note count."),u=r<50n?Number(r):50,n=[];for(let a=0;a<u;a++)try{let i=await e.read("notes",[t,BigInt(a)]);if(!Array.isArray(i)||i.length!==4)throw new o("Invalid NetNet bond note.");let[s,l,p,w]=i.map(B=>U(B,"Invalid NetNet bond note amount or timestamp."));if(l>s||w<=p||w>=1n<<64n)throw new o("Invalid NetNet bond note vesting or claimed amount.");let x=s-l;if(x===0n)continue;let E=e.block.timestamp>=w?s:e.block.timestamp<=p?0n:s*(e.block.timestamp-p)/(w-p),D=E>l?E-l:0n;n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:${a}`,chainId:y,matured:e.block.timestamp>=w,assets:[{token:v,amount:x.toString()}],description:`NetNet bond note ${a}: ${x} NET base units outstanding; ${D} claimable now, vesting ends at Unix ${w}. Redeem vested NET with netnet_financial_action product bond operation redeem. Payment cannot be withdrawn. Block ${e.block.number}.`})}catch(i){n.push(c(String(a),i))}return r>BigInt(u)&&n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:coverage`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond positions checked the first ${u} of ${r} notes. Use netnet_financial_status product bond offset ${u} to read the remaining notes.`}),n}catch(e){return[c("unreadable",e)]}}let _=(t,c,e,r)=>({name:t,inputSchema:{type:"object",properties:c,required:e,additionalProperties:!1},execute:async(u,n)=>{try{if($(n),Object.keys(u).some(a=>!Object.hasOwn(c,a)))throw new o("Unsupported NetNet financial argument.");return await r(u,n)}catch(a){throw new o(h.plainError(a))}}}),W={type:"string",enum:Object.keys(C),description:"NetNet financial product: genesis (founding sale), bond, inverse (NET buyback), treasury, pteam (team option), rwa (equity desk), premium (premium keeper) or tax (tax collector)."};return{positions:S,tools:[_("netnet_financial_status",{product:W,offset:{type:"integer",minimum:0,description:"Index of the first wallet note to return (bond and rwa products only). Default 0."},limit:{type:"integer",minimum:1,maximum:50,description:"Maximum notes to return, 1 to 50 (default 20; bond and rwa products only)."}},["product"],async(t,c)=>{let e=await P(t.product),r=V[e.product],u=t.offset??0,n=t.limit??20;if(!Number.isSafeInteger(u)||Number(u)<0||!Number.isSafeInteger(n)||Number(n)<1||Number(n)>50)throw new o("Use a nonnegative offset and limit 1..50.");let a=await Promise.all(r.map(async s=>{try{return[s,{value:T(await e.read(s))}]}catch(l){return[s,{unavailable:h.plainError(l)}]}})),i={};if(e.product==="genesis")for(let s of["purchasedRaw","purchasedNetOf","claimedNet","claimableNetOf"])i[s]=T(await e.read(s,[c]));if(e.product==="bond"||e.product==="rwa"){i.pending=T(await e.read("pendingFor",[c]));let s=await e.read("noteCount",[c]);if(typeof s!="bigint"||s<0n)throw new o("Invalid NetNet note count.");let l=s<BigInt(Number(u)+Number(n))?s:BigInt(Number(u)+Number(n));i.noteCount=s.toString(),i.notes=await Promise.all(Array.from({length:Math.max(0,Number(l-BigInt(Number(u))))},async(p,w)=>({id:String(Number(u)+w),note:T(await e.read(e.product==="bond"?"notes":"noteAt",[c,BigInt(Number(u)+w)]))}))),i.nextOffset=l<s?l.toString():null,e.product==="bond"&&(i.markets=await Promise.all([0n,1n].map(async p=>{try{return{id:p.toString(),quoteToken:g(await e.read("quoteToken",[p])),priceWad:String(await e.read("bondPrice",[p]))}}catch(w){return{id:p.toString(),unavailable:h.plainError(w)}}})))}return e.product==="treasury"&&(i.isMinter=await e.read("isMinter",[c]),i.isSpender=await e.read("isSpender",[c])),{chainId:y,contract:e.contract,product:e.product,blockNumber:String(e.block.number),tokens:[v,k],metrics:Object.fromEntries(a),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:O[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."}}),_("netnet_financial_action",{product:W,operation:{type:"string",enum:[...new Set(Object.values(O).flat())],description:"Action to run; it must be one the chosen product supports, for example bond deposit or redeem, genesis purchase or claim, inverse swap."},amount:I('Amount in base units of the token the operation spends or moves: USDG has 6 decimals, NET 9 ("1000000" = 1 USDG, "1000000000" = 1 NET).'),minAmountOut:I('Least output you must receive, in base units of the output token (USDG 6 decimals, NET 9). Example: "1000000" = 1 USDG.'),maxPriceWad:I("Highest bond price you accept, as an 18-decimal wad of USDG per NET in base units (1e18 = 1 USDG). Bond deposit only."),maxPayment:I('Most USDG you will pay to exercise, in USDG base units (6 decimals). Example: "1000000" = 1 USDG. pteam exercise only.'),marketId:{type:"integer",enum:[0,1],description:"Bond market: 0 pays with USDG, 1 pays with the canonical NET/USDG LP token. Bond deposit only."},recipient:{type:"string",description:"Address that receives the minted NET or spent USDG. Treasury mintNet and spendUsdg only; use the intended address."},halted:{type:"boolean",description:"rwa setHalt only: true halts the desk, false resumes it."},token:{type:"string",description:"Address of the stray token to sweep (0x + 40 hex digits). rwa skim only."},noteIds:{type:"array",maxItems:50,description:"Bond note ids to redeem, unique decimal strings (rwa redeem only); omit to redeem every vested note.",items:I('Note id (index of the wallet note), as a decimal string. Example: "0".')},menu:{type:"array",maxItems:32,description:"Complete replacement RWA equity menu (rwa setMenu only): up to 32 entries; target weights must sum to 10000 basis points.",items:{type:"object",description:"Menu entry with token and feed addresses, targetWeightBps (10000 = 100%) and active (boolean)."}}},["product","operation"],async(t,c)=>{let e=await P(t.product),r=t.operation;if(typeof r!="string"||!O[e.product].includes(r))throw new o("This operation is not supported by the selected financial product.");let u=new Set(["product","operation"]),n=[],a,i=0n,s="",l=(...d)=>d.forEach(m=>u.add(m)),p=()=>(l("amount"),A(t.amount)),w=()=>(l("minAmountOut"),A(t.minAmountOut));if(e.product==="genesis"){if(r==="purchase"&&(i=p(),a=k,n=[i],s="Founding subscription; NET is claimable only after successful finalization and vesting. A failed sale requires refund."),r==="claim"&&await e.read("claimableNetOf",[c])===0n)throw new o("No vested founding NET is claimable by this wallet.")}else if(e.product==="bond")if(r==="deposit"){if(l("marketId","maxPriceWad"),t.marketId!==0&&t.marketId!==1)throw new o("Bond marketId must be 0 (USDG) or 1 (canonical LP).");let d=BigInt(t.marketId);if(g(await e.read("quoteToken",[d]))!==(d===0n?k.address:z))throw new o("Bond quote token is not the pinned USDG or canonical LP.");i=p(),a=d===0n?k:{address:z,decimals:18,symbol:"NET/USDG LP",chainId:y};let f=A(t.maxPriceWad),b=await e.read("bondPrice",[d]);if(typeof b!="bigint"||b===0n||b>f)throw new o("Bond price exceeds maxPriceWad or is invalid.");n=[d,i,f,c],s="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 n=[c];else if(e.product==="inverse"){if(i=p(),a=v,n=[i,w()],s="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 o("NetNet buyback is inactive: oracle, finalization or capacity is unavailable.")}else if(e.product==="pteam"){if(g(await e.read("holder"))!==N(c))throw new o("This wallet is not the immutable pTEAM holder.");let d=p();if(l("maxPayment"),d>await e.read("exercisableNow"))throw new o("The NET exercise amount exceeds the vested cap.");let m=await e.read("strikeWad");if(i=(d*m/10n**BigInt(v.decimals)+10n**12n-1n)/10n**12n,i===0n||i>A(t.maxPayment))throw new o("The exercise payment exceeds maxPayment or rounds to zero.");a=k,n=[d],s=`Exercise pays ${i} USDG base units into treasury reserves and mints ${d} NET base units to the immutable holder. No withdrawal or exercise reversal exists.`}else if(e.product==="treasury"){let d=p();if(r==="mintNet"||r==="spendUsdg"){l("recipient");let m=g(t.recipient);if(await e.read(r==="mintNet"?"isMinter":"isSpender",[c])!==!0)throw new o("This wallet lacks the fixed NetNet treasury minter/spender role.");n=[m,d],s=`Protocol treasury operation sends ${d} base units to ${m}; it does not deposit into this wallet\u2019s savings.`}else n=[d],s="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(r)&&g(await e.read("manager"))!==N(c))throw new o("This wallet lacks the immutable RWA manager role.");if(r==="redeem")if(l("noteIds"),t.noteIds===void 0)n=[c];else{if(!Array.isArray(t.noteIds)||!t.noteIds.length||t.noteIds.length>50)throw new o("Provide 1..50 unique note IDs.");let m=t.noteIds.map(b=>A(b,!0));if(new Set(m.map(String)).size!==m.length)throw new o("Note IDs must be unique.");let f=await e.read("noteCount",[c]);if(m.some(b=>b>=f))throw new o("RWA note ID is out of range.");n=[c,m]}else if(r==="setHalt"){if(l("halted"),typeof t.halted!="boolean")throw new o("Provide halted as a boolean.");n=[t.halted]}else if(r==="setMenu"){if(l("menu"),!Array.isArray(t.menu)||!t.menu.length||t.menu.length>32)throw new o("Provide 1..32 explicit RWA menu entries.");let m=t.menu.map(f=>{if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(H=>!["token","feed","targetWeightBps","active"].includes(H)))throw new o("Invalid RWA menu fields.");let b=f;if(typeof b.active!="boolean")throw new o("RWA active must be boolean.");return{token:g(b.token),feed:g(b.feed),targetWeightBps:A(b.targetWeightBps,!0),active:b.active}});if(new Set(m.map(f=>f.token)).size!==m.length||m.reduce((f,b)=>f+b.targetWeightBps,0n)!==10000n||m.some(f=>f.active&&(f.token===j||f.feed===j)))throw new o("RWA menu tokens must be unique, weights sum to 10000, active feeds/tokens nonzero.");n=[m],s=`Replace the complete RWA equity menu: ${JSON.stringify(T(m))}.`}else if(r==="skim")l("token"),n=[g(t.token)],s=`Sweep eligible stray assets to sleeve ${g(await e.read("sleeve"))}, not to this wallet.`;else if(r!=="pokeHwm"){let m=p();if(n=[m],r==="depositInventory"&&(a=v,i=m,s="Inventory funding is one-way. The manager cannot withdraw these NET; they are committed to bond obligations."),r==="setDiscount"&&m>await e.read("MAX_DISCOUNT_BPS")||r==="setInventoryMax"&&m>await e.read("INVENTORY_HARD_CAP"))throw new o("RWA setting exceeds its immutable maximum.")}}else e.product==="premium"?(n=[w()],s="Permissionless mint-and-sell keeper operation; all sale proceeds go to NetNet treasury. The caller receives no reward."):(n=[p(),w()],s="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(d=>!u.has(d)))throw new o("Unexpected fields for this NetNet operation.");if(a&&await e.rpc.readContract({address:a.address,abi:R,functionName:"balanceOf",args:[c],blockNumber:e.block.number})<i)throw new o(`Top up ${a.symbol}: needs ${i} base units.`);let x=`NetNet ${e.product}.${r}, contract ${e.contract}, chain ${y}, values ${JSON.stringify(T(n))}. ${a?`Approve exactly ${i} ${a.symbol} base units (${a.address}, decimals ${a.decimals}). `:""}${s}`,E=[...a?[h.approval(a.address,e.contract,i.toString(),y)]:[],h.unsignedTx({to:e.contract,data:L({abi:e.abi,functionName:r,args:n}),value:"0",chainId:y,description:x})],D=await h.preview(E,c),B=0n;for(let d of D.changes){if(!/^-?\d+$/.test(d.amount))throw new o("Invalid NetNet preview amount.");if(BigInt(d.amount)<0n&&(B-=BigInt(d.amount)),BigInt(d.amount)<0n&&(!a||d.token.chainId!==y||!F(d.token.address,a.address)||d.token.decimals!==a.decimals||-BigInt(d.amount)>i))throw new o("NetNet preview spends outside the exact input budget.")}if(B>i)throw new o("NetNet preview exceeds the aggregate input budget.");return{txs:E,preview:D,summary:x}})]}};export{C as a,z as b,oe as c};
@@ -1 +1 @@
1
- import{a as B}from"./2JWAFLJU.js";import{c as x}from"./R73R4KN3.js";import{c as P}from"./QIB6OMQV.js";import{b as M}from"./MQ37QX6U.js";import{k as F}from"./YXXK6EPI.js";import{c as V}from"./HOBIXKGO.js";import{a as _}from"./A3PN3PK3.js";import{b as O,o as R}from"./GYPMUYB5.js";import{b as I}from"./SPJCSEKP.js";import{a as S}from"./43LI5NKJ.js";import{a as H}from"./66F5ZH34.js";import{g as A,m as N,n as W}from"./NWNYJ26T.js";import{b as m,j as G}from"./TI727O2H.js";import{a as u}from"./XSD5NL7J.js";import{encodeFunctionData as L,getAddress as b,parseAbi as z}from"viem";var c=z(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)","function balanceOf(address) view returns (uint256)","function previewDeposit(uint256 assets) view returns (uint256)","function previewRedeem(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),Q=z(["function deposit() payable"]),p=G[m],T=[{key:"core",name:"Longbow Core USDG",vault:p.vaults.longbowCore.address,asset:p.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"frontier",name:"Longbow Frontier USDG",vault:p.vaults.longbowFrontier.address,asset:p.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"eth",name:"Longbow ETH",vault:p.vaults.longbowEth.address,asset:p.tokens.WETH.address,symbol:"WETH",decimals:18}],D=[{key:"v1-usdg",name:"Longbow USDG Core V1 (legacy)",vault:b("0x8cb8AA35228c96C1C4E956E69AbAEBCc2aA7Dcfe"),asset:p.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"v1-weth",name:"Longbow WETH Core V1 (legacy)",vault:b("0x93777a9b917be3c8259c84456222f43a01dd6492"),asset:p.tokens.WETH.address,symbol:"WETH",decimals:18}];function j(s,i){return W(s,`${i} must be positive and within the uint256 range.`,{notString:`${i} must be a positive integer string in base units.`,positive:!0})}function h(s){return N(s,"Longbow returned an invalid integer response.")}function q(s,i=!1){if(typeof s!="string")throw new u("Provide the address of a current Longbow vault.");let w=D.find(y=>A(y.vault,s));if(w&&!i)throw new u("Longbow V1 vaults are withdraw-only; deposit into a current V2 vault from longbow_list instead.");let g=w??T.find(y=>A(y.vault,s));if(!g)throw new u("Provide the address of a current Longbow vault, or a Longbow V1 vault to withdraw from. Other vaults are not supported.");return g}function C(s,i){if(Object.keys(s).some(w=>!i.includes(w)))throw new u("Unsupported Longbow input. Use the fields in the tool schema.")}var X=s=>{async function i(e){try{return await e()}catch(t){throw new u(s.plainError(t))}}async function w(){let e=s.clientFor(m);if(await e.getChainId()!==m)throw new u("Longbow requires a client on chain 4663.");return e}async function g(e,t){let[o,r,a,n]=await Promise.all([e.readContract({address:t.vault,abi:c,functionName:"asset"}),e.readContract({address:t.vault,abi:c,functionName:"decimals"}),e.readContract({address:t.asset,abi:c,functionName:"decimals"}),_(e,t.vault)]);if(typeof o!="string"||!A(o,t.asset))throw new u("Longbow vault asset does not match the recorded deployment.");if(r!==18||a!==t.decimals)throw new u("Longbow token decimals do not match the recorded deployment.");return{vault:t.vault,key:t.key,name:t.name,asset:{address:b(t.asset),symbol:t.symbol,decimals:a,chainId:m},share:{address:t.vault,symbol:n,decimals:r,chainId:m}}}async function y(e,t,o,r){let a=R(o.amount,O);if(BigInt(a)===0n)throw new u("The expected output is too small for a nonzero simulation minimum.");let n=await s.preview(e,t);if(n.changes.filter(l=>l.token.chainId===o.token.chainId&&A(l.token.address,o.token.address)&&l.token.decimals===o.token.decimals).reduce((l,v)=>l+BigInt(v.amount),0n)<BigInt(a))throw new u("Longbow simulated output is below the expected minimum.");let d=n.changes.map(({token:l,amount:v})=>{let U=v.startsWith("-");return`${U?"-":"+"}${s.formatAmount(U?v.slice(1):v,l.decimals)} ${l.symbol} (${l.address}, chain ${l.chainId})`}).join("; ");return{txs:e,preview:n,expectedOutput:o,minimumOutput:{token:o.token,amount:a},minimumEnforcedOnchain:!1,summary:`${r} ${d}. Simulation only; no on-chain minimum is enforced by these ERC-4626 calls. ${n.summary}`}}async function Y(e){C(e,[]);let t=await w();return Promise.all(T.map(async o=>{let[r,a,n,f]=await Promise.all([g(t,o),t.readContract({address:o.vault,abi:c,functionName:"totalAssets"}),t.readContract({address:o.vault,abi:c,functionName:"performanceFee"}),t.readContract({address:o.vault,abi:c,functionName:"managementFee"})]);return{...r,totalAssets:{token:r.asset,amount:h(a).toString()},fees:{performanceFeeE18:h(n).toString(),managementFeeE18:h(f).toString()},caveat:"Morpho V2 max views can be zero even when writes succeed. Simulate the requested action; listing does not prove availability."}}))}async function K(e,t){C(e,["vault","amount","wrapEth"]),S(t);let o=q(e.vault),r=j(e.amount,"Deposit amount");if(e.wrapEth!==void 0&&typeof e.wrapEth!="boolean")throw new u("wrapEth must be a boolean.");if(e.wrapEth&&!A(o.asset,p.tokens.WETH.address))throw new u("Only a WETH vault accepts explicit ETH wrapping.");let a=await w(),n=await g(a,o),f=h(await a.readContract({address:n.vault,abi:c,functionName:"previewDeposit",args:[r]})),d=[];return e.wrapEth&&d.push(s.unsignedTx({to:n.asset.address,data:L({abi:Q,functionName:"deposit"}),value:r.toString(),chainId:m,description:`Wrap ${s.formatAmount(r.toString(),18)} ETH into WETH for ${n.name}.`})),d.push(s.approval(n.asset.address,n.vault,r.toString(),m)),d.push(s.unsignedTx({to:n.vault,data:L({abi:c,functionName:"deposit",args:[r,b(t)]}),value:"0",chainId:m,description:`Deposit ${s.formatAmount(r.toString(),n.asset.decimals)} ${n.asset.symbol} into ${n.name}.`})),y(d,t,{token:n.share,amount:f.toString()},`Deposit into ${n.name}.`)}async function J(e,t){C(e,["vault","shares"]),S(t);let o=q(e.vault,!0),r=e.shares==="all"?void 0:j(e.shares,"Redeem shares"),a=await w(),n=await g(a,o),f=h(await a.readContract({address:n.vault,abi:c,functionName:"balanceOf",args:[t]})),d=r??f;if(d===0n||d>f)throw new u("The wallet has insufficient Longbow shares for this redemption.");let l=h(await a.readContract({address:n.vault,abi:c,functionName:"previewRedeem",args:[d]})),v=[s.unsignedTx({to:n.vault,data:L({abi:c,functionName:"redeem",args:[d,b(t),b(t)]}),value:"0",chainId:m,description:`Redeem ${s.formatAmount(d.toString(),n.share.decimals)} shares from ${n.name} into ${n.asset.symbol}.`})];return y(v,t,{token:n.asset,amount:l.toString()},`Redeem from ${n.name}.`)}let E={type:"string",enum:T.map(e=>e.vault),description:"Current vault address on chain 4663."},$=H('Positive amount of the vault asset in base units, never a human-unit decimal (USDG has 6 decimals, WETH 18). Example: "1000000" = 1 USDG.'),k=(e,t,o,r)=>({name:e,inputSchema:{type:"object",description:e==="longbow_deposit"?"Deposit the selected vault\u2019s USDG (6 decimals) or WETH (18 decimals) in base units for shares. Exit with longbow_withdraw; check positions after confirmation.":e==="longbow_withdraw"?"Redeem shares in 18-decimal base units, or shares all for a full exit. Returns USDG or WETH according to the selected vault.":"List current Longbow vault assets and shares; exit existing shares with longbow_withdraw.",properties:t,required:o,additionalProperties:!1},execute:(a,n)=>i(()=>r(a,n))});return{tools:[k("longbow_list",{},[],Y),k("longbow_deposit",{vault:E,amount:$,wrapEth:{type:"boolean",default:!1,description:"Explicitly wrap this amount of native ETH before depositing into the WETH vault."}},["vault","amount"],K),k("longbow_withdraw",{vault:{...E,enum:[...E.enum,...D.map(e=>e.vault)],description:"Current vault address, or a Longbow V1 vault (withdraw-only) on chain 4663."},shares:{anyOf:[$,{const:"all"}],description:"Share base units (18 decimals), or all for the fresh wallet share balance. Returns the underlying asset, including WETH."}},["vault","shares"],J)],positions:e=>i(async()=>{S(e);let t=await w();return(await Promise.all([...T,...D].map(async r=>{let a=await g(t,r),n=h(await t.readContract({address:a.vault,abi:c,functionName:"balanceOf",args:[e]}));if(n===0n)return[];let f=h(await t.readContract({address:a.vault,abi:c,functionName:"previewRedeem",args:[n]}));return[{module:"longbow",id:`${m}:${a.vault.toLowerCase()}`,chainId:m,assets:[{token:a.asset,amount:f.toString()}],description:`${a.name}: ${s.formatAmount(n.toString(),a.share.decimals)} shares (${a.share.address}, ${a.share.decimals} decimals). Underlying is a preview, not a guaranteed redemption.`}]}))).flat()})}};function he(s){return I("longbow",[X(s),P(s),F(s),x(s),M(s),V(s),{tools:B(s,"longbow",T.map(i=>({vault:i.vault,asset:{address:b(i.asset),symbol:i.symbol,decimals:i.decimals,chainId:m}})))}])}export{D as a,X as b,he as c};
1
+ import{a as B}from"./YAVWSW3G.js";import{c as x}from"./R73R4KN3.js";import{c as P}from"./QIB6OMQV.js";import{b as M}from"./72EV7TGI.js";import{k as F}from"./YXXK6EPI.js";import{c as V}from"./UCHJYWGU.js";import{a as _}from"./A3PN3PK3.js";import{b as O,o as R}from"./GYPMUYB5.js";import{b as I}from"./SPJCSEKP.js";import{a as S}from"./43LI5NKJ.js";import{a as H}from"./66F5ZH34.js";import{g as A,m as N,n as W}from"./NWNYJ26T.js";import{b as m,j as G}from"./TI727O2H.js";import{a as u}from"./XSD5NL7J.js";import{encodeFunctionData as L,getAddress as b,parseAbi as z}from"viem";var c=z(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)","function balanceOf(address) view returns (uint256)","function previewDeposit(uint256 assets) view returns (uint256)","function previewRedeem(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),Q=z(["function deposit() payable"]),p=G[m],T=[{key:"core",name:"Longbow Core USDG",vault:p.vaults.longbowCore.address,asset:p.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"frontier",name:"Longbow Frontier USDG",vault:p.vaults.longbowFrontier.address,asset:p.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"eth",name:"Longbow ETH",vault:p.vaults.longbowEth.address,asset:p.tokens.WETH.address,symbol:"WETH",decimals:18}],D=[{key:"v1-usdg",name:"Longbow USDG Core V1 (legacy)",vault:b("0x8cb8AA35228c96C1C4E956E69AbAEBCc2aA7Dcfe"),asset:p.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"v1-weth",name:"Longbow WETH Core V1 (legacy)",vault:b("0x93777a9b917be3c8259c84456222f43a01dd6492"),asset:p.tokens.WETH.address,symbol:"WETH",decimals:18}];function j(s,i){return W(s,`${i} must be positive and within the uint256 range.`,{notString:`${i} must be a positive integer string in base units.`,positive:!0})}function h(s){return N(s,"Longbow returned an invalid integer response.")}function q(s,i=!1){if(typeof s!="string")throw new u("Provide the address of a current Longbow vault.");let w=D.find(y=>A(y.vault,s));if(w&&!i)throw new u("Longbow V1 vaults are withdraw-only; deposit into a current V2 vault from longbow_list instead.");let g=w??T.find(y=>A(y.vault,s));if(!g)throw new u("Provide the address of a current Longbow vault, or a Longbow V1 vault to withdraw from. Other vaults are not supported.");return g}function C(s,i){if(Object.keys(s).some(w=>!i.includes(w)))throw new u("Unsupported Longbow input. Use the fields in the tool schema.")}var X=s=>{async function i(e){try{return await e()}catch(t){throw new u(s.plainError(t))}}async function w(){let e=s.clientFor(m);if(await e.getChainId()!==m)throw new u("Longbow requires a client on chain 4663.");return e}async function g(e,t){let[o,r,a,n]=await Promise.all([e.readContract({address:t.vault,abi:c,functionName:"asset"}),e.readContract({address:t.vault,abi:c,functionName:"decimals"}),e.readContract({address:t.asset,abi:c,functionName:"decimals"}),_(e,t.vault)]);if(typeof o!="string"||!A(o,t.asset))throw new u("Longbow vault asset does not match the recorded deployment.");if(r!==18||a!==t.decimals)throw new u("Longbow token decimals do not match the recorded deployment.");return{vault:t.vault,key:t.key,name:t.name,asset:{address:b(t.asset),symbol:t.symbol,decimals:a,chainId:m},share:{address:t.vault,symbol:n,decimals:r,chainId:m}}}async function y(e,t,o,r){let a=R(o.amount,O);if(BigInt(a)===0n)throw new u("The expected output is too small for a nonzero simulation minimum.");let n=await s.preview(e,t);if(n.changes.filter(l=>l.token.chainId===o.token.chainId&&A(l.token.address,o.token.address)&&l.token.decimals===o.token.decimals).reduce((l,v)=>l+BigInt(v.amount),0n)<BigInt(a))throw new u("Longbow simulated output is below the expected minimum.");let d=n.changes.map(({token:l,amount:v})=>{let U=v.startsWith("-");return`${U?"-":"+"}${s.formatAmount(U?v.slice(1):v,l.decimals)} ${l.symbol} (${l.address}, chain ${l.chainId})`}).join("; ");return{txs:e,preview:n,expectedOutput:o,minimumOutput:{token:o.token,amount:a},minimumEnforcedOnchain:!1,summary:`${r} ${d}. Simulation only; no on-chain minimum is enforced by these ERC-4626 calls. ${n.summary}`}}async function Y(e){C(e,[]);let t=await w();return Promise.all(T.map(async o=>{let[r,a,n,f]=await Promise.all([g(t,o),t.readContract({address:o.vault,abi:c,functionName:"totalAssets"}),t.readContract({address:o.vault,abi:c,functionName:"performanceFee"}),t.readContract({address:o.vault,abi:c,functionName:"managementFee"})]);return{...r,totalAssets:{token:r.asset,amount:h(a).toString()},fees:{performanceFeeE18:h(n).toString(),managementFeeE18:h(f).toString()},caveat:"Morpho V2 max views can be zero even when writes succeed. Simulate the requested action; listing does not prove availability."}}))}async function K(e,t){C(e,["vault","amount","wrapEth"]),S(t);let o=q(e.vault),r=j(e.amount,"Deposit amount");if(e.wrapEth!==void 0&&typeof e.wrapEth!="boolean")throw new u("wrapEth must be a boolean.");if(e.wrapEth&&!A(o.asset,p.tokens.WETH.address))throw new u("Only a WETH vault accepts explicit ETH wrapping.");let a=await w(),n=await g(a,o),f=h(await a.readContract({address:n.vault,abi:c,functionName:"previewDeposit",args:[r]})),d=[];return e.wrapEth&&d.push(s.unsignedTx({to:n.asset.address,data:L({abi:Q,functionName:"deposit"}),value:r.toString(),chainId:m,description:`Wrap ${s.formatAmount(r.toString(),18)} ETH into WETH for ${n.name}.`})),d.push(s.approval(n.asset.address,n.vault,r.toString(),m)),d.push(s.unsignedTx({to:n.vault,data:L({abi:c,functionName:"deposit",args:[r,b(t)]}),value:"0",chainId:m,description:`Deposit ${s.formatAmount(r.toString(),n.asset.decimals)} ${n.asset.symbol} into ${n.name}.`})),y(d,t,{token:n.share,amount:f.toString()},`Deposit into ${n.name}.`)}async function J(e,t){C(e,["vault","shares"]),S(t);let o=q(e.vault,!0),r=e.shares==="all"?void 0:j(e.shares,"Redeem shares"),a=await w(),n=await g(a,o),f=h(await a.readContract({address:n.vault,abi:c,functionName:"balanceOf",args:[t]})),d=r??f;if(d===0n||d>f)throw new u("The wallet has insufficient Longbow shares for this redemption.");let l=h(await a.readContract({address:n.vault,abi:c,functionName:"previewRedeem",args:[d]})),v=[s.unsignedTx({to:n.vault,data:L({abi:c,functionName:"redeem",args:[d,b(t),b(t)]}),value:"0",chainId:m,description:`Redeem ${s.formatAmount(d.toString(),n.share.decimals)} shares from ${n.name} into ${n.asset.symbol}.`})];return y(v,t,{token:n.asset,amount:l.toString()},`Redeem from ${n.name}.`)}let E={type:"string",enum:T.map(e=>e.vault),description:"Current vault address on chain 4663."},$=H('Positive amount of the vault asset in base units, never a human-unit decimal (USDG has 6 decimals, WETH 18). Example: "1000000" = 1 USDG.'),k=(e,t,o,r)=>({name:e,inputSchema:{type:"object",description:e==="longbow_deposit"?"Deposit the selected vault\u2019s USDG (6 decimals) or WETH (18 decimals) in base units for shares. Exit with longbow_withdraw; check positions after confirmation.":e==="longbow_withdraw"?"Redeem shares in 18-decimal base units, or shares all for a full exit. Returns USDG or WETH according to the selected vault.":"List current Longbow vault assets and shares; exit existing shares with longbow_withdraw.",properties:t,required:o,additionalProperties:!1},execute:(a,n)=>i(()=>r(a,n))});return{tools:[k("longbow_list",{},[],Y),k("longbow_deposit",{vault:E,amount:$,wrapEth:{type:"boolean",default:!1,description:"Explicitly wrap this amount of native ETH before depositing into the WETH vault."}},["vault","amount"],K),k("longbow_withdraw",{vault:{...E,enum:[...E.enum,...D.map(e=>e.vault)],description:"Current vault address, or a Longbow V1 vault (withdraw-only) on chain 4663."},shares:{anyOf:[$,{const:"all"}],description:"Share base units (18 decimals), or all for the fresh wallet share balance. Returns the underlying asset, including WETH."}},["vault","shares"],J)],positions:e=>i(async()=>{S(e);let t=await w();return(await Promise.all([...T,...D].map(async r=>{let a=await g(t,r),n=h(await t.readContract({address:a.vault,abi:c,functionName:"balanceOf",args:[e]}));if(n===0n)return[];let f=h(await t.readContract({address:a.vault,abi:c,functionName:"previewRedeem",args:[n]}));return[{module:"longbow",id:`${m}:${a.vault.toLowerCase()}`,chainId:m,assets:[{token:a.asset,amount:f.toString()}],description:`${a.name}: ${s.formatAmount(n.toString(),a.share.decimals)} shares (${a.share.address}, ${a.share.decimals} decimals). Underlying is a preview, not a guaranteed redemption.`}]}))).flat()})}};function he(s){return I("longbow",[X(s),P(s),F(s),x(s),M(s),V(s),{tools:B(s,"longbow",T.map(i=>({vault:i.vault,asset:{address:b(i.asset),symbol:i.symbol,decimals:i.decimals,chainId:m}})))}])}export{D as a,X as b,he as c};
@@ -1 +1 @@
1
- import{a as j}from"./USEF3QKG.js";import{a as O}from"./4NDIYRH5.js";import{j as E}from"./2GXHYI23.js";import{b as D}from"./SPJCSEKP.js";import{a as R}from"./43LI5NKJ.js";import{c as H}from"./SCG5HWMN.js";import{c as b,e as h,g as v,i as _,l as B}from"./NWNYJ26T.js";import{b as L}from"./IX3GZMTM.js";import{b as u,j as M}from"./TI727O2H.js";import{a as p}from"./XSD5NL7J.js";import{a as z}from"./JXOEJPJ4.js";import{encodeFunctionData as S,parseAbi as ne,zeroAddress as P}from"viem";import{encodeAbiParameters as F,encodeFunctionData as X,keccak256 as U,parseAbi as Y}from"viem";var I=M[u].merkl.distributor.address,A="Claim rewards on Merkl (Powered by Merkl \u2014 https://app.merkl.xyz)",W=`${A}. No claimable rewards on Robinhood Chain. Pending rewards must settle into a Merkle root before they can be claimed.`,C=Y(["function claimed(address user,address token) view returns (uint208 amount,uint48 timestamp,bytes32 merkleRoot)","function getMerkleRoot() view returns (bytes32)","function claim(address[] users,address[] tokens,uint256[] amounts,bytes32[][] proofs)"]);function J(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{64}$/.test(s)}function k(){throw new p("Merkl returned an unexpected response. Please refetch rewards.")}function T(s){typeof s!="string"&&k();let d=L(s);if(d>=1n<<256n)throw new p("The Merkl reward amount exceeds the uint256 range.");return d.toString()}function ee(s){let d=[],m=new Set;for(let c of s)if((!h(c)||!h(c.chain)||!Number.isSafeInteger(c.chain.id))&&k(),c.chain.id===u){Array.isArray(c.rewards)||k();for(let r of c.rewards){if((!h(r)||typeof r.distributionLayer!="string"||!h(r.token))&&k(),r.distributionLayer!=="TREE"||(Number.isSafeInteger(r.token.chainId)||k(),r.token.chainId!==u)||(Array.isArray(r.proofs)||k(),!r.proofs.length))continue;(!r.proofs.every(J)||typeof r.token.address!="string"||typeof r.token.symbol!="string"||!r.token.symbol.trim()||typeof r.token.decimals!="number"||!Number.isInteger(r.token.decimals)||r.token.decimals<0||r.token.decimals>255)&&k(),R(r.token.address);let t=T(r.amount),n=T(r.pending);if(BigInt(t)===0n)continue;let e=r.token.address.toLowerCase();if(m.has(e))throw new p("Merkl returned duplicate token leaves. Please refetch rewards.");m.add(e),d.push({token:{address:r.token.address,chainId:u,decimals:r.token.decimals,symbol:r.token.symbol},amount:t,pending:n,proofs:r.proofs})}}return d}function re(s,d,m){let c=U(F([{type:"address"},{type:"address"},{type:"uint256"}],[s,d.token.address,BigInt(d.amount)]));for(let r of d.proofs){let t=BigInt(c)<BigInt(r)?[c,r]:[r,c];c=U(F([{type:"bytes32"},{type:"bytes32"}],t))}if(!v(c,m))throw new p("The Merkl proof does not match the active root. Please refetch rewards.")}function Z(s){if(!h(s)||Object.keys(s).length)throw new p("This Merkl tool takes no arguments and uses the connected wallet.")}async function q(s,d){let m=await K(s,d),c=new Map,r=[],t=new Set;for(let n of m)if((!h(n)||!h(n.chain)||!Number.isSafeInteger(n.chain.id))&&k(),n.chain.id===u){Array.isArray(n.rewards)||k();for(let e of n.rewards){if((!h(e)||typeof e.distributionLayer!="string"||!h(e.token)||!Number.isSafeInteger(e.token.chainId))&&k(),e.token.chainId!==u)continue;(typeof e.token.address!="string"||typeof e.token.symbol!="string"||!e.token.symbol.trim()||typeof e.token.decimals!="number"||!Number.isInteger(e.token.decimals)||e.token.decimals<0||e.token.decimals>255)&&k(),R(e.token.address);let a=T(e.amount),i=T(e.pending),o=`${e.distributionLayer}:${e.token.address.toLowerCase()}`;if(t.has(o))throw new p("Merkl returned duplicate earning rows. Please refetch rewards.");t.add(o);let l={address:e.token.address,symbol:e.token.symbol,decimals:e.token.decimals,chainId:u},f="0";if(e.distributionLayer==="TREE"){let g=await s.clientFor(u).readContract({address:I,abi:C,functionName:"claimed",args:[d,l.address]});(!Array.isArray(g)||typeof g[0]!="bigint"||g[0]<0n||g[0]>=1n<<208n)&&k(),f=g[0].toString(),c.set(l.address.toLowerCase(),f)}r.push({token:l,amount:a,pending:i,claimed:f,claimable:"0",distributionLayer:e.distributionLayer,status:e.distributionLayer!=="TREE"?"unsupported_distribution_layer":BigInt(a)>BigInt(f)?"awaiting_verified_proof":BigInt(i)>0n?"pending_settlement":"settled"})}}return{body:m,earnings:r,claimedSnapshot:c}}async function K(s,d){return R(d),H(s.http,`https://api.merkl.xyz/v4/users/${d}/rewards/summary?chainId=${u}`,{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},m=>Array.isArray(m))}async function x(s,d,m){return N(s,d,m)}async function N(s,d,m,c){R(d);let r=ee(m??await K(s,d)),t=s.clientFor(u),n=[];for(let a of r){let i=c?.get(a.token.address.toLowerCase());if(i===void 0){let o=await t.readContract({address:I,abi:C,functionName:"claimed",args:[d,a.token.address]});if(!Array.isArray(o)||typeof o[0]!="bigint"||o[0]<0n||o[0]>=1n<<208n)throw new p("The Merkl claimed balance could not be read. Please try again.");i=o[0].toString()}BigInt(a.amount)<=BigInt(i)||n.push({...a,claimed:i,claimable:(BigInt(a.amount)-BigInt(i)).toString()})}if(!n.length)return[];let e=await t.readContract({address:I,abi:C,functionName:"getMerkleRoot"});if(!J(e))throw new p("The active Merkl root could not be read. Please try again.");for(let a of n)re(d,a,e);return n}var te=s=>{async function d(t){try{return await t()}catch(n){throw new p(s.plainError(n))}}function m(t){let n=t.amount.startsWith("-"),e=n?t.amount.slice(1):t.amount;return`${n?"-":""}${s.formatAmount(e,t.token.decimals)} ${z(t.token.symbol)} (${t.token.address}, chain ${t.token.chainId}, ${t.token.decimals} decimals)`}let c=t=>x(s,t);return{tools:[{name:"merkl_rewards",description:"Read claimable rewards (Powered by Merkl \u2014 https://app.merkl.xyz).",inputSchema:{type:"object",properties:{},additionalProperties:!1,description:"Read rewards (Powered by Merkl \u2014 https://app.merkl.xyz)."},execute:(t,n)=>d(async()=>{Z(t);let{body:e,earnings:a,claimedSnapshot:i}=await q(s,n),o=await N(s,n,e,i);for(let l of a){let f=o.find(g=>v(g.token.address,l.token.address)&&l.distributionLayer==="TREE");f&&(l.claimed=f.claimed,l.claimable=f.claimable,l.status="claimable")}return{earnings:a,rewards:o.map(({proofs:l,...f})=>f),summary:o.length?`${A}. Claimable reward leaves: ${o.map(l=>m({token:l.token,amount:l.claimable})).join("; ")}. Wrapped leaves may transfer underlying tokens; claim preview shows the received assets. Pending rewards appear separately in earnings and are excluded from claimable amounts.`:`${W} Earnings include pending-only and unsupported distribution layers; an unverified amount is never presented as claimable.`}})},{name:"merkl_claim",description:A,inputSchema:{type:"object",properties:{},additionalProperties:!1,description:A},execute:(t,n)=>d(async()=>{Z(t);let e=await c(n);if(!e.length)return{txs:[],summary:W};let a=[s.unsignedTx({to:I,chainId:u,value:"0",description:A,data:X({abi:C,functionName:"claim",args:[e.map(()=>n),e.map(o=>o.token.address),e.map(o=>BigInt(o.amount)),e.map(o=>o.proofs)]})})],i=await s.preview(a,n);return{txs:a,summary:`${A}. Prepared unsigned claim. Expected wallet changes: ${i.changes.length?i.changes.map(m).join("; "):"no token transfers in simulation"}. ${i.summary}`}})}],positions:t=>d(async()=>{let{body:n,earnings:e,claimedSnapshot:a}=await q(s,t),i=await N(s,t,n,a);return e.flatMap(o=>{let l=o.distributionLayer==="TREE"?i.find(V=>v(V.token.address,o.token.address)):void 0,f=BigInt(o.pending)>0n;if(!l&&!f)return[];let g="Merkl pending rewards are not yet claimable and are excluded from valuation.";return[{module:"merkl",id:`${u}:${o.token.address.toLowerCase()}${o.distributionLayer==="TREE"?"":`:${o.distributionLayer}`}`,chainId:u,assets:l?[{token:l.token,amount:l.claimable}]:[],economics:{principal:[],debt:[],backing:[],coverage:f?{complete:!1,reason:g}:{complete:!0},rewards:[...l?[E("claimable",{token:l.token,amount:l.claimable,source:"merkl.claimable",claim:{tool:"merkl_claim",args:{}}})]:[],...f?[E("unpaid",{token:o.token,amount:null,source:"merkl.pending",unknownReason:g})]:[]]},description:`${A}. Unclaimed reward leaf; wrapped rewards may transfer underlying assets. Pending rewards are excluded from valuation.`}]})})}},ge=s=>D("merkl",[te(s),O(s),G(s),j(s)]);var $=M[u].merkl.distributor.address,w=ne(["function operators(address,address) view returns (uint256)","function claimRecipient(address,address) view returns (address)","function toggleOperator(address,address)","function setClaimRecipient(address,address)","function claim(address[],address[],uint256[],bytes32[][])","function claimWithRecipient(address[],address[],uint256[],bytes32[][],address[],bytes[])"]),Q="Provide a valid address.";function y(s,d=!1){let m=_(s,Q);return d?m:B(m,Q)}var G=s=>{let d=()=>s.clientFor(u),m=async(r,t,n)=>{let e=[s.unsignedTx({to:$,chainId:u,value:"0",data:r,description:t})],a=await s.preview(e,n);return{txs:e,preview:a,summary:`Powered by Merkl \u2014 https://app.merkl.xyz. ${t} ${a.summary}`}},c=(r,t,n,e)=>({name:`merkl_${r}`,inputSchema:{type:"object",properties:t,required:n,additionalProperties:!1},execute:async(a,i)=>{try{let o=Object.keys(a).find(l=>!Object.hasOwn(t,l));if(o)throw new p(`Unsupported Merkl input: ${o}.`);return await e(a,y(i))}catch(o){throw new p(s.plainError(o))}}});return{tools:[c("claim_config",{token:{...b,description:"Reward token address; zero address selects the global setting where supported."},operator:{...b,description:"Address of the operator whose claim permission is read or changed."}},[],async(r,t)=>{let n=y(r.token??P,!0),e=y(await d().readContract({address:$,abi:w,functionName:"claimRecipient",args:[t,P]}),!0),a=y(await d().readContract({address:$,abi:w,functionName:"claimRecipient",args:[t,n]}),!0),i;if(r.operator!==void 0){let o=await d().readContract({address:$,abi:w,functionName:"operators",args:[t,y(r.operator,!0)]});if(o!==0n&&o!==1n)throw new p("Merkl returned invalid operator authorization.");i=o===1n}return{chainId:u,wallet:t,token:n,defaultRecipient:e,tokenRecipient:a,effectiveRecipient:a!==P?a:e!==P?e:t,...i===void 0?{}:{operatorEnabled:i},summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Zero recipient restores self-claims. Token overrides take precedence over the global recipient."}}),c("set_operator",{operator:{...b,description:"Address of the operator whose claim permission is read or changed."},enabled:{type:"boolean",description:"true grants claim permission; false revokes it."}},["operator","enabled"],async(r,t)=>{let n=y(r.operator,!0);if(typeof r.enabled!="boolean")throw new p("Provide enabled as boolean.");let e=await d().readContract({address:$,abi:w,functionName:"operators",args:[t,n]});if(e!==0n&&e!==1n)throw new p("Merkl returned invalid operator authorization.");return e===1n===r.enabled?{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Operator already has the requested state; no transaction needed."}:m(S({abi:w,functionName:"toggleOperator",args:[t,n]}),`${r.enabled?"Authorize":"Revoke"} Merkl claims by ${n} for ${t}. Zero operator grants permissionless claiming; configured recipients still apply. The contract toggles the observed state; preview and confirmation must remain current.`,t)}),c("set_recipient",{recipient:{...b,description:"Address to receive rewards; zero restores the default where supported."},token:{...b,description:"Reward token address; zero address selects the global setting where supported."}},["recipient"],async(r,t)=>{let n=y(r.recipient,!0),e=y(r.token??P,!0);return m(S({abi:w,functionName:"setClaimRecipient",args:[n,e]}),`Set Merkl reward recipient for ${e===P?"all tokens":e} to ${n===P?`self (${t})`:n}. This redirects future claims; token-specific overrides remain authoritative.`,t)}),c("claim_to",{recipient:{...b,description:"Address to receive rewards; zero restores the default where supported."},token:{...b,description:"Reward token address; zero address selects the global setting where supported."},data:{type:"string",pattern:"^0x([0-9a-fA-F]{2})*$",maxLength:16386,description:"Optional recipient callback data as 0x-prefixed hex bytes."}},["recipient"],async(r,t)=>{let n=y(r.recipient),e=r.token===void 0?void 0:y(r.token),a=r.data??"0x";if(typeof a!="string"||!/^0x([0-9a-fA-F]{2})*$/.test(a)||a.length>16386)throw new p("Provide callback data as at most 8192 hexadecimal bytes.");let i=(await x(s,t)).filter(o=>!e||v(o.token.address,e));return i.length?m(S({abi:w,functionName:"claimWithRecipient",args:[i.map(()=>t),i.map(o=>o.token.address),i.map(o=>BigInt(o.amount)),i.map(o=>o.proofs),i.map(()=>n),i.map(()=>a)]}),`Claim ${i.map(o=>`${o.claimable} ${o.token.symbol} base units (token ${o.token.address}, decimals ${o.token.decimals})`).join("; ")} to ${n}, overriding saved claim recipients for this claim only. Callback data for each leaf: ${a}. Inspect all callback effects in preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for the selected token."}}),c("claim_for",{user:{...b,description:"Address of the user whose rewards are claimed."},token:{...b,description:"Reward token address; zero address selects the global setting where supported."}},["user"],async(r,t)=>{let n=y(r.user),e=r.token===void 0?void 0:y(r.token),a=(await x(s,n)).filter(i=>!e||v(i.token.address,e));return a.length?m(S({abi:w,functionName:"claim",args:[a.map(()=>n),a.map(i=>i.token.address),a.map(i=>BigInt(i.amount)),a.map(i=>i.proofs)]}),`Claim Merkl rewards for ${n}; caller ${t} pays gas. The user's saved recipients control payment. Claim authorization and actual receipts must pass preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for this user."}})]}};export{G as a,x as b,te as c,ge as d};
1
+ import{a as j}from"./USEF3QKG.js";import{a as O}from"./WCI3FHWT.js";import{j as E}from"./2GXHYI23.js";import{b as D}from"./SPJCSEKP.js";import{a as R}from"./43LI5NKJ.js";import{c as H}from"./SCG5HWMN.js";import{c as b,e as h,g as v,i as _,l as B}from"./NWNYJ26T.js";import{b as L}from"./IX3GZMTM.js";import{b as u,j as M}from"./TI727O2H.js";import{a as p}from"./XSD5NL7J.js";import{a as z}from"./JXOEJPJ4.js";import{encodeFunctionData as S,parseAbi as ne,zeroAddress as P}from"viem";import{encodeAbiParameters as F,encodeFunctionData as X,keccak256 as U,parseAbi as Y}from"viem";var I=M[u].merkl.distributor.address,A="Claim rewards on Merkl (Powered by Merkl \u2014 https://app.merkl.xyz)",W=`${A}. No claimable rewards on Robinhood Chain. Pending rewards must settle into a Merkle root before they can be claimed.`,C=Y(["function claimed(address user,address token) view returns (uint208 amount,uint48 timestamp,bytes32 merkleRoot)","function getMerkleRoot() view returns (bytes32)","function claim(address[] users,address[] tokens,uint256[] amounts,bytes32[][] proofs)"]);function J(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{64}$/.test(s)}function k(){throw new p("Merkl returned an unexpected response. Please refetch rewards.")}function T(s){typeof s!="string"&&k();let d=L(s);if(d>=1n<<256n)throw new p("The Merkl reward amount exceeds the uint256 range.");return d.toString()}function ee(s){let d=[],m=new Set;for(let c of s)if((!h(c)||!h(c.chain)||!Number.isSafeInteger(c.chain.id))&&k(),c.chain.id===u){Array.isArray(c.rewards)||k();for(let r of c.rewards){if((!h(r)||typeof r.distributionLayer!="string"||!h(r.token))&&k(),r.distributionLayer!=="TREE"||(Number.isSafeInteger(r.token.chainId)||k(),r.token.chainId!==u)||(Array.isArray(r.proofs)||k(),!r.proofs.length))continue;(!r.proofs.every(J)||typeof r.token.address!="string"||typeof r.token.symbol!="string"||!r.token.symbol.trim()||typeof r.token.decimals!="number"||!Number.isInteger(r.token.decimals)||r.token.decimals<0||r.token.decimals>255)&&k(),R(r.token.address);let t=T(r.amount),n=T(r.pending);if(BigInt(t)===0n)continue;let e=r.token.address.toLowerCase();if(m.has(e))throw new p("Merkl returned duplicate token leaves. Please refetch rewards.");m.add(e),d.push({token:{address:r.token.address,chainId:u,decimals:r.token.decimals,symbol:r.token.symbol},amount:t,pending:n,proofs:r.proofs})}}return d}function re(s,d,m){let c=U(F([{type:"address"},{type:"address"},{type:"uint256"}],[s,d.token.address,BigInt(d.amount)]));for(let r of d.proofs){let t=BigInt(c)<BigInt(r)?[c,r]:[r,c];c=U(F([{type:"bytes32"},{type:"bytes32"}],t))}if(!v(c,m))throw new p("The Merkl proof does not match the active root. Please refetch rewards.")}function Z(s){if(!h(s)||Object.keys(s).length)throw new p("This Merkl tool takes no arguments and uses the connected wallet.")}async function q(s,d){let m=await K(s,d),c=new Map,r=[],t=new Set;for(let n of m)if((!h(n)||!h(n.chain)||!Number.isSafeInteger(n.chain.id))&&k(),n.chain.id===u){Array.isArray(n.rewards)||k();for(let e of n.rewards){if((!h(e)||typeof e.distributionLayer!="string"||!h(e.token)||!Number.isSafeInteger(e.token.chainId))&&k(),e.token.chainId!==u)continue;(typeof e.token.address!="string"||typeof e.token.symbol!="string"||!e.token.symbol.trim()||typeof e.token.decimals!="number"||!Number.isInteger(e.token.decimals)||e.token.decimals<0||e.token.decimals>255)&&k(),R(e.token.address);let a=T(e.amount),i=T(e.pending),o=`${e.distributionLayer}:${e.token.address.toLowerCase()}`;if(t.has(o))throw new p("Merkl returned duplicate earning rows. Please refetch rewards.");t.add(o);let l={address:e.token.address,symbol:e.token.symbol,decimals:e.token.decimals,chainId:u},f="0";if(e.distributionLayer==="TREE"){let g=await s.clientFor(u).readContract({address:I,abi:C,functionName:"claimed",args:[d,l.address]});(!Array.isArray(g)||typeof g[0]!="bigint"||g[0]<0n||g[0]>=1n<<208n)&&k(),f=g[0].toString(),c.set(l.address.toLowerCase(),f)}r.push({token:l,amount:a,pending:i,claimed:f,claimable:"0",distributionLayer:e.distributionLayer,status:e.distributionLayer!=="TREE"?"unsupported_distribution_layer":BigInt(a)>BigInt(f)?"awaiting_verified_proof":BigInt(i)>0n?"pending_settlement":"settled"})}}return{body:m,earnings:r,claimedSnapshot:c}}async function K(s,d){return R(d),H(s.http,`https://api.merkl.xyz/v4/users/${d}/rewards/summary?chainId=${u}`,{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},m=>Array.isArray(m))}async function x(s,d,m){return N(s,d,m)}async function N(s,d,m,c){R(d);let r=ee(m??await K(s,d)),t=s.clientFor(u),n=[];for(let a of r){let i=c?.get(a.token.address.toLowerCase());if(i===void 0){let o=await t.readContract({address:I,abi:C,functionName:"claimed",args:[d,a.token.address]});if(!Array.isArray(o)||typeof o[0]!="bigint"||o[0]<0n||o[0]>=1n<<208n)throw new p("The Merkl claimed balance could not be read. Please try again.");i=o[0].toString()}BigInt(a.amount)<=BigInt(i)||n.push({...a,claimed:i,claimable:(BigInt(a.amount)-BigInt(i)).toString()})}if(!n.length)return[];let e=await t.readContract({address:I,abi:C,functionName:"getMerkleRoot"});if(!J(e))throw new p("The active Merkl root could not be read. Please try again.");for(let a of n)re(d,a,e);return n}var te=s=>{async function d(t){try{return await t()}catch(n){throw new p(s.plainError(n))}}function m(t){let n=t.amount.startsWith("-"),e=n?t.amount.slice(1):t.amount;return`${n?"-":""}${s.formatAmount(e,t.token.decimals)} ${z(t.token.symbol)} (${t.token.address}, chain ${t.token.chainId}, ${t.token.decimals} decimals)`}let c=t=>x(s,t);return{tools:[{name:"merkl_rewards",description:"Read claimable rewards (Powered by Merkl \u2014 https://app.merkl.xyz).",inputSchema:{type:"object",properties:{},additionalProperties:!1,description:"Read rewards (Powered by Merkl \u2014 https://app.merkl.xyz)."},execute:(t,n)=>d(async()=>{Z(t);let{body:e,earnings:a,claimedSnapshot:i}=await q(s,n),o=await N(s,n,e,i);for(let l of a){let f=o.find(g=>v(g.token.address,l.token.address)&&l.distributionLayer==="TREE");f&&(l.claimed=f.claimed,l.claimable=f.claimable,l.status="claimable")}return{earnings:a,rewards:o.map(({proofs:l,...f})=>f),summary:o.length?`${A}. Claimable reward leaves: ${o.map(l=>m({token:l.token,amount:l.claimable})).join("; ")}. Wrapped leaves may transfer underlying tokens; claim preview shows the received assets. Pending rewards appear separately in earnings and are excluded from claimable amounts.`:`${W} Earnings include pending-only and unsupported distribution layers; an unverified amount is never presented as claimable.`}})},{name:"merkl_claim",description:A,inputSchema:{type:"object",properties:{},additionalProperties:!1,description:A},execute:(t,n)=>d(async()=>{Z(t);let e=await c(n);if(!e.length)return{txs:[],summary:W};let a=[s.unsignedTx({to:I,chainId:u,value:"0",description:A,data:X({abi:C,functionName:"claim",args:[e.map(()=>n),e.map(o=>o.token.address),e.map(o=>BigInt(o.amount)),e.map(o=>o.proofs)]})})],i=await s.preview(a,n);return{txs:a,summary:`${A}. Prepared unsigned claim. Expected wallet changes: ${i.changes.length?i.changes.map(m).join("; "):"no token transfers in simulation"}. ${i.summary}`}})}],positions:t=>d(async()=>{let{body:n,earnings:e,claimedSnapshot:a}=await q(s,t),i=await N(s,t,n,a);return e.flatMap(o=>{let l=o.distributionLayer==="TREE"?i.find(V=>v(V.token.address,o.token.address)):void 0,f=BigInt(o.pending)>0n;if(!l&&!f)return[];let g="Merkl pending rewards are not yet claimable and are excluded from valuation.";return[{module:"merkl",id:`${u}:${o.token.address.toLowerCase()}${o.distributionLayer==="TREE"?"":`:${o.distributionLayer}`}`,chainId:u,assets:l?[{token:l.token,amount:l.claimable}]:[],economics:{principal:[],debt:[],backing:[],coverage:f?{complete:!1,reason:g}:{complete:!0},rewards:[...l?[E("claimable",{token:l.token,amount:l.claimable,source:"merkl.claimable",claim:{tool:"merkl_claim",args:{}}})]:[],...f?[E("unpaid",{token:o.token,amount:null,source:"merkl.pending",unknownReason:g})]:[]]},description:`${A}. Unclaimed reward leaf; wrapped rewards may transfer underlying assets. Pending rewards are excluded from valuation.`}]})})}},ge=s=>D("merkl",[te(s),O(s),G(s),j(s)]);var $=M[u].merkl.distributor.address,w=ne(["function operators(address,address) view returns (uint256)","function claimRecipient(address,address) view returns (address)","function toggleOperator(address,address)","function setClaimRecipient(address,address)","function claim(address[],address[],uint256[],bytes32[][])","function claimWithRecipient(address[],address[],uint256[],bytes32[][],address[],bytes[])"]),Q="Provide a valid address.";function y(s,d=!1){let m=_(s,Q);return d?m:B(m,Q)}var G=s=>{let d=()=>s.clientFor(u),m=async(r,t,n)=>{let e=[s.unsignedTx({to:$,chainId:u,value:"0",data:r,description:t})],a=await s.preview(e,n);return{txs:e,preview:a,summary:`Powered by Merkl \u2014 https://app.merkl.xyz. ${t} ${a.summary}`}},c=(r,t,n,e)=>({name:`merkl_${r}`,inputSchema:{type:"object",properties:t,required:n,additionalProperties:!1},execute:async(a,i)=>{try{let o=Object.keys(a).find(l=>!Object.hasOwn(t,l));if(o)throw new p(`Unsupported Merkl input: ${o}.`);return await e(a,y(i))}catch(o){throw new p(s.plainError(o))}}});return{tools:[c("claim_config",{token:{...b,description:"Reward token address; zero address selects the global setting where supported."},operator:{...b,description:"Address of the operator whose claim permission is read or changed."}},[],async(r,t)=>{let n=y(r.token??P,!0),e=y(await d().readContract({address:$,abi:w,functionName:"claimRecipient",args:[t,P]}),!0),a=y(await d().readContract({address:$,abi:w,functionName:"claimRecipient",args:[t,n]}),!0),i;if(r.operator!==void 0){let o=await d().readContract({address:$,abi:w,functionName:"operators",args:[t,y(r.operator,!0)]});if(o!==0n&&o!==1n)throw new p("Merkl returned invalid operator authorization.");i=o===1n}return{chainId:u,wallet:t,token:n,defaultRecipient:e,tokenRecipient:a,effectiveRecipient:a!==P?a:e!==P?e:t,...i===void 0?{}:{operatorEnabled:i},summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Zero recipient restores self-claims. Token overrides take precedence over the global recipient."}}),c("set_operator",{operator:{...b,description:"Address of the operator whose claim permission is read or changed."},enabled:{type:"boolean",description:"true grants claim permission; false revokes it."}},["operator","enabled"],async(r,t)=>{let n=y(r.operator,!0);if(typeof r.enabled!="boolean")throw new p("Provide enabled as boolean.");let e=await d().readContract({address:$,abi:w,functionName:"operators",args:[t,n]});if(e!==0n&&e!==1n)throw new p("Merkl returned invalid operator authorization.");return e===1n===r.enabled?{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Operator already has the requested state; no transaction needed."}:m(S({abi:w,functionName:"toggleOperator",args:[t,n]}),`${r.enabled?"Authorize":"Revoke"} Merkl claims by ${n} for ${t}. Zero operator grants permissionless claiming; configured recipients still apply. The contract toggles the observed state; preview and confirmation must remain current.`,t)}),c("set_recipient",{recipient:{...b,description:"Address to receive rewards; zero restores the default where supported."},token:{...b,description:"Reward token address; zero address selects the global setting where supported."}},["recipient"],async(r,t)=>{let n=y(r.recipient,!0),e=y(r.token??P,!0);return m(S({abi:w,functionName:"setClaimRecipient",args:[n,e]}),`Set Merkl reward recipient for ${e===P?"all tokens":e} to ${n===P?`self (${t})`:n}. This redirects future claims; token-specific overrides remain authoritative.`,t)}),c("claim_to",{recipient:{...b,description:"Address to receive rewards; zero restores the default where supported."},token:{...b,description:"Reward token address; zero address selects the global setting where supported."},data:{type:"string",pattern:"^0x([0-9a-fA-F]{2})*$",maxLength:16386,description:"Optional recipient callback data as 0x-prefixed hex bytes."}},["recipient"],async(r,t)=>{let n=y(r.recipient),e=r.token===void 0?void 0:y(r.token),a=r.data??"0x";if(typeof a!="string"||!/^0x([0-9a-fA-F]{2})*$/.test(a)||a.length>16386)throw new p("Provide callback data as at most 8192 hexadecimal bytes.");let i=(await x(s,t)).filter(o=>!e||v(o.token.address,e));return i.length?m(S({abi:w,functionName:"claimWithRecipient",args:[i.map(()=>t),i.map(o=>o.token.address),i.map(o=>BigInt(o.amount)),i.map(o=>o.proofs),i.map(()=>n),i.map(()=>a)]}),`Claim ${i.map(o=>`${o.claimable} ${o.token.symbol} base units (token ${o.token.address}, decimals ${o.token.decimals})`).join("; ")} to ${n}, overriding saved claim recipients for this claim only. Callback data for each leaf: ${a}. Inspect all callback effects in preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for the selected token."}}),c("claim_for",{user:{...b,description:"Address of the user whose rewards are claimed."},token:{...b,description:"Reward token address; zero address selects the global setting where supported."}},["user"],async(r,t)=>{let n=y(r.user),e=r.token===void 0?void 0:y(r.token),a=(await x(s,n)).filter(i=>!e||v(i.token.address,e));return a.length?m(S({abi:w,functionName:"claim",args:[a.map(()=>n),a.map(i=>i.token.address),a.map(i=>BigInt(i.amount)),a.map(i=>i.proofs)]}),`Claim Merkl rewards for ${n}; caller ${t} pays gas. The user's saved recipients control payment. Claim authorization and actual receipts must pass preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for this user."}})]}};export{G as a,x as b,te as c,ge as d};
@@ -1 +1 @@
1
- import{d as o}from"./M6SQPOOL.js";import{a as i}from"./LFSJDFMY.js";import{b as a}from"./TI727O2H.js";var m=s=>({tools:i.map(e=>{let t=e==="netnet_blackjack_claim"?"seriesId":"sessionId";return{name:e,inputSchema:{description:"Self-only recovery on chain 4663, available without an active identity or subscription; every action requires local human confirmation. Card counts use whole units.",type:"object",additionalProperties:!1,required:[t],properties:{[t]:{type:"string",pattern:"^[1-9][0-9]{0,77}$",description:t==="seriesId"?'Card series id holding your parked blackjack chips, as a decimal string. Example: "1".':'Blackjack session id to settle, as a decimal string. Example: "1".'}}},execute:async(n,c)=>{let r=await o(e,n,c,s.clientFor(a));return{txs:r.txs,summary:r.decision}}}})});export{m as a};
1
+ import{d as o}from"./OFWTO4N6.js";import{a as i}from"./LFSJDFMY.js";import{b as a}from"./TI727O2H.js";var m=s=>({tools:i.map(e=>{let t=e==="netnet_blackjack_claim"?"seriesId":"sessionId";return{name:e,inputSchema:{description:"Self-only recovery on chain 4663, available without an active identity or subscription; every action requires local human confirmation. Card counts use whole units.",type:"object",additionalProperties:!1,required:[t],properties:{[t]:{type:"string",pattern:"^[1-9][0-9]{0,77}$",description:t==="seriesId"?'Card series id holding your parked blackjack chips, as a decimal string. Example: "1".':'Blackjack session id to settle, as a decimal string. Example: "1".'}}},execute:async(n,c)=>{let r=await o(e,n,c,s.clientFor(a));return{txs:r.txs,summary:r.decision}}}})});export{m as a};
@@ -1,4 +1,4 @@
1
- import{e as c}from"./NWNYJ26T.js";import{a as x}from"./XSD5NL7J.js";import{a as C}from"./JXOEJPJ4.js";var E="https://mcp.fobo.fun/mcp",k="2025-03-26",A=4*1024*1024,n=d=>new x(`FOBO ${d}. Nothing was signed. Please try again.`);function z(d={}){let O=d.fetch??globalThis.fetch,y=d.endpoint??E,b=d.timeoutMs??3e4;if(!Number.isSafeInteger(b)||b<=0)throw n("timeout must be a positive number of milliseconds");let s,i=k,P=0,u=!1,o,e=new Set;async function w(r,l,m,h="POST",f=!1){let t=new AbortController;e.add(t);let v,p=++P,S=new Promise((g,a)=>{v=setTimeout(()=>{a(n("request timed out")),t.abort()},b)});try{return await Promise.race([S,(async()=>{let g={"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":i};m&&(g["Mcp-Session-Id"]=m);let a=await O(y,{method:h,headers:g,signal:t.signal,...h==="POST"?{body:JSON.stringify({jsonrpc:"2.0",...f?{}:{id:p},method:r,params:l})}:{}});if(h==="DELETE"&&(a.ok||a.status===405||a.status===404))return{};if(f){if(!a.ok)throw n("session initialization was refused");return await a.body?.cancel(),{}}let R=await M(a,p);if(!a.ok&&R.error?.code!==-32e3)throw n("service is unavailable");return{rpc:R,session:a.headers.get("Mcp-Session-Id")??void 0}})()])}catch(g){throw g instanceof x?g:n("could not be reached")}finally{clearTimeout(v),e.delete(t),t.abort()}}async function T(){if(u)throw n("client is closed");s||(o||(o=(async()=>{let r=await w("initialize",{protocolVersion:k,capabilities:{},clientInfo:{name:"oak",version:"0.3.1"}});if(r.rpc?.error||!r.session||!c(r.rpc?.result))throw n("did not provide an MCP session");let l=r.rpc.result.protocolVersion;if(typeof l=="string"){if(!["2025-03-26","2025-06-18","2025-11-25"].includes(l))throw n("MCP protocol version is unsupported");i=l}if(u)throw n("client is closed");await w("notifications/initialized",{},r.session,"POST",!0),s=r.session})().finally(()=>{o=void 0})),await o)}return{async call(r,l){await T();for(let m=0;m<2;m++){if(u)throw n("client is closed");let h=s,{rpc:f}=await w("tools/call",{name:r,arguments:l},h);if(f?.error?.code===-32e3){if(m===1)throw n("session expired");s===h&&(s=void 0),await T();continue}if(!f||f.error)throw n("request was refused");let t=f.result;if(c(t)&&t.isError===!0){let v=Array.isArray(t.content)?t.content.filter(c).filter(p=>p.type==="text"&&typeof p.text=="string").map(p=>p.text).join(" "):"";throw new x(`FOBO refused the request: ${C(v||"The tool returned an error.")}. Nothing was signed. Ask for a fresh summary.`)}if(c(t)&&c(t.structuredContent))return t.structuredContent;if(c(t)&&"content"in t){if(!Array.isArray(t.content)||t.content.length!==1||!c(t.content[0])||t.content[0].type!=="text"||typeof t.content[0].text!="string")throw n("returned an unsupported tool answer");try{return JSON.parse(t.content[0].text)}catch{throw n("returned an unreadable tool answer")}}return t}throw n("session expired")},async close(){if(u)return;u=!0;for(let l of e)l.abort();let r=s;s=void 0,r&&await w("",{},r,"DELETE")}}}async function M(d,O){let y=d.body?.getReader();if(!y)throw n("returned an empty response");let b=new TextDecoder,s=d.headers.get("Content-Type")?.includes("text/event-stream"),i="",P=0,u=o=>{let e;try{e=JSON.parse(o)}catch{throw n("returned an unreadable response")}if(!c(e)||e.jsonrpc!=="2.0")throw n("returned an invalid response");if(!(s&&!("id"in e)&&typeof e.method=="string")){if(e.id!==O||"result"in e=="error"in e||"error"in e&&(!c(e.error)||typeof e.error.code!="number"))throw n("returned an invalid response");return e}};try{for(;;){let o=await y.read();if(P+=o.value?.length??0,P>A)throw n("response is too large");if(i+=b.decode(o.value,{stream:!o.done}),s){i=i.replace(/\r\n/g,`
1
+ import{e as c}from"./NWNYJ26T.js";import{a as x}from"./XSD5NL7J.js";import{a as C}from"./JXOEJPJ4.js";var E="https://mcp.fobo.fun/mcp",k="2025-03-26",A=4*1024*1024,n=d=>new x(`FOBO ${d}. Nothing was signed. Please try again.`);function z(d={}){let O=d.fetch??globalThis.fetch,y=d.endpoint??E,b=d.timeoutMs??3e4;if(!Number.isSafeInteger(b)||b<=0)throw n("timeout must be a positive number of milliseconds");let s,i=k,P=0,u=!1,o,e=new Set;async function w(r,l,m,h="POST",f=!1){let t=new AbortController;e.add(t);let v,p=++P,S=new Promise((g,a)=>{v=setTimeout(()=>{a(n("request timed out")),t.abort()},b)});try{return await Promise.race([S,(async()=>{let g={"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":i};m&&(g["Mcp-Session-Id"]=m);let a=await O(y,{method:h,headers:g,signal:t.signal,...h==="POST"?{body:JSON.stringify({jsonrpc:"2.0",...f?{}:{id:p},method:r,params:l})}:{}});if(h==="DELETE"&&(a.ok||a.status===405||a.status===404))return{};if(f){if(!a.ok)throw n("session initialization was refused");return await a.body?.cancel(),{}}let R=await M(a,p);if(!a.ok&&R.error?.code!==-32e3)throw n("service is unavailable");return{rpc:R,session:a.headers.get("Mcp-Session-Id")??void 0}})()])}catch(g){throw g instanceof x?g:n("could not be reached")}finally{clearTimeout(v),e.delete(t),t.abort()}}async function T(){if(u)throw n("client is closed");s||(o||(o=(async()=>{let r=await w("initialize",{protocolVersion:k,capabilities:{},clientInfo:{name:"oak",version:"0.3.2"}});if(r.rpc?.error||!r.session||!c(r.rpc?.result))throw n("did not provide an MCP session");let l=r.rpc.result.protocolVersion;if(typeof l=="string"){if(!["2025-03-26","2025-06-18","2025-11-25"].includes(l))throw n("MCP protocol version is unsupported");i=l}if(u)throw n("client is closed");await w("notifications/initialized",{},r.session,"POST",!0),s=r.session})().finally(()=>{o=void 0})),await o)}return{async call(r,l){await T();for(let m=0;m<2;m++){if(u)throw n("client is closed");let h=s,{rpc:f}=await w("tools/call",{name:r,arguments:l},h);if(f?.error?.code===-32e3){if(m===1)throw n("session expired");s===h&&(s=void 0),await T();continue}if(!f||f.error)throw n("request was refused");let t=f.result;if(c(t)&&t.isError===!0){let v=Array.isArray(t.content)?t.content.filter(c).filter(p=>p.type==="text"&&typeof p.text=="string").map(p=>p.text).join(" "):"";throw new x(`FOBO refused the request: ${C(v||"The tool returned an error.")}. Nothing was signed. Ask for a fresh summary.`)}if(c(t)&&c(t.structuredContent))return t.structuredContent;if(c(t)&&"content"in t){if(!Array.isArray(t.content)||t.content.length!==1||!c(t.content[0])||t.content[0].type!=="text"||typeof t.content[0].text!="string")throw n("returned an unsupported tool answer");try{return JSON.parse(t.content[0].text)}catch{throw n("returned an unreadable tool answer")}}return t}throw n("session expired")},async close(){if(u)return;u=!0;for(let l of e)l.abort();let r=s;s=void 0,r&&await w("",{},r,"DELETE")}}}async function M(d,O){let y=d.body?.getReader();if(!y)throw n("returned an empty response");let b=new TextDecoder,s=d.headers.get("Content-Type")?.includes("text/event-stream"),i="",P=0,u=o=>{let e;try{e=JSON.parse(o)}catch{throw n("returned an unreadable response")}if(!c(e)||e.jsonrpc!=="2.0")throw n("returned an invalid response");if(!(s&&!("id"in e)&&typeof e.method=="string")){if(e.id!==O||"result"in e=="error"in e||"error"in e&&(!c(e.error)||typeof e.error.code!="number"))throw n("returned an invalid response");return e}};try{for(;;){let o=await y.read();if(P+=o.value?.length??0,P>A)throw n("response is too large");if(i+=b.decode(o.value,{stream:!o.done}),s){i=i.replace(/\r\n/g,`
2
2
  `);let e;for(;(e=i.indexOf(`
3
3
 
4
4
  `))!==-1;){let w=i.slice(0,e);i=i.slice(e+2);let T=w.split(`
@@ -1 +1 @@
1
- import{b as z,c as I}from"./LFSJDFMY.js";import{b as W}from"./DMDOSHV7.js";import{d as R,e as _}from"./XV6F3RET.js";import{K as E}from"./AXHFNE6L.js";import{a as F}from"./43LI5NKJ.js";import{d as H,g as A,i as j}from"./NWNYJ26T.js";import{b as C,t as S}from"./TI727O2H.js";import{a as s}from"./XSD5NL7J.js";import{encodeFunctionData as M,erc20Abi as V,getAddress as Z,keccak256 as K,zeroAddress as x}from"viem";var r=R.turbo,h=R.blackjack,g=m=>j(m,"Provide an explicit card address.",H);function G(m,d){if(/^uint\d*\[\]$/.test(m.type)&&Array.isArray(d))return d.map(c=>G({...m,type:m.type.slice(0,-2)},c));if(/^uint\d*$/.test(m.type)&&(typeof d!="string"||!/^(0|[1-9]\d*)$/.test(d)))throw new s("Card integers must be canonical decimal strings, without leading zeros.");return W(m,d)}var J=["buy","cashOut","claimExpiry","refund","safeTransferFrom","safeBatchTransferFrom"],X=["liquidate","recordKnock","liquidateKnock","clearKnock","recordDrift","settle","markVoid","depositHouse","depositPutPot","withdrawHouse","withdrawPutPot","createSeries","haltSales","resumeSales","sweepFees","skim"],Q=m=>m==="netnet_turbo_action"||m.startsWith("netnet_blackjack_")&&["netnet_blackjack_finalize","netnet_blackjack_expire","netnet_blackjack_claim"].includes(m);async function de(m,d,c,k){if(F(c),!Q(m))throw new s("No local NetNet card action builder exists.");let v=m!=="netnet_turbo_action";if(Object.keys(d).some(e=>!(v?["sessionId","seriesId"]:["operation","values","minimum","allowZeroPayout"]).includes(e)))throw new s("Unexpected card action argument.");if(v&&!z(m,d))throw new s("Recovery accepts exactly one positive decimal session or series ID.");if(await k.getChainId()!==C)throw new s("NetNet cards require chain 4663.");let w=await k.getBlock();if(w.number===null||!w.hash)throw new s("Card action block is unavailable.");let p=(e,t,i=[])=>k.readContract({address:e.address,abi:e.abi,functionName:t,args:i,blockNumber:w.number});for(let e of v?[r,h]:[r]){let t=await k.getCode({address:e.address,blockNumber:w.number});if(!t||K(t)!==e.codeHash)throw new s("NetNet card runtime changed or is unavailable. Requalify this deployment before signing.")}for(let e of v?Object.values(_):[_.turbo]){let t=await k.getCode({address:Z(e.address),blockNumber:w.number});if(!t||K(t)!==e.codeHash)throw new s("NetNet linked card library changed or is unavailable. Requalify before signing.")}let l={txs:[],inputs:[],cards:[],decision:"",blockNumber:w.number,blockHash:w.hash},$=(e,t,i,a,o)=>({chainId:4663,collection:r.address,operator:e,from:t,to:i,id:a,amount:o,operation:t===x?"mint":i===x?"burn":"transfer"}),T=(e,t,i,a,o=[])=>{l.txs.push({to:e,chainId:C,value:"0",data:M({abi:t,functionName:i,args:a}),description:l.decision}),l.cards.push(o)},D=(e,t)=>{if(t<=0n||t>=1n<<128n)throw new s("Card payment must be positive and below the exact-approval ceiling.");l.inputs.push({token:e,amount:t,to:r.address}),T(e,V,"approve",[r.address,t])};if(v){if(g(await p(h,"cards"))!==r.address||g(await p(h,"turbo"))!==r.address)throw new s("Blackjack card wiring changed.");let e=m==="netnet_blackjack_claim";if(Object.keys(d).some(b=>b!==(e?"seriesId":"sessionId")))throw new s("Recovery accepts only its one exact session or series ID.");let t=E(e?d.seriesId:d.sessionId),i,a,o,u="Original-series parked payout; self-claim only.";if(e){if(i=t,a=await p(h,"unclaimedChips",[t,c]),o="claimUnclaimedChips",a===0n)throw new s("This wallet has no parked chips for that series.")}else{let b=await p(h,"sessionOf",[t]);if(!b||!A(b.player,c))throw new s("Recovery is limited to this wallet\u2019s recorded blackjack session.");let y=m==="netnet_blackjack_finalize";if(o=y?"finalize":"expireSession",b.state!==(y?2:1))throw new s(y?"Session is not Closing. Use its current on-chain state to choose recovery.":"Session is not Open. A Closing session uses finalize after its challenge window.");let N=y?b.closeAt:b.deadline;if(u=y?`Challenge ends ${new Date(Number(N)*1e3).toISOString()}.`:`Session deadline ${new Date(Number(N)*1e3).toISOString()}; player-only expiry until ${new Date(Number(N+3600n)*1e3).toISOString()}.`,w.timestamp<N)throw new s(`Recovery is not due until ${N} Unix seconds.`);i=await p(h,"tableSeries"),a=b.chips}if(i<=0n||a<0n)throw new s("Blackjack recovery accounting is unavailable.");return l.decision=`${o} ${e?"series":"session"} ${t} at ${h.address}: return ${a} whole cards of collection ${r.address}, series ${i}, to ${Z(c)}. ${u} Last on-chain chips may omit off-chain winnings; cards may be worthless. A failed receiver parks the payout at ${h.address}; self-claim only. ETH gas extra.`,T(h.address,h.abi,o,[t],a===0n?[]:[$(h.address,h.address,c,i,a)]),l.recovery={...e?{}:{sessionId:t.toString()},seriesId:i.toString(),count:a.toString(),player:c,operation:o},l}let n=String(d.operation);if(n==="setApprovalForAll")throw new s(I.setApprovalForAll);if(["convertPremiums","convertSleeveFees"].includes(n))throw new s(I.conversion);if(![...J,...X].includes(n))throw new s("Choose a qualified finite TURBO operation.");if(!Array.isArray(d.values))throw new s("Provide ordered TURBO values using decimal integer strings.");let U=n==="safeTransferFrom"||n==="safeBatchTransferFrom",B=r.abi.find(e=>e.name===n),q=U?B.inputs.slice(1,-1):B.inputs;if(d.values.length!==q.length)throw new s("TURBO values do not match the exact operation inputs.");let f=q.map((e,t)=>G(e,d.values[t])),O=g(await p(r,"manager")),L=g(await p(r,"sleeve")),P=[];if(U){if(d.minimum!==void 0||d.allowZeroPayout!==void 0)throw new s("Transfer has no payout floor.");let e=g(f[0]);if(e===x||A(e,c))throw new s("Name a nonzero, non-self card recipient.");let t=await k.getCode({address:e,blockNumber:w.number});if(t&&t!=="0x")throw new s("Card transfer to a contract requires qualified credit and recovery. New blackjack seating remains disabled.");let i=n==="safeTransferFrom"?[f[1]]:f[1],a=n==="safeTransferFrom"?[f[2]]:f[2];if(!i.length||i.length>8||i.length!==a.length||new Set(i.map(String)).size!==i.length||i.some((o,u)=>o<=0n||a[u]<=0n||u>0&&o<=i[u-1]))throw new s("Use at most eight unique positive series IDs in increasing order and exact positive counts.");for(let o=0;o<i.length;o++){if(await p(r,"balanceOf",[c,i[o]])<a[o])throw new s("Card transfer exceeds this wallet\u2019s balance.");P.push($(c,c,e,i[o],a[o])),l.inputs.push({token:r.address,id:i[o],amount:a[o],to:e,exact:!0})}l.decision=`Transfer whole cards of collection ${r.address}: ${i.map((o,u)=>`series ${o} count ${a[u]}`).join(", ")} to ${e}. Basis does not travel with cards; no operator approval. No payout; transfer is irreversible. ETH gas extra.`,f=[c,...f,"0x"]}else if(["buy","cashOut","claimExpiry","refund"].includes(n)){let e=f[0],t=f[1],i=await p(r,"seriesOf",[e]);if(!i||i.asset===x||t<=0n)throw new s("Choose a known series and positive whole-card count.");let a=i.side===0?g(i.asset):S.mainnet.usdg,o=await k.readContract({address:a,abi:V,functionName:"decimals",blockNumber:w.number});if((n==="buy"||n==="cashOut")&&(i.state!==1||w.timestamp>=i.expiry))throw new s("This TURBO series is not OPEN and unexpired.");if(n==="buy"){let[u]=await p(r,"quoteBuy",[e,t]);if(!u||u>f[2])throw new s("Current card quote exceeds the explicit maximum USDG payment.");if(d.minimum!==void 0||d.allowZeroPayout!==void 0)throw new s("Buy uses its exact count and maximum USDG price.");l.decision=`Spend at most ${f[2]} USDG base units (${S.mainnet.usdg}, decimals 6) at ${r.address}; receive ${t} whole cards, collection ${r.address}, series ${e}, into this wallet. Exact quoted approval ${u}; fees included. Strike ${i.strikeWad} WAD; expiry ${new Date(Number(i.expiry)*1e3).toISOString()}; cards can lose all value. Any residual USDG allowance requires zero cleanup. ETH gas extra.`,D(S.mainnet.usdg,u),P=[$(c,x,c,e,t)]}else{if(n==="cashOut"&&d.minimum!==void 0)throw new s("cashOut takes its one encoded minimum in values, not a second local minimum.");if(await p(r,"balanceOf",[c,e])<t)throw new s("Card burn exceeds this wallet\u2019s balance.");let u=n==="cashOut"?f[2]:E(d.minimum,!0);if(u===0n&&d.allowZeroPayout!==!0)throw new s("A zero payout floor requires allowZeroPayout:true and explicit human confirmation.");let b=0n;if(n==="cashOut"){let y=await p(r,"quoteCashOut",[e,t,c]);if(y[0]<u)throw new s("The current cash-out quote misses the payout minimum.");b=y[1]}else if(i.state!==(n==="claimExpiry"?3:4))throw new s("Expiry claims require EXPIRED; pro-rata refunds require VOID.");l.decision=`Burn ${t} whole cards of ${r.address}, series ${e}; ${n==="refund"?"series pro-rata VOID refund, not personal purchase-price repayment":n}; receive >=${u} base units of ${a} (decimals ${o}) into this wallet. ${n==="cashOut"?`Minimum encoded in calldata; current performance fee ${b}.`:"Floor is local simulation only; no on-chain minimum. Settled payout includes applicable fees."} Burned cards cannot be returned; ETH gas extra.`,P=[$(c,c,x,e,t)],l.inputs.push({token:r.address,id:e,amount:t,to:x,exact:!0}),l.receipt={token:a,minimum:u,recipient:c,enforcement:n==="cashOut"?"calldata":"simulation"}}}else{if(d.minimum!==void 0||d.allowZeroPayout!==void 0)throw new s("This TURBO operation has no caller payout floor.");if(["withdrawHouse","withdrawPutPot","createSeries","resumeSales"].includes(n)&&!A(O,c))throw new s(`This TURBO operation requires manager ${O}.`);if(n==="haltSales"&&!A(c,O)&&!A(c,g(await p(r,"halter"))))throw new s("TURBO haltSales requires the current manager or halter.");if(["depositHouse","depositPutPot","withdrawHouse","withdrawPutPot","createSeries"].includes(n)){let t=g(f[0]);if(!(await Promise.all(["asset0","asset1","asset2"].map(a=>p(r,a)))).some(a=>typeof a=="string"&&A(a,t)))throw new s("This is not a pinned TURBO reserve asset.")}l.decision=`${n} at ${r.address}; values ${JSON.stringify(f,(t,i)=>typeof i=="bigint"?String(i):i)}. Protocol capital/accounting action; manager ${O}; sleeve ${L}; no caller reward. ${n.startsWith("deposit")?"Irreversible house funding; no personal withdrawable balance.":n.startsWith("withdraw")?"Pays the current manager; operating and reservation floors still apply.":"Series state, risk or protocol fee allocation may change."} No card approval; ETH gas extra.`,(n==="depositHouse"||n==="depositPutPot")&&D(n==="depositHouse"?g(f[0]):S.mainnet.usdg,f[1])}if(l.decision.length>1024)throw new s("Card decision terms exceed the complete confirmation label capacity. Use fewer card IDs.");T(r.address,r.abi,n,f,P);for(let e of l.txs)e.description=l.decision;return l}export{J as a,X as b,Q as c,de as d};
1
+ import{b as z,c as I}from"./LFSJDFMY.js";import{b as W}from"./DMDOSHV7.js";import{d as R,e as _}from"./XV6F3RET.js";import{L as E}from"./XKLXVTSE.js";import{a as F}from"./43LI5NKJ.js";import{d as H,g as A,i as j}from"./NWNYJ26T.js";import{b as C,t as S}from"./TI727O2H.js";import{a as s}from"./XSD5NL7J.js";import{encodeFunctionData as M,erc20Abi as V,getAddress as Z,keccak256 as K,zeroAddress as x}from"viem";var r=R.turbo,h=R.blackjack,g=m=>j(m,"Provide an explicit card address.",H);function G(m,d){if(/^uint\d*\[\]$/.test(m.type)&&Array.isArray(d))return d.map(c=>G({...m,type:m.type.slice(0,-2)},c));if(/^uint\d*$/.test(m.type)&&(typeof d!="string"||!/^(0|[1-9]\d*)$/.test(d)))throw new s("Card integers must be canonical decimal strings, without leading zeros.");return W(m,d)}var J=["buy","cashOut","claimExpiry","refund","safeTransferFrom","safeBatchTransferFrom"],X=["liquidate","recordKnock","liquidateKnock","clearKnock","recordDrift","settle","markVoid","depositHouse","depositPutPot","withdrawHouse","withdrawPutPot","createSeries","haltSales","resumeSales","sweepFees","skim"],Q=m=>m==="netnet_turbo_action"||m.startsWith("netnet_blackjack_")&&["netnet_blackjack_finalize","netnet_blackjack_expire","netnet_blackjack_claim"].includes(m);async function de(m,d,c,k){if(F(c),!Q(m))throw new s("No local NetNet card action builder exists.");let v=m!=="netnet_turbo_action";if(Object.keys(d).some(e=>!(v?["sessionId","seriesId"]:["operation","values","minimum","allowZeroPayout"]).includes(e)))throw new s("Unexpected card action argument.");if(v&&!z(m,d))throw new s("Recovery accepts exactly one positive decimal session or series ID.");if(await k.getChainId()!==C)throw new s("NetNet cards require chain 4663.");let w=await k.getBlock();if(w.number===null||!w.hash)throw new s("Card action block is unavailable.");let p=(e,t,i=[])=>k.readContract({address:e.address,abi:e.abi,functionName:t,args:i,blockNumber:w.number});for(let e of v?[r,h]:[r]){let t=await k.getCode({address:e.address,blockNumber:w.number});if(!t||K(t)!==e.codeHash)throw new s("NetNet card runtime changed or is unavailable. Requalify this deployment before signing.")}for(let e of v?Object.values(_):[_.turbo]){let t=await k.getCode({address:Z(e.address),blockNumber:w.number});if(!t||K(t)!==e.codeHash)throw new s("NetNet linked card library changed or is unavailable. Requalify before signing.")}let l={txs:[],inputs:[],cards:[],decision:"",blockNumber:w.number,blockHash:w.hash},$=(e,t,i,a,o)=>({chainId:4663,collection:r.address,operator:e,from:t,to:i,id:a,amount:o,operation:t===x?"mint":i===x?"burn":"transfer"}),T=(e,t,i,a,o=[])=>{l.txs.push({to:e,chainId:C,value:"0",data:M({abi:t,functionName:i,args:a}),description:l.decision}),l.cards.push(o)},D=(e,t)=>{if(t<=0n||t>=1n<<128n)throw new s("Card payment must be positive and below the exact-approval ceiling.");l.inputs.push({token:e,amount:t,to:r.address}),T(e,V,"approve",[r.address,t])};if(v){if(g(await p(h,"cards"))!==r.address||g(await p(h,"turbo"))!==r.address)throw new s("Blackjack card wiring changed.");let e=m==="netnet_blackjack_claim";if(Object.keys(d).some(b=>b!==(e?"seriesId":"sessionId")))throw new s("Recovery accepts only its one exact session or series ID.");let t=E(e?d.seriesId:d.sessionId),i,a,o,u="Original-series parked payout; self-claim only.";if(e){if(i=t,a=await p(h,"unclaimedChips",[t,c]),o="claimUnclaimedChips",a===0n)throw new s("This wallet has no parked chips for that series.")}else{let b=await p(h,"sessionOf",[t]);if(!b||!A(b.player,c))throw new s("Recovery is limited to this wallet\u2019s recorded blackjack session.");let y=m==="netnet_blackjack_finalize";if(o=y?"finalize":"expireSession",b.state!==(y?2:1))throw new s(y?"Session is not Closing. Use its current on-chain state to choose recovery.":"Session is not Open. A Closing session uses finalize after its challenge window.");let N=y?b.closeAt:b.deadline;if(u=y?`Challenge ends ${new Date(Number(N)*1e3).toISOString()}.`:`Session deadline ${new Date(Number(N)*1e3).toISOString()}; player-only expiry until ${new Date(Number(N+3600n)*1e3).toISOString()}.`,w.timestamp<N)throw new s(`Recovery is not due until ${N} Unix seconds.`);i=await p(h,"tableSeries"),a=b.chips}if(i<=0n||a<0n)throw new s("Blackjack recovery accounting is unavailable.");return l.decision=`${o} ${e?"series":"session"} ${t} at ${h.address}: return ${a} whole cards of collection ${r.address}, series ${i}, to ${Z(c)}. ${u} Last on-chain chips may omit off-chain winnings; cards may be worthless. A failed receiver parks the payout at ${h.address}; self-claim only. ETH gas extra.`,T(h.address,h.abi,o,[t],a===0n?[]:[$(h.address,h.address,c,i,a)]),l.recovery={...e?{}:{sessionId:t.toString()},seriesId:i.toString(),count:a.toString(),player:c,operation:o},l}let n=String(d.operation);if(n==="setApprovalForAll")throw new s(I.setApprovalForAll);if(["convertPremiums","convertSleeveFees"].includes(n))throw new s(I.conversion);if(![...J,...X].includes(n))throw new s("Choose a qualified finite TURBO operation.");if(!Array.isArray(d.values))throw new s("Provide ordered TURBO values using decimal integer strings.");let U=n==="safeTransferFrom"||n==="safeBatchTransferFrom",B=r.abi.find(e=>e.name===n),q=U?B.inputs.slice(1,-1):B.inputs;if(d.values.length!==q.length)throw new s("TURBO values do not match the exact operation inputs.");let f=q.map((e,t)=>G(e,d.values[t])),O=g(await p(r,"manager")),L=g(await p(r,"sleeve")),P=[];if(U){if(d.minimum!==void 0||d.allowZeroPayout!==void 0)throw new s("Transfer has no payout floor.");let e=g(f[0]);if(e===x||A(e,c))throw new s("Name a nonzero, non-self card recipient.");let t=await k.getCode({address:e,blockNumber:w.number});if(t&&t!=="0x")throw new s("Card transfer to a contract requires qualified credit and recovery. New blackjack seating remains disabled.");let i=n==="safeTransferFrom"?[f[1]]:f[1],a=n==="safeTransferFrom"?[f[2]]:f[2];if(!i.length||i.length>8||i.length!==a.length||new Set(i.map(String)).size!==i.length||i.some((o,u)=>o<=0n||a[u]<=0n||u>0&&o<=i[u-1]))throw new s("Use at most eight unique positive series IDs in increasing order and exact positive counts.");for(let o=0;o<i.length;o++){if(await p(r,"balanceOf",[c,i[o]])<a[o])throw new s("Card transfer exceeds this wallet\u2019s balance.");P.push($(c,c,e,i[o],a[o])),l.inputs.push({token:r.address,id:i[o],amount:a[o],to:e,exact:!0})}l.decision=`Transfer whole cards of collection ${r.address}: ${i.map((o,u)=>`series ${o} count ${a[u]}`).join(", ")} to ${e}. Basis does not travel with cards; no operator approval. No payout; transfer is irreversible. ETH gas extra.`,f=[c,...f,"0x"]}else if(["buy","cashOut","claimExpiry","refund"].includes(n)){let e=f[0],t=f[1],i=await p(r,"seriesOf",[e]);if(!i||i.asset===x||t<=0n)throw new s("Choose a known series and positive whole-card count.");let a=i.side===0?g(i.asset):S.mainnet.usdg,o=await k.readContract({address:a,abi:V,functionName:"decimals",blockNumber:w.number});if((n==="buy"||n==="cashOut")&&(i.state!==1||w.timestamp>=i.expiry))throw new s("This TURBO series is not OPEN and unexpired.");if(n==="buy"){let[u]=await p(r,"quoteBuy",[e,t]);if(!u||u>f[2])throw new s("Current card quote exceeds the explicit maximum USDG payment.");if(d.minimum!==void 0||d.allowZeroPayout!==void 0)throw new s("Buy uses its exact count and maximum USDG price.");l.decision=`Spend at most ${f[2]} USDG base units (${S.mainnet.usdg}, decimals 6) at ${r.address}; receive ${t} whole cards, collection ${r.address}, series ${e}, into this wallet. Exact quoted approval ${u}; fees included. Strike ${i.strikeWad} WAD; expiry ${new Date(Number(i.expiry)*1e3).toISOString()}; cards can lose all value. Any residual USDG allowance requires zero cleanup. ETH gas extra.`,D(S.mainnet.usdg,u),P=[$(c,x,c,e,t)]}else{if(n==="cashOut"&&d.minimum!==void 0)throw new s("cashOut takes its one encoded minimum in values, not a second local minimum.");if(await p(r,"balanceOf",[c,e])<t)throw new s("Card burn exceeds this wallet\u2019s balance.");let u=n==="cashOut"?f[2]:E(d.minimum,!0);if(u===0n&&d.allowZeroPayout!==!0)throw new s("A zero payout floor requires allowZeroPayout:true and explicit human confirmation.");let b=0n;if(n==="cashOut"){let y=await p(r,"quoteCashOut",[e,t,c]);if(y[0]<u)throw new s("The current cash-out quote misses the payout minimum.");b=y[1]}else if(i.state!==(n==="claimExpiry"?3:4))throw new s("Expiry claims require EXPIRED; pro-rata refunds require VOID.");l.decision=`Burn ${t} whole cards of ${r.address}, series ${e}; ${n==="refund"?"series pro-rata VOID refund, not personal purchase-price repayment":n}; receive >=${u} base units of ${a} (decimals ${o}) into this wallet. ${n==="cashOut"?`Minimum encoded in calldata; current performance fee ${b}.`:"Floor is local simulation only; no on-chain minimum. Settled payout includes applicable fees."} Burned cards cannot be returned; ETH gas extra.`,P=[$(c,c,x,e,t)],l.inputs.push({token:r.address,id:e,amount:t,to:x,exact:!0}),l.receipt={token:a,minimum:u,recipient:c,enforcement:n==="cashOut"?"calldata":"simulation"}}}else{if(d.minimum!==void 0||d.allowZeroPayout!==void 0)throw new s("This TURBO operation has no caller payout floor.");if(["withdrawHouse","withdrawPutPot","createSeries","resumeSales"].includes(n)&&!A(O,c))throw new s(`This TURBO operation requires manager ${O}.`);if(n==="haltSales"&&!A(c,O)&&!A(c,g(await p(r,"halter"))))throw new s("TURBO haltSales requires the current manager or halter.");if(["depositHouse","depositPutPot","withdrawHouse","withdrawPutPot","createSeries"].includes(n)){let t=g(f[0]);if(!(await Promise.all(["asset0","asset1","asset2"].map(a=>p(r,a)))).some(a=>typeof a=="string"&&A(a,t)))throw new s("This is not a pinned TURBO reserve asset.")}l.decision=`${n} at ${r.address}; values ${JSON.stringify(f,(t,i)=>typeof i=="bigint"?String(i):i)}. Protocol capital/accounting action; manager ${O}; sleeve ${L}; no caller reward. ${n.startsWith("deposit")?"Irreversible house funding; no personal withdrawable balance.":n.startsWith("withdraw")?"Pays the current manager; operating and reservation floors still apply.":"Series state, risk or protocol fee allocation may change."} No card approval; ETH gas extra.`,(n==="depositHouse"||n==="depositPutPot")&&D(n==="depositHouse"?g(f[0]):S.mainnet.usdg,f[1])}if(l.decision.length>1024)throw new s("Card decision terms exceed the complete confirmation label capacity. Use fewer card IDs.");T(r.address,r.abi,n,f,P);for(let e of l.txs)e.description=l.decision;return l}export{J as a,X as b,Q as c,de as d};
@@ -1 +1 @@
1
- import{a as N,b as F,e as b,f as i,k as T,m as O,o as B}from"./W7OCS4AM.js";import{c as I,e as A}from"./HQIS3QI7.js";import{h as x}from"./BSX4LFYI.js";import{a as o,e as k}from"./XSD5NL7J.js";function u(e,s){if(e.version!==1||e.chainId!==4663||!Object.hasOwn(b,e.kind))throw new o("Invalid FOBO pending action. Nothing further was signed.");if(!Number.isSafeInteger(s)||!Number.isSafeInteger(e.quotedAt)||s<e.quotedAt||s-e.quotedAt>=N)throw new o("This FOBO action expired. Nothing further was signed. Ask for a fresh summary, then say yes or no.")}function w(e,s){return typeof e=="string"&&e.toLowerCase()===s.toLowerCase()}function P(e){if(typeof e!="number"&&typeof e!="string"||!/^\d+$/.test(String(e)))throw new o("FOBO returned an invalid Permit2 nonce.");let s=Number(e);if(!Number.isSafeInteger(s)||s<0||s>=2**48)throw new o("FOBO returned an invalid Permit2 nonce.");return s}function _(e,s,n){let t=i(s),m=i(t.domain),c=i(t.message),p=i(c.details);if(!["buy","sell"].includes(e.kind)||![4663,"0x1237"].includes(m.chainId)||!w(m.verifyingContract,F.permit2)||t.primaryType!=="PermitSingle"||!w(c.spender,F.router)||!w(p.token,e.request._currencyIn)||!e.terms.amountIn)throw new o("FOBO permit does not match the approved token, spender or chain. Nothing further was signed.");return I({token:e.request._currencyIn,amount:BigInt(e.terms.amountIn),nonce:P(p.nonce),now:n})}async function*q(e,s,n){let t=structuredClone(s);u(t,n.now());let m=!1,c,p;try{if(t.kind==="launch"){let a=i(await e.call("sign_in_start",{account:t.wallet}));if(u(t,n.now()),typeof a.message!="string"||typeof a.ticket!="string"||!a.ticket||a.ticket.length>2e3)throw new o("FOBO returned an invalid sign-in ticket. Nothing was signed.");A(a.message,t.wallet,n.now());let f=await n.signMessage(a.message);u(t,n.now());let l=i(await e.call("sign_in_finish",{account:t.wallet,ticket:a.ticket,signature:f}));if(l.success===!1||l.ok===!1||l.isError===!0)throw new o("FOBO sign-in was refused. Nothing further was signed.");yield{kind:"signin",status:"signed"}}for(let a=0;a<4;a++){u(t,n.now());let f={...T(t),...c?{permit:c}:{}},h=a===0&&["limitOrder","cancel","claim"].includes(t.kind)&&typeof t.request._prepared=="string"?O({status:"ready",transactions:JSON.parse(String(t.request._prepared)).map(r=>({...r,from:t.wallet,gas:r.gasLimit}))}):O(await e.call(b[t.kind],f));u(t,n.now());let y=await B(t,h,n.now(),c?.message,n.readContract);if(h.status==="needs_approval"){if(m||c)throw new o("FOBO requested a repeated approval. Nothing further was signed. Ask for a fresh summary.");for(let r of y){u(t,n.now());let d=await n.sendTransaction(r);m=!0,await n.waitForReceipt(d),yield{kind:"approval",hash:d,tx:r,status:"mined"}}continue}if(h.status==="needs_signature"){if(c)throw new o("FOBO requested a repeated permit. Nothing further was signed.");p=_(t,h.typedData,n.now()),u(t,n.now());let r=await n.signTypedData(p);c={message:i(p).message,signature:r},yield{kind:"permit",status:"signed"};continue}if(p){let r=i(i(p).message),d=i(r.details);for(let S of y){let g=x(S.data,["0x0Af57F62982D03066ef917AcAd87F771c06528Ec","0x0000000000000000000000000000000000000000"]).permit;if(!g||!w(g.token,d.token)||g.amount!==BigInt(String(d.amount))||g.nonce!==Number(d.nonce)||g.expiration!==Number(d.expiration)||!w(g.spender,r.spender)||g.sigDeadline!==BigInt(String(r.sigDeadline)))throw new o("FOBO changed the exact signed permit in the swap. Nothing further was signed.")}}for(let r of y){u(t,n.now());let d=await n.sendTransaction(r);await n.waitForReceipt(d),yield{kind:"transaction",hash:d,tx:r,status:"mined"}}return}throw new o("FOBO preparation did not finish. Nothing further was signed. Ask for a fresh summary.")}catch(a){let f=m?" An exact approval was already sent; use oak_cleanup_allowances to review any allowance left.":"";throw new o(`${k(a).replaceAll("Nothing was signed.","Nothing further was signed.")} FOBO execution stopped; nothing further was signed.${f}`)}}export{_ as a,q as b};
1
+ import{a as N,b as F,e as b,f as i,k as T,m as O,o as B}from"./X5I5EJ5T.js";import{c as I,e as A}from"./SVKG4JOY.js";import{h as x}from"./BSX4LFYI.js";import{a as o,e as k}from"./XSD5NL7J.js";function u(e,s){if(e.version!==1||e.chainId!==4663||!Object.hasOwn(b,e.kind))throw new o("Invalid FOBO pending action. Nothing further was signed.");if(!Number.isSafeInteger(s)||!Number.isSafeInteger(e.quotedAt)||s<e.quotedAt||s-e.quotedAt>=N)throw new o("This FOBO action expired. Nothing further was signed. Ask for a fresh summary, then say yes or no.")}function w(e,s){return typeof e=="string"&&e.toLowerCase()===s.toLowerCase()}function P(e){if(typeof e!="number"&&typeof e!="string"||!/^\d+$/.test(String(e)))throw new o("FOBO returned an invalid Permit2 nonce.");let s=Number(e);if(!Number.isSafeInteger(s)||s<0||s>=2**48)throw new o("FOBO returned an invalid Permit2 nonce.");return s}function _(e,s,n){let t=i(s),m=i(t.domain),c=i(t.message),p=i(c.details);if(!["buy","sell"].includes(e.kind)||![4663,"0x1237"].includes(m.chainId)||!w(m.verifyingContract,F.permit2)||t.primaryType!=="PermitSingle"||!w(c.spender,F.router)||!w(p.token,e.request._currencyIn)||!e.terms.amountIn)throw new o("FOBO permit does not match the approved token, spender or chain. Nothing further was signed.");return I({token:e.request._currencyIn,amount:BigInt(e.terms.amountIn),nonce:P(p.nonce),now:n})}async function*q(e,s,n){let t=structuredClone(s);u(t,n.now());let m=!1,c,p;try{if(t.kind==="launch"){let a=i(await e.call("sign_in_start",{account:t.wallet}));if(u(t,n.now()),typeof a.message!="string"||typeof a.ticket!="string"||!a.ticket||a.ticket.length>2e3)throw new o("FOBO returned an invalid sign-in ticket. Nothing was signed.");A(a.message,t.wallet,n.now());let f=await n.signMessage(a.message);u(t,n.now());let l=i(await e.call("sign_in_finish",{account:t.wallet,ticket:a.ticket,signature:f}));if(l.success===!1||l.ok===!1||l.isError===!0)throw new o("FOBO sign-in was refused. Nothing further was signed.");yield{kind:"signin",status:"signed"}}for(let a=0;a<4;a++){u(t,n.now());let f={...T(t),...c?{permit:c}:{}},h=a===0&&["limitOrder","cancel","claim"].includes(t.kind)&&typeof t.request._prepared=="string"?O({status:"ready",transactions:JSON.parse(String(t.request._prepared)).map(r=>({...r,from:t.wallet,gas:r.gasLimit}))}):O(await e.call(b[t.kind],f));u(t,n.now());let y=await B(t,h,n.now(),c?.message,n.readContract);if(h.status==="needs_approval"){if(m||c)throw new o("FOBO requested a repeated approval. Nothing further was signed. Ask for a fresh summary.");for(let r of y){u(t,n.now());let d=await n.sendTransaction(r);m=!0,await n.waitForReceipt(d),yield{kind:"approval",hash:d,tx:r,status:"mined"}}continue}if(h.status==="needs_signature"){if(c)throw new o("FOBO requested a repeated permit. Nothing further was signed.");p=_(t,h.typedData,n.now()),u(t,n.now());let r=await n.signTypedData(p);c={message:i(p).message,signature:r},yield{kind:"permit",status:"signed"};continue}if(p){let r=i(i(p).message),d=i(r.details);for(let S of y){let g=x(S.data,["0x0Af57F62982D03066ef917AcAd87F771c06528Ec","0x0000000000000000000000000000000000000000"]).permit;if(!g||!w(g.token,d.token)||g.amount!==BigInt(String(d.amount))||g.nonce!==Number(d.nonce)||g.expiration!==Number(d.expiration)||!w(g.spender,r.spender)||g.sigDeadline!==BigInt(String(r.sigDeadline)))throw new o("FOBO changed the exact signed permit in the swap. Nothing further was signed.")}}for(let r of y){u(t,n.now());let d=await n.sendTransaction(r);await n.waitForReceipt(d),yield{kind:"transaction",hash:d,tx:r,status:"mined"}}return}throw new o("FOBO preparation did not finish. Nothing further was signed. Ask for a fresh summary.")}catch(a){let f=m?" An exact approval was already sent; use oak_cleanup_allowances to review any allowance left.":"";throw new o(`${k(a).replaceAll("Nothing was signed.","Nothing further was signed.")} FOBO execution stopped; nothing further was signed.${f}`)}}export{_ as a,q as b};
@@ -1 +1 @@
1
- import{b as Z}from"./M7CQPTRK.js";import{a as I,b as J,d as V}from"./RUTSEGGD.js";import{a as Q}from"./CEQNXF6A.js";import{a as E}from"./QYKXWBZC.js";import{K as y}from"./AXHFNE6L.js";import{c as $}from"./W7QNSNOH.js";import{a as H}from"./43LI5NKJ.js";import{a as N}from"./66F5ZH34.js";import{d as M,g as O,i as K}from"./NWNYJ26T.js";import{b}from"./TI727O2H.js";import{a as e}from"./XSD5NL7J.js";import{encodeFunctionData as Y,erc20Abi as X,getAddress as W,parseAbi as ee,zeroAddress as te}from"viem";var v={address:W("0xCeF73866b088766DeD46Ba71d9Bd7591B5e931d2"),symbol:"tNET",decimals:9,chainId:b},_={pair_oracle:["checkpoint"],futures:["open","close","marginCall","accrueCarry","sweepCarrySkim"],underwriting:["subscribe","redeem"],prize:["enter","enterWithNet","exit","exitToUsdg","lockTranche","earlyUnlock","pokeRebase"]},fe=x=>({tools:[{name:"netnet_desk_action",inputSchema:{type:"object",additionalProperties:!1,required:["program","operation"],properties:{program:{type:"string",enum:Object.keys(_),description:"Desk program: pair_oracle (price checkpoint), futures, underwriting or prize (WinNET)."},operation:{type:"string",enum:[...new Set(Object.values(_).flat())],description:"Action to run; it must be one the chosen program supports (see the program list in this tool)."},amount:N('Amount in base units of the token the operation spends or moves: tNET 9 decimals for futures and underwriting, USDG 6 or NET 9 for prize. Example: "1000000000" = 1 NET.'),minAmountOut:N('Least output you must receive, in base units of the output token (USDG 6 decimals, NET 9, underwriting shares). Example: "1000000" = 1 USDG.'),maxPayment:N('Most tNET you will pay for futures open (margin plus fee), in tNET base units (9 decimals). Example: "1000000000" = 1 tNET.'),sizeUsdWad:N('Futures position notional in USD as an 18-decimal wad in base units (1e18 = 1 USD). Example: "100000000000000000000" = 100 USD.'),isLong:{type:"boolean",description:"Futures open only: true for a long position, false for a short."},account:{type:"string",description:"Futures marginCall only: address of the trader to margin-call; they must be liquidatable."},referrer:{type:"string",description:"Prize enter only: optional referrer address recorded at the first deposit; cannot be your own wallet."},trancheIndex:N('Zero-based index of your WinNET tranche to lock or unlock early, as a decimal string. Example: "0".'),lockDraws:{enum:["7","30"],description:"Prize lockTranche only: commit the tranche for 7 or 30 draws."},maxPenaltyAssets:N('Prize earlyUnlock only: highest forfeited principal you accept, in NET base units (9 decimals). Example: "1000000000" = 1 NET.')}},execute:async(t,m)=>{try{if(H(m),typeof t.program!="string"||!Object.hasOwn(_,t.program)||typeof t.operation!="string"||!_[t.program].includes(t.operation))throw new e("Choose a supported finite NetNet desk operation.");let p=t.program,r=t.operation,P=E[p],z=Q[p],T=x.clientFor(b);if(await T.getChainId()!==b)throw new e("NetNet desk actions require chain 4663.");let D=await T.getBlock(),q=new Set(["program","operation"]),u=(n,s=[])=>T.readContract({address:P.address,abi:z,functionName:n,args:s,blockNumber:D.number}),h=(...n)=>n.forEach(s=>q.add(s)),A=()=>(h("amount"),y(t.amount)),S=()=>(h("minAmountOut"),y(t.minAmountOut)),d=n=>K(n,"Provide an explicit checksummed account.",M),l=[],a,c=0n,w="",g;if(p==="pair_oracle"){if(d(await u("pairContract"))!==Z)throw new e("The oracle does not use the pinned canonical pair.");w="Permissionless oracle checkpoint; it sends no reward to this wallet and may not yet produce a valid TWAP."}else if(p==="futures"||p==="underwriting"){if(d(await u("token"))!==v.address||await T.readContract({address:v.address,abi:X,functionName:"decimals",blockNumber:D.number})!==9)throw new e("This desk does not use the pinned valueless 9-decimal tNET test collateral.");let n=E.futures.address,s=E.underwriting.address;if(p==="futures"?d(await u("vault"))!==s:d(await u("clearinghouse"))!==n)throw new e("Futures and underwriting counterparties do not match the published pins.");if(w="Experimental tNET test program; tNET has no monetary value. Futures margin and underwriting capital can be lost. Utilization/ADL can prevent redemption. Prices and fees are read from the contract oracle; these calls encode no price floor.",r==="open"){if(h("isLong","sizeUsdWad","maxPayment"),typeof t.isLong!="boolean")throw new e("Provide isLong as a boolean.");let o=A(),f=y(t.sizeUsdWad);if(o>=1n<<128n||f>=1n<<128n)throw new e("Position margin and notional must fit uint128.");let k=d(await u("oracle"));if(k!==W("0xc8a11E8793F8714a159061369173dc86A0A5E23F"))throw new e("The futures oracle is not the published deployment.");let C=await T.readContract({address:k,abi:ee(["function marginPriceWad() view returns (uint256)"]),functionName:"marginPriceWad",blockNumber:D.number});if(C<=0n)throw new e("Futures margin price is unavailable.");let i=f*5n/10000n*1000000000n/C;if(c=o+i,a=v,c>y(t.maxPayment))throw new e("Margin plus taker fee exceeds maxPayment.");l=[t.isLong,f,o],w+=` Entry fee ${i} tNET base units; exact approval caps price drift and may require a fresh preview.`}else if(r==="marginCall"){h("account");let o=d(t.account);if(await u("liquidatable",[o])!==!0)throw new e("The selected futures trader is not liquidatable.");l=[o]}else if(r==="subscribe"){c=A(),a=v,l=[c];let[o,f]=await Promise.all([u("totalShares"),u("equityTokens")]);if(typeof o!="bigint"||typeof f!="bigint"||o>0n&&f===0n)throw new e("Underwriting share price is invalid.");let k=o===0n?c:c*o/f;if(k===0n||k<S())throw new e("Underwriting subscription rounds to zero or misses the local share minimum.");w+=` Current quote ${k} underwriting share units; the share minimum is a local check, not encoded calldata.`}else if(r==="redeem"){let o=A();if(o>await u("sharesOf",[m]))throw new e("The wallet has insufficient underwriting shares.");l=[o],g={token:v,amount:S()}}}else{let[n,s,o,f,k,C]=await Promise.all(["net","usdg","staking","sNet","controller","book"].map(i=>u(i)));if(d(n)!==I.address||d(s)!==$.address||d(o)!==V||d(f)!==J.address||d(k)!==E.draw.address||d(C)!==E.bonus.address)throw new e("WinNET token, staking, book or controller does not match its published pins.");if(w="WinNET principal is a fixed NET claim, exposed to NET price changes. Entry commits through three staking epochs; locks commit for 7 or 30 draws. Early unlock forfeits 1% of principal and cancels streak credits. Pair buys and sells each incur the NET trading tax; no prize or return is guaranteed.",r==="enter"||r==="enterWithNet"){h("referrer");let i=t.referrer===void 0?te:d(t.referrer);if(i===W(m))throw new e("WinNET does not permit self-referral.");c=A(),a=r==="enter"?$:I,l=r==="enter"?[c,S(),i]:[c,i],w+=` Referrer ${i} is recorded at the first deposit and cannot later be changed.`}else if(r==="exit"||r==="exitToUsdg"){let i=A();if(i>await u("principalOf",[m]))throw new e("WinNET exit exceeds this wallet\u2019s fixed principal.");l=r==="exit"?[i,m]:[i,S(),m],g={token:r==="exit"?I:$,amount:r==="exit"?i:y(t.minAmountOut)}}else if(r==="lockTranche"||r==="earlyUnlock"){h("trancheIndex");let i=y(t.trancheIndex,!0),U=await u("trancheAt",[m,i]);if(!Array.isArray(U)||typeof U[0]!="bigint"||U[0]===0n)throw new e("Choose a nonempty WinNET tranche.");if(r==="lockTranche"){if(h("lockDraws"),t.lockDraws!=="7"&&t.lockDraws!=="30")throw new e("Choose a 7- or 30-draw lock.");l=[i,BigInt(t.lockDraws)]}else{h("maxPenaltyAssets");let j=(U[0]+99n)/100n;if(j>y(t.maxPenaltyAssets,!0))throw new e("Early unlock exceeds maxPenaltyAssets in NET base units.");l=[i],w+=` Current irreversible forfeiture ${j} NET base units.`}}}if(Object.keys(t).some(n=>!q.has(n)))throw new e("Unexpected fields for this desk operation.");if(a&&await T.readContract({address:a.address,abi:X,functionName:"balanceOf",args:[m],blockNumber:D.number})<c)throw new e(`Top up ${a.symbol}; this action needs ${c} base units.`);let F=`NetNet ${p}.${r}, contract ${P.address}, chain ${b}, ordered values ${JSON.stringify(l,(n,s)=>typeof s=="bigint"?String(s):s)}. ${a?`Approve exactly ${c} ${a.symbol} base units (token ${a.address}, decimals ${a.decimals}). `:""}${w}`,L=[...a?[x.approval(a.address,P.address,c.toString(),b)]:[],x.unsignedTx({to:P.address,data:Y({abi:z,functionName:r,args:l}),value:"0",chainId:b,description:F})],R=await x.preview(L,m),B=0n,G=0n;for(let n of R.changes){if(n.token.chainId!==b||!/^-?\d+$/.test(n.amount))throw new e("Invalid desk preview metadata.");let s=BigInt(n.amount);if(s<0n){if(!a||!O(n.token.address,a.address)||n.token.decimals!==a.decimals)throw new e("Desk preview spends an unexpected wallet asset.");B-=s}if(g&&O(n.token.address,g.token.address)){if(n.token.decimals!==g.token.decimals)throw new e("Desk receipt decimals mismatch.");G+=s}}if(B>c||g&&G<g.amount)throw new e("Desk preview exceeds its input budget or misses the requested receipt minimum.");return{txs:L,preview:R,summary:F}}catch(p){throw new e(x.plainError(p))}}}]});export{v as a,fe as b};
1
+ import{b as Z}from"./CXH46MHJ.js";import{a as I,b as J,d as V}from"./RUTSEGGD.js";import{a as Q}from"./CEQNXF6A.js";import{a as E}from"./QYKXWBZC.js";import{L as y}from"./XKLXVTSE.js";import{c as $}from"./W7QNSNOH.js";import{a as H}from"./43LI5NKJ.js";import{a as N}from"./66F5ZH34.js";import{d as M,g as O,i as K}from"./NWNYJ26T.js";import{b}from"./TI727O2H.js";import{a as e}from"./XSD5NL7J.js";import{encodeFunctionData as Y,erc20Abi as X,getAddress as W,parseAbi as ee,zeroAddress as te}from"viem";var v={address:W("0xCeF73866b088766DeD46Ba71d9Bd7591B5e931d2"),symbol:"tNET",decimals:9,chainId:b},_={pair_oracle:["checkpoint"],futures:["open","close","marginCall","accrueCarry","sweepCarrySkim"],underwriting:["subscribe","redeem"],prize:["enter","enterWithNet","exit","exitToUsdg","lockTranche","earlyUnlock","pokeRebase"]},fe=x=>({tools:[{name:"netnet_desk_action",inputSchema:{type:"object",additionalProperties:!1,required:["program","operation"],properties:{program:{type:"string",enum:Object.keys(_),description:"Desk program: pair_oracle (price checkpoint), futures, underwriting or prize (WinNET)."},operation:{type:"string",enum:[...new Set(Object.values(_).flat())],description:"Action to run; it must be one the chosen program supports (see the program list in this tool)."},amount:N('Amount in base units of the token the operation spends or moves: tNET 9 decimals for futures and underwriting, USDG 6 or NET 9 for prize. Example: "1000000000" = 1 NET.'),minAmountOut:N('Least output you must receive, in base units of the output token (USDG 6 decimals, NET 9, underwriting shares). Example: "1000000" = 1 USDG.'),maxPayment:N('Most tNET you will pay for futures open (margin plus fee), in tNET base units (9 decimals). Example: "1000000000" = 1 tNET.'),sizeUsdWad:N('Futures position notional in USD as an 18-decimal wad in base units (1e18 = 1 USD). Example: "100000000000000000000" = 100 USD.'),isLong:{type:"boolean",description:"Futures open only: true for a long position, false for a short."},account:{type:"string",description:"Futures marginCall only: address of the trader to margin-call; they must be liquidatable."},referrer:{type:"string",description:"Prize enter only: optional referrer address recorded at the first deposit; cannot be your own wallet."},trancheIndex:N('Zero-based index of your WinNET tranche to lock or unlock early, as a decimal string. Example: "0".'),lockDraws:{enum:["7","30"],description:"Prize lockTranche only: commit the tranche for 7 or 30 draws."},maxPenaltyAssets:N('Prize earlyUnlock only: highest forfeited principal you accept, in NET base units (9 decimals). Example: "1000000000" = 1 NET.')}},execute:async(t,m)=>{try{if(H(m),typeof t.program!="string"||!Object.hasOwn(_,t.program)||typeof t.operation!="string"||!_[t.program].includes(t.operation))throw new e("Choose a supported finite NetNet desk operation.");let p=t.program,r=t.operation,P=E[p],z=Q[p],T=x.clientFor(b);if(await T.getChainId()!==b)throw new e("NetNet desk actions require chain 4663.");let D=await T.getBlock(),q=new Set(["program","operation"]),u=(n,s=[])=>T.readContract({address:P.address,abi:z,functionName:n,args:s,blockNumber:D.number}),h=(...n)=>n.forEach(s=>q.add(s)),A=()=>(h("amount"),y(t.amount)),S=()=>(h("minAmountOut"),y(t.minAmountOut)),d=n=>K(n,"Provide an explicit checksummed account.",M),l=[],a,c=0n,w="",g;if(p==="pair_oracle"){if(d(await u("pairContract"))!==Z)throw new e("The oracle does not use the pinned canonical pair.");w="Permissionless oracle checkpoint; it sends no reward to this wallet and may not yet produce a valid TWAP."}else if(p==="futures"||p==="underwriting"){if(d(await u("token"))!==v.address||await T.readContract({address:v.address,abi:X,functionName:"decimals",blockNumber:D.number})!==9)throw new e("This desk does not use the pinned valueless 9-decimal tNET test collateral.");let n=E.futures.address,s=E.underwriting.address;if(p==="futures"?d(await u("vault"))!==s:d(await u("clearinghouse"))!==n)throw new e("Futures and underwriting counterparties do not match the published pins.");if(w="Experimental tNET test program; tNET has no monetary value. Futures margin and underwriting capital can be lost. Utilization/ADL can prevent redemption. Prices and fees are read from the contract oracle; these calls encode no price floor.",r==="open"){if(h("isLong","sizeUsdWad","maxPayment"),typeof t.isLong!="boolean")throw new e("Provide isLong as a boolean.");let o=A(),f=y(t.sizeUsdWad);if(o>=1n<<128n||f>=1n<<128n)throw new e("Position margin and notional must fit uint128.");let k=d(await u("oracle"));if(k!==W("0xc8a11E8793F8714a159061369173dc86A0A5E23F"))throw new e("The futures oracle is not the published deployment.");let C=await T.readContract({address:k,abi:ee(["function marginPriceWad() view returns (uint256)"]),functionName:"marginPriceWad",blockNumber:D.number});if(C<=0n)throw new e("Futures margin price is unavailable.");let i=f*5n/10000n*1000000000n/C;if(c=o+i,a=v,c>y(t.maxPayment))throw new e("Margin plus taker fee exceeds maxPayment.");l=[t.isLong,f,o],w+=` Entry fee ${i} tNET base units; exact approval caps price drift and may require a fresh preview.`}else if(r==="marginCall"){h("account");let o=d(t.account);if(await u("liquidatable",[o])!==!0)throw new e("The selected futures trader is not liquidatable.");l=[o]}else if(r==="subscribe"){c=A(),a=v,l=[c];let[o,f]=await Promise.all([u("totalShares"),u("equityTokens")]);if(typeof o!="bigint"||typeof f!="bigint"||o>0n&&f===0n)throw new e("Underwriting share price is invalid.");let k=o===0n?c:c*o/f;if(k===0n||k<S())throw new e("Underwriting subscription rounds to zero or misses the local share minimum.");w+=` Current quote ${k} underwriting share units; the share minimum is a local check, not encoded calldata.`}else if(r==="redeem"){let o=A();if(o>await u("sharesOf",[m]))throw new e("The wallet has insufficient underwriting shares.");l=[o],g={token:v,amount:S()}}}else{let[n,s,o,f,k,C]=await Promise.all(["net","usdg","staking","sNet","controller","book"].map(i=>u(i)));if(d(n)!==I.address||d(s)!==$.address||d(o)!==V||d(f)!==J.address||d(k)!==E.draw.address||d(C)!==E.bonus.address)throw new e("WinNET token, staking, book or controller does not match its published pins.");if(w="WinNET principal is a fixed NET claim, exposed to NET price changes. Entry commits through three staking epochs; locks commit for 7 or 30 draws. Early unlock forfeits 1% of principal and cancels streak credits. Pair buys and sells each incur the NET trading tax; no prize or return is guaranteed.",r==="enter"||r==="enterWithNet"){h("referrer");let i=t.referrer===void 0?te:d(t.referrer);if(i===W(m))throw new e("WinNET does not permit self-referral.");c=A(),a=r==="enter"?$:I,l=r==="enter"?[c,S(),i]:[c,i],w+=` Referrer ${i} is recorded at the first deposit and cannot later be changed.`}else if(r==="exit"||r==="exitToUsdg"){let i=A();if(i>await u("principalOf",[m]))throw new e("WinNET exit exceeds this wallet\u2019s fixed principal.");l=r==="exit"?[i,m]:[i,S(),m],g={token:r==="exit"?I:$,amount:r==="exit"?i:y(t.minAmountOut)}}else if(r==="lockTranche"||r==="earlyUnlock"){h("trancheIndex");let i=y(t.trancheIndex,!0),U=await u("trancheAt",[m,i]);if(!Array.isArray(U)||typeof U[0]!="bigint"||U[0]===0n)throw new e("Choose a nonempty WinNET tranche.");if(r==="lockTranche"){if(h("lockDraws"),t.lockDraws!=="7"&&t.lockDraws!=="30")throw new e("Choose a 7- or 30-draw lock.");l=[i,BigInt(t.lockDraws)]}else{h("maxPenaltyAssets");let j=(U[0]+99n)/100n;if(j>y(t.maxPenaltyAssets,!0))throw new e("Early unlock exceeds maxPenaltyAssets in NET base units.");l=[i],w+=` Current irreversible forfeiture ${j} NET base units.`}}}if(Object.keys(t).some(n=>!q.has(n)))throw new e("Unexpected fields for this desk operation.");if(a&&await T.readContract({address:a.address,abi:X,functionName:"balanceOf",args:[m],blockNumber:D.number})<c)throw new e(`Top up ${a.symbol}; this action needs ${c} base units.`);let F=`NetNet ${p}.${r}, contract ${P.address}, chain ${b}, ordered values ${JSON.stringify(l,(n,s)=>typeof s=="bigint"?String(s):s)}. ${a?`Approve exactly ${c} ${a.symbol} base units (token ${a.address}, decimals ${a.decimals}). `:""}${w}`,L=[...a?[x.approval(a.address,P.address,c.toString(),b)]:[],x.unsignedTx({to:P.address,data:Y({abi:z,functionName:r,args:l}),value:"0",chainId:b,description:F})],R=await x.preview(L,m),B=0n,G=0n;for(let n of R.changes){if(n.token.chainId!==b||!/^-?\d+$/.test(n.amount))throw new e("Invalid desk preview metadata.");let s=BigInt(n.amount);if(s<0n){if(!a||!O(n.token.address,a.address)||n.token.decimals!==a.decimals)throw new e("Desk preview spends an unexpected wallet asset.");B-=s}if(g&&O(n.token.address,g.token.address)){if(n.token.decimals!==g.token.decimals)throw new e("Desk receipt decimals mismatch.");G+=s}}if(B>c||g&&G<g.amount)throw new e("Desk preview exceeds its input budget or misses the requested receipt minimum.");return{txs:L,preview:R,summary:F}}catch(p){throw new e(x.plainError(p))}}}]});export{v as a,fe as b};
@@ -1,3 +1,3 @@
1
- import{a as o,b as C,c as K,d as O,e as E,f as D}from"./4ZD5D2UP.js";import{h as H}from"./BSX4LFYI.js";import{c as U}from"./43LI5NKJ.js";import{e as N,g as R,h as l}from"./NWNYJ26T.js";import{a as P}from"./XSD5NL7J.js";import{decodeFunctionData as y,encodeFunctionData as k,erc20Abi as _,getAddress as q,isAddress as G,zeroAddress as h}from"viem";var X=15000000n,j=1200,L="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",w=n=>(1n<<BigInt(n))-1n;function S(n){throw new P(`FOBO ${n}. Nothing was signed. Ask for a fresh summary.`)}function i(n,e){n||S(e)}function I(n,e){return i(typeof n=="string"&&G(n,{strict:!1}),e),q(n)}function m(n,e,s){i(l(I(n,s),I(e,s)),s)}function T(n,e,s=256){i(typeof n=="string"&&n.length<=80&&/^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(n),`${e} must be an unsigned integer`);let r=BigInt(n);return i(r<=w(s),`${e} is too large`),r}function p(n,e,s=256){return i(typeof n=="bigint"&&n>=0n&&n<=w(s),`${e} is invalid`),n}function B(n){i(Number.isSafeInteger(n)&&n>=0&&n<=Number(w(48))-1800,"clock is invalid")}var $=120;function v(n,e){i(R(n,e),"calldata must be canonical")}function M(n,e){return l(n.currency0,e.currency0)&&l(n.currency1,e.currency1)&&l(n.hooks,e.hooks)&&n.fee===e.fee&&n.tickSpacing===e.tickSpacing}function z(n){i([o.permit2,o.factory,o.limitOrders].some(e=>l(n,e)),"approval spender is not pinned")}function J(n,e,s){let r=I(n,"approval token is invalid");return i(r!==h&&!l(r,L),"approval token cannot be native ETH"),z(I(e,"approval spender is invalid")),i(p(s,"approval amount")<w(256),"approval amount cannot be unlimited"),U(r,q(e),s.toString(),o.chainId)}function oe(n){let e=I(n.token,"permit token is invalid");i(e!==h&&!l(e,L),"permit token cannot be native ETH"),i(p(n.amount,"permit amount",160)>0n&&n.amount<w(160),"permit amount must be exact and positive"),i(Number.isSafeInteger(n.nonce)&&n.nonce>=0&&n.nonce<=Number(w(48)),"permit nonce is invalid"),B(n.now);let s=n.now+j;return{domain:{name:"Permit2",chainId:o.chainId,verifyingContract:o.permit2},types:{PermitDetails:[{name:"token",type:"address"},{name:"amount",type:"uint160"},{name:"expiration",type:"uint48"},{name:"nonce",type:"uint48"}],PermitSingle:[{name:"details",type:"PermitDetails"},{name:"spender",type:"address"},{name:"sigDeadline",type:"uint256"}]},primaryType:"PermitSingle",message:{details:{token:e,amount:n.amount.toString(),expiration:s,nonce:n.nonce},spender:o.router,sigDeadline:s.toString()}}}function re(n,e,s){try{return Q(n,e,s)}catch(r){if(r instanceof P&&r.message.startsWith("FOBO ")&&r.message.includes("Nothing was signed."))throw r;S("transaction could not be decoded and verified")}}function Q(n,e,s){i(N(n),"transaction is invalid"),i(n.chainId===o.chainId||n.chainId==="0x1237","chain must be 4663"),m(n.from,s,"wallet does not match the transaction sender");let r=I(n.to,"contract address is invalid");i(typeof n.data=="string"&&/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(n.data),"selector or calldata is invalid");let d=T(n.value,"value"),u=T(n.gas,"gas");i(u>=21000n&&u<=X,"gas is outside the signing ceiling");let F=n.data.slice(0,10).toLowerCase(),f=(t,a)=>{m(r,t,"contract does not match the approved action"),i(F===a,"selector is not pinned for this contract")},A;switch(e.kind){case"approval":{i(l(r,e.token),"approval token differs from the approved input"),i(F===o.selectors.approve,"selector is not an ERC-20 approval"),i(d===0n,"approval value must be zero");let t=y({abi:_,data:n.data});i(t.functionName==="approve","selector is not an ERC-20 approval"),v(n.data,k({abi:_,functionName:"approve",args:t.args}));let[a]=t.args;return z(a),m(a,e.spender,"approval spender differs from the approved action"),{...J(r,a,e.amount),gasLimit:u.toString()}}case"trade":{f(o.router,o.selectors.execute),B(e.now);let t=H(n.data,[o.hook,h]);i(e.pools.length>0&&t.legs.length===e.pools.length&&t.legs.some(c=>l(c.poolKey.hooks,o.hook))&&t.legs.every((c,b)=>M(c.poolKey,e.pools[b])),"swap pools differ from the approved route");let a={currency0:h,currency1:o.usdg,fee:500,tickSpacing:10,hooks:h};if(i(t.legs.every(c=>l(c.poolKey.hooks,o.hook)||M(c.poolKey,a)),"swap contains an unsupported hookless pool"),m(t.currencyIn,e.currencyIn,"swap input currency differs"),m(t.currencyOut,e.currencyOut,"swap output currency differs"),i(t.amountIn===p(e.amountIn,"swap amount")&&t.amountIn>0n,"swap input amount differs"),i(t.amountOutMinimum>=p(e.minOut,"minimum output")&&e.minOut>0n,"swap minimum output is below the approved minimum"),i(t.deadline>BigInt(e.now)&&t.deadline<=BigInt(e.now+1200+$),"swap deadline must be within 20 minutes"),i(d===(l(e.currencyIn,h)?e.amountIn:0n),"swap ETH value differs from the approved input"),t.permit){let c=e.permit;i(c,"swap encodes an unexpected permit"),m(c.details.token,e.currencyIn,"permit token differs from the trade input"),i(T(c.details.amount,"permit amount",160)===e.amountIn&&e.amountIn<w(160),"permit amount differs from the exact trade input"),m(c.spender,o.router,"permit spender must be the Universal Router");let b=T(c.sigDeadline,"permit deadline");i(Number.isSafeInteger(c.details.expiration)&&c.details.expiration>e.now&&BigInt(c.details.expiration)<=b&&b>=BigInt(e.now+300)&&b<=BigInt(e.now+1800),"permit expiration or signature deadline is outside the signing window");let g=t.permit;i(l(g.token,c.details.token)&&g.amount===e.amountIn&&g.expiration===c.details.expiration&&g.nonce===c.details.nonce&&l(g.spender,c.spender)&&g.sigDeadline===b,"swap permit differs from the locally signed exact permit")}else i(!e.permit,"swap omitted the locally signed permit");A=`FOBO swap: exact input ${t.amountIn}; minimum output ${t.amountOutMinimum}.`;break}case"launch":{f(o.factory,o.selectors.launch),B(e.now);let t=y({abi:C,data:n.data});v(n.data,k({abi:C,...t}));let[a]=t.args;i(a.name===e.name&&a.ticker===e.ticker,"launch name or ticker differs from the approved launch"),m(a.quote,e.pair,"launch pair differs from the approved launch"),i(a.devBuyTokens===p(e.devBuyTokens,"initial buy")&&a.devBuyTokens<=50000000n*10n**18n&&a.devBuyMaxCost===p(e.devBuyMaxCost,"initial buy cost"),"launch initial buy or cost differs"),i(a.vestMonths===e.vestMonths&&[0,1,3,6,12].includes(a.vestMonths)&&(a.vestMonths===0||a.devBuyTokens>0n),"launch lock months differ"),i(a.deadline>BigInt(e.now)&&a.deadline<=BigInt(e.now+900+$),"launch deadline must be within 15 minutes"),i(d===p(e.launchFeeWei,"launch fee")+(l(a.quote,h)?a.devBuyMaxCost:0n),"launch ETH value differs from its fee plus initial buy"),A="Launch the approved FOBO token with its approved initial buy and lock.";break}case"limitOrder":{f(o.limitOrders,o.selectors.place);let t=y({abi:O,data:n.data});i(t.functionName==="place","selector is not place"),v(n.data,k({abi:O,...t}));let[a,c,b,g,W,V,Z]=t.args;i((a===0||a===1)&&a===e.side,"limit order side differs"),m(c,e.token,"limit order token differs"),m(b,e.payToken,"limit order pay token differs"),i(g===p(e.amount,"order amount")&&g>0n&&W===p(e.limitPriceUsdE18,"limit price")&&V===p(e.expiry,"order expiry")&&Z===p(e.maxFeePerFill,"keeper fee"),"limit order amount, price, expiry or keeper fee differs"),i(d===(a===0&&l(b,h)?g:0n),"limit order ETH value differs from its native escrow"),A="Place the approved FOBO limit order; escrow refunds and fills belong to this wallet.";break}case"cancel":{f(o.limitOrders,o.selectors.cancel),i(d===0n,"cancel value must be zero");let t=y({abi:O,data:n.data});i(t.functionName==="cancel","selector is not cancel"),v(n.data,k({abi:O,...t})),i(t.args[0]===p(e.orderId,"order id"),"cancel order differs"),m(t.args[1],s,"cancel recipient must be this wallet"),A="Cancel the approved FOBO order and refund this wallet.";break}case"claim":{if(i(d===0n,"claim value must be zero"),e.claimKind==="creator"){f(o.hook,o.selectors.claimCreator);let t=y({abi:K,data:n.data});v(n.data,k({abi:K,...t})),i(M(t.args[0],e.poolKey)&&l(t.args[0].hooks,o.hook),"creator claim pool differs"),m(t.args[1],s,"creator claim recipient must be this wallet")}else if(e.claimKind==="referral"){f(o.revenue,o.selectors.claimReferral);let t=y({abi:E,data:n.data});v(n.data,k({abi:E,...t})),m(t.args[0],s,"referral claim account must be this wallet"),m(t.args[1],e.currency,"referral claim currency differs"),m(t.args[2],e.recipient??s,"referral claim recipient differs from the approved recipient")}else{i(e.claimKind==="vesting","claim kind is unsupported"),f(o.vesting,o.selectors.claimVesting);let t=y({abi:D,data:n.data});v(n.data,k({abi:D,...t})),i(t.args[0]===p(e.lockId,"vesting lock"),"vesting lock differs"),m(e.beneficiary,s,"vesting beneficiary must be this wallet")}A="Claim the approved FOBO earnings to their approved recipient.";break}default:S("transaction expectation is unsupported")}return{to:r,data:n.data,value:d.toString(),chainId:o.chainId,gasLimit:u.toString(),description:A}}function ae(n,e,s){let r="sign-in message is not a fresh fobo.fun sign-in for this wallet";try{B(s),i(typeof n=="string"&&n.length<=2048&&!/[\r\p{Cc}\p{Cf}]/u.test(n.replaceAll(`
1
+ import{a as o,b as C,c as K,d as F,e as E,f as D}from"./4ZD5D2UP.js";import{h as H}from"./BSX4LFYI.js";import{c as U}from"./43LI5NKJ.js";import{e as N,g as R,h as l}from"./NWNYJ26T.js";import{a as P}from"./XSD5NL7J.js";import{decodeFunctionData as y,encodeFunctionData as k,erc20Abi as _,getAddress as q,isAddress as G,zeroAddress as h}from"viem";var X=15000000n,j=1200,L="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",w=n=>(1n<<BigInt(n))-1n;function S(n){throw new P(`FOBO ${n}. Nothing was signed. Ask for a fresh summary.`)}function i(n,e){n||S(e)}function I(n,e){return i(typeof n=="string"&&G(n,{strict:!1}),e),q(n)}function m(n,e,s){i(l(I(n,s),I(e,s)),s)}function T(n,e,s=256){i(typeof n=="string"&&n.length<=80&&/^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(n),`${e} must be an unsigned integer`);let r=BigInt(n);return i(r<=w(s),`${e} is too large`),r}function p(n,e,s=256){return i(typeof n=="bigint"&&n>=0n&&n<=w(s),`${e} is invalid`),n}function B(n){i(Number.isSafeInteger(n)&&n>=0&&n<=Number(w(48))-1800,"clock is invalid")}var $=120;function v(n,e){i(R(n,e),"calldata must be canonical")}function M(n,e){return l(n.currency0,e.currency0)&&l(n.currency1,e.currency1)&&l(n.hooks,e.hooks)&&n.fee===e.fee&&n.tickSpacing===e.tickSpacing}function z(n){i([o.permit2,o.factory,o.limitOrders].some(e=>l(n,e)),"approval spender is not pinned")}function J(n,e,s){let r=I(n,"approval token is invalid");return i(r!==h&&!l(r,L),"approval token cannot be native ETH"),z(I(e,"approval spender is invalid")),i(p(s,"approval amount")<w(256),"approval amount cannot be unlimited"),U(r,q(e),s.toString(),o.chainId)}function oe(n){let e=I(n.token,"permit token is invalid");i(e!==h&&!l(e,L),"permit token cannot be native ETH"),i(p(n.amount,"permit amount",160)>0n&&n.amount<w(160),"permit amount must be exact and positive"),i(Number.isSafeInteger(n.nonce)&&n.nonce>=0&&n.nonce<=Number(w(48)),"permit nonce is invalid"),B(n.now);let s=n.now+j;return{domain:{name:"Permit2",chainId:o.chainId,verifyingContract:o.permit2},types:{PermitDetails:[{name:"token",type:"address"},{name:"amount",type:"uint160"},{name:"expiration",type:"uint48"},{name:"nonce",type:"uint48"}],PermitSingle:[{name:"details",type:"PermitDetails"},{name:"spender",type:"address"},{name:"sigDeadline",type:"uint256"}]},primaryType:"PermitSingle",message:{details:{token:e,amount:n.amount.toString(),expiration:s,nonce:n.nonce},spender:o.router,sigDeadline:s.toString()}}}function re(n,e,s){try{return Q(n,e,s)}catch(r){if(r instanceof P&&r.message.startsWith("FOBO ")&&r.message.includes("Nothing was signed."))throw r;S("transaction could not be decoded and verified")}}function Q(n,e,s){i(N(n),"transaction is invalid"),i(n.chainId===o.chainId||n.chainId==="0x1237","chain must be 4663"),m(n.from,s,"wallet does not match the transaction sender");let r=I(n.to,"contract address is invalid");i(typeof n.data=="string"&&/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(n.data),"selector or calldata is invalid");let d=T(n.value,"value"),u=T(n.gas,"gas");i(u>=21000n&&u<=X,"gas is outside the signing ceiling");let O=n.data.slice(0,10).toLowerCase(),f=(t,a)=>{m(r,t,"contract does not match the approved action"),i(O===a,"selector is not pinned for this contract")},A;switch(e.kind){case"approval":{i(l(r,e.token),"approval token differs from the approved input"),i(O===o.selectors.approve,"selector is not an ERC-20 approval"),i(d===0n,"approval value must be zero");let t=y({abi:_,data:n.data});i(t.functionName==="approve","selector is not an ERC-20 approval"),v(n.data,k({abi:_,functionName:"approve",args:t.args}));let[a]=t.args;return z(a),m(a,e.spender,"approval spender differs from the approved action"),{...J(r,a,e.amount),gasLimit:u.toString()}}case"trade":{f(o.router,o.selectors.execute),B(e.now);let t=H(n.data,[o.hook,h]);i(e.pools.length>0&&t.legs.length===e.pools.length&&t.legs.some(c=>l(c.poolKey.hooks,o.hook))&&t.legs.every((c,b)=>M(c.poolKey,e.pools[b])),"swap pools differ from the approved route");let a={currency0:h,currency1:o.usdg,fee:500,tickSpacing:10,hooks:h};if(i(t.legs.every(c=>l(c.poolKey.hooks,o.hook)||M(c.poolKey,a)),"swap contains an unsupported hookless pool"),m(t.currencyIn,e.currencyIn,"swap input currency differs"),m(t.currencyOut,e.currencyOut,"swap output currency differs"),i(t.amountIn===p(e.amountIn,"swap amount")&&t.amountIn>0n,"swap input amount differs"),i(t.amountOutMinimum>=p(e.minOut,"minimum output")&&e.minOut>0n,"swap minimum output is below the approved minimum"),i(t.deadline>BigInt(e.now)&&t.deadline<=BigInt(e.now+1200+$),"swap deadline must be within 20 minutes"),i(d===(l(e.currencyIn,h)?e.amountIn:0n),"swap ETH value differs from the approved input"),t.permit){let c=e.permit;i(c,"swap encodes an unexpected permit"),m(c.details.token,e.currencyIn,"permit token differs from the trade input"),i(T(c.details.amount,"permit amount",160)===e.amountIn&&e.amountIn<w(160),"permit amount differs from the exact trade input"),m(c.spender,o.router,"permit spender must be the Universal Router");let b=T(c.sigDeadline,"permit deadline");i(Number.isSafeInteger(c.details.expiration)&&c.details.expiration>e.now&&BigInt(c.details.expiration)<=b&&b>=BigInt(e.now+300)&&b<=BigInt(e.now+1800),"permit expiration or signature deadline is outside the signing window");let g=t.permit;i(l(g.token,c.details.token)&&g.amount===e.amountIn&&g.expiration===c.details.expiration&&g.nonce===c.details.nonce&&l(g.spender,c.spender)&&g.sigDeadline===b,"swap permit differs from the locally signed exact permit")}else i(!e.permit,"swap omitted the locally signed permit");A=`FOBO swap: exact input ${t.amountIn}; minimum output ${t.amountOutMinimum}.`;break}case"launch":{f(o.factory,o.selectors.launch),B(e.now);let t=y({abi:C,data:n.data});v(n.data,k({abi:C,...t}));let[a]=t.args;i(a.name===e.name&&a.ticker===e.ticker,"launch name or ticker differs from the approved launch"),m(a.quote,e.pair,"launch pair differs from the approved launch"),i(a.devBuyTokens===p(e.devBuyTokens,"initial buy")&&a.devBuyTokens<=50000000n*10n**18n&&a.devBuyMaxCost===p(e.devBuyMaxCost,"initial buy cost"),"launch initial buy or cost differs"),i(a.vestMonths===e.vestMonths&&[0,1,3,6,12].includes(a.vestMonths)&&(a.vestMonths===0||a.devBuyTokens>0n),"launch lock months differ"),i(a.deadline>BigInt(e.now)&&a.deadline<=BigInt(e.now+900+$),"launch deadline must be within 15 minutes"),i(d===p(e.launchFeeWei,"launch fee")+(l(a.quote,h)?a.devBuyMaxCost:0n),"launch ETH value differs from its fee plus initial buy"),A="Launch the approved FOBO token with its approved initial buy and lock.";break}case"limitOrder":{f(o.limitOrders,o.selectors.place);let t=y({abi:F,data:n.data});i(t.functionName==="place","selector is not place"),v(n.data,k({abi:F,...t}));let[a,c,b,g,W,V,Z]=t.args;i((a===0||a===1)&&a===e.side,"limit order side differs"),m(c,e.token,"limit order token differs"),m(b,e.payToken,"limit order pay token differs"),i(g===p(e.amount,"order amount")&&g>0n&&W===p(e.limitPriceUsdE18,"limit price")&&V===p(e.expiry,"order expiry")&&Z===p(e.maxFeePerFill,"keeper fee"),"limit order amount, price, expiry or keeper fee differs"),i(d===(a===0&&l(b,h)?g:0n),"limit order ETH value differs from its native escrow"),A="Place the approved FOBO limit order; escrow refunds and fills belong to this wallet.";break}case"cancel":{f(o.limitOrders,o.selectors.cancel),i(d===0n,"cancel value must be zero");let t=y({abi:F,data:n.data});i(t.functionName==="cancel","selector is not cancel"),v(n.data,k({abi:F,...t})),i(t.args[0]===p(e.orderId,"order id"),"cancel order differs"),m(t.args[1],s,"cancel recipient must be this wallet"),A="Cancel the approved FOBO order and refund this wallet.";break}case"claim":{if(i(d===0n,"claim value must be zero"),e.claimKind==="creator"){f(o.hook,o.selectors.claimCreator);let t=y({abi:K,data:n.data});v(n.data,k({abi:K,...t})),i(M(t.args[0],e.poolKey)&&l(t.args[0].hooks,o.hook),"creator claim pool differs"),m(t.args[1],s,"creator claim recipient must be this wallet")}else if(e.claimKind==="referral"){f(o.revenue,o.selectors.claimReferral);let t=y({abi:E,data:n.data});v(n.data,k({abi:E,...t})),m(t.args[0],s,"referral claim account must be this wallet"),m(t.args[1],e.currency,"referral claim currency differs"),m(t.args[2],e.recipient??s,"referral claim recipient differs from the approved recipient")}else{i(e.claimKind==="vesting","claim kind is unsupported"),f(o.vesting,o.selectors.claimVesting);let t=y({abi:D,data:n.data});v(n.data,k({abi:D,...t})),i(t.args[0]===p(e.lockId,"vesting lock"),"vesting lock differs"),m(e.beneficiary,s,"vesting beneficiary must be this wallet")}A="Claim the approved FOBO earnings to their approved recipient.";break}default:S("transaction expectation is unsupported")}return{to:r,data:n.data,value:d.toString(),chainId:o.chainId,gasLimit:u.toString(),description:A}}function ae(n,e,s){let r="sign-in message is not a fresh fobo.fun sign-in for this wallet";try{B(s),i(typeof n=="string"&&n.length<=2048&&!/[\r\p{Cc}\p{Cf}]/u.test(n.replaceAll(`
2
2
  `,"")),r);let d=n.split(`
3
- `);i(d[0]==="fobo.fun wants you to sign in with your Ethereum account:"&&d[2]==="",r),m(d[1],e,r);let u=3;d[u]!=="URI: https://fobo.fun"&&d[u]!=="URI: https://fobo.fun/"&&(i(["Sign in to fobo.fun","Sign in to fobo.fun.","Sign in to FOBO.","Sign in to fobo."].includes(d[u]??"")&&d[u+1]==="",r),u+=2),i(["URI: https://fobo.fun","URI: https://fobo.fun/"].includes(d[u]??"")&&d[u+1]==="Version: 1",r),u+=2,d[u]?.startsWith("Chain ID:")&&(i(d[u]==="Chain ID: 4663",r),u++),i(/^Nonce: [a-zA-Z0-9]{8,128}$/.test(d[u]??""),r);let F=d[u+1]?.match(/^Issued At: (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z)$/)?.[1];i(F&&d.length===u+2,r);let f=Date.parse(F)/1e3;i(Number.isFinite(f)&&f<=s&&f>=s-300,r)}catch{S(r)}}export{X as a,J as b,oe as c,re as d,ae as e};
3
+ `);i(["fobo.fun wants you to sign in with your Ethereum account:","fobo.fun wants you to sign in with your wallet:"].includes(d[0]??"")&&d[2]==="",r),m(d[1],e,r);let u=3;d[u]!=="URI: https://fobo.fun"&&d[u]!=="URI: https://fobo.fun/"&&(i(["Sign in to fobo.fun","Sign in to fobo.fun.","Sign in to FOBO.","Sign in to fobo.","Sign in to FOBO. This is free: no transaction, no gas."].includes(d[u]??"")&&d[u+1]==="",r),u+=2),i(["URI: https://fobo.fun","URI: https://fobo.fun/"].includes(d[u]??"")&&d[u+1]==="Version: 1",r),u+=2,d[u]?.startsWith("Chain ID:")&&(i(d[u]==="Chain ID: 4663",r),u++),i(/^Nonce: [a-zA-Z0-9]{8,128}$/.test(d[u]??""),r);let O=d[u+1]?.match(/^Issued At: (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z)$/)?.[1];i(O&&d.length===u+2,r);let f=Date.parse(O)/1e3;i(Number.isFinite(f)&&f<=s&&f>=s-300,r)}catch{S(r)}}export{X as a,J as b,oe as c,re as d,ae as e};
@@ -1 +1 @@
1
- import{e as g,f as T,g as k,i as E}from"./AXHFNE6L.js";import{c as _,d as S}from"./W7QNSNOH.js";import{g as h}from"./NWNYJ26T.js";import{b as f}from"./TI727O2H.js";import{a as i}from"./XSD5NL7J.js";import{decodeAbiParameters as P,encodeAbiParameters as B,getAddress as d}from"viem";var D=d("0xcEF685D4796FA80F71a97e803D2c0b6719F1b4E2"),H=[{name:"items",type:"tuple[]",components:[{...k[0],name:"offer"},{name:"ratifierData",type:"bytes"}]}],G=l=>({tools:[{name:"longbow_fixed_offers",inputSchema:{type:"object",additionalProperties:!1,properties:{limit:{type:"integer",minimum:1,maximum:50,description:"Maximum number of offers to return, 1 to 50 (default 20). Newest-expiring offers come first."},marketId:{type:"string",description:"Optional Midnight market id as 0x followed by 64 hex digits (bytes32); only offers in that market are returned."}}},execute:async o=>{try{let a=o.limit??20;if(Object.keys(o).some(s=>!["limit","marketId"].includes(s))||!Number.isInteger(a)||Number(a)<1||Number(a)>50||o.marketId!==void 0&&(typeof o.marketId!="string"||!/^0x[0-9a-f]{64}$/i.test(o.marketId)))throw new i("Use limit 1..50 and an optional exact bytes32 marketId.");let p=await l.http("https://longbow.credit/api/fixed/offers",{method:"GET",redirect:"error"});if(!p.ok)throw new i(`Longbow fixed order book returned HTTP ${p.status}; offers are unavailable.`);let x=await p.text();if(x.length>2e6)throw new i("Longbow fixed order book exceeds the supported response size.");let t=JSON.parse(x);if(!t||t.chainId!==f||typeof t.mempool!="string"||d(t.mempool)!==D||!Array.isArray(t.publications)||t.publications.length>1e3||!Number.isSafeInteger(t.head)||Number(t.head)<0)throw new i("Longbow fixed indexer does not match the pinned chain, mempool or publication schema.");let c=[],u=[],y=0;for(let[s,m]of t.publications.entries())try{if(!m||typeof m!="object")throw new i("Invalid publication.");let r=m,n=r.itemsAbi;if(!Number.isSafeInteger(r.blockNumber)||Number(r.blockNumber)<0||Number(r.blockNumber)>Number(t.head))throw new i("Invalid publication block.");if(typeof n!="string"||!/^0x[0-9a-f]+$/i.test(n)||n.length>1e6||n.length<130||BigInt(`0x${n.slice(2,66)}`)!==32n||BigInt(`0x${n.slice(66,130)}`)>512n)throw new i("Invalid or oversized publication encoding.");let[w]=P(H,n);if(w.length!==r.items)throw new i("Publication count mismatch.");for(let b of w){y++;let e=b.offer;if(e.market.chainId!==BigInt(f)||d(e.market.midnight)!==g||b.ratifierData.length>32770)throw new i("Publication market or proof is unqualified.");let I=E(e.market);if(o.marketId!==void 0&&!h(I,String(o.marketId)))continue;let N=[_,S].find(O=>h(O.address,e.market.loanToken));c.push({marketId:I,offer:B(k,[e]),ratifierData:b.ratifierData,maker:d(e.maker),buy:e.buy,maturity:e.market.maturity.toString(),start:e.start.toString(),expiry:e.expiry.toString(),tick:e.tick.toString(),loanToken:N??null,directBuilderSupported:!!N&&/^0x0{40}$/i.test(e.callback)&&e.callbackData==="0x"&&T.includes(d(e.ratifier)),sourceBlock:String(r.blockNumber)})}}catch(r){u.push({publication:s,reason:l.plainError(r)})}return c.sort((s,m)=>BigInt(s.expiry)>BigInt(m.expiry)?-1:BigInt(s.expiry)<BigInt(m.expiry)?1:0),{chainId:f,midnight:g,mempool:D,indexedHead:String(t.head),decodedCount:y,matchingCount:c.length,offers:c.slice(0,Number(a)),incomplete:u.length>0||t.skipped!==0,rejected:u,warning:"Historical off-chain publications, not executable quotes. Expiry, consumption, authorization, signatures and liquidity are not verified here. Use morpho_midnight_status and preview morpho_midnight_take with the returned exact offer/proof; callback offers need a separately qualified builder. This read publishes nothing and creates no signature."}}catch(a){throw new i(l.plainError(a))}}}]});export{D as a,H as b,G as c};
1
+ import{e as g,f as T,g as k,i as E}from"./XKLXVTSE.js";import{c as _,d as S}from"./W7QNSNOH.js";import{g as h}from"./NWNYJ26T.js";import{b as f}from"./TI727O2H.js";import{a as i}from"./XSD5NL7J.js";import{decodeAbiParameters as P,encodeAbiParameters as B,getAddress as d}from"viem";var D=d("0xcEF685D4796FA80F71a97e803D2c0b6719F1b4E2"),H=[{name:"items",type:"tuple[]",components:[{...k[0],name:"offer"},{name:"ratifierData",type:"bytes"}]}],G=l=>({tools:[{name:"longbow_fixed_offers",inputSchema:{type:"object",additionalProperties:!1,properties:{limit:{type:"integer",minimum:1,maximum:50,description:"Maximum number of offers to return, 1 to 50 (default 20). Newest-expiring offers come first."},marketId:{type:"string",description:"Optional Midnight market id as 0x followed by 64 hex digits (bytes32); only offers in that market are returned."}}},execute:async o=>{try{let a=o.limit??20;if(Object.keys(o).some(s=>!["limit","marketId"].includes(s))||!Number.isInteger(a)||Number(a)<1||Number(a)>50||o.marketId!==void 0&&(typeof o.marketId!="string"||!/^0x[0-9a-f]{64}$/i.test(o.marketId)))throw new i("Use limit 1..50 and an optional exact bytes32 marketId.");let p=await l.http("https://longbow.credit/api/fixed/offers",{method:"GET",redirect:"error"});if(!p.ok)throw new i(`Longbow fixed order book returned HTTP ${p.status}; offers are unavailable.`);let x=await p.text();if(x.length>2e6)throw new i("Longbow fixed order book exceeds the supported response size.");let t=JSON.parse(x);if(!t||t.chainId!==f||typeof t.mempool!="string"||d(t.mempool)!==D||!Array.isArray(t.publications)||t.publications.length>1e3||!Number.isSafeInteger(t.head)||Number(t.head)<0)throw new i("Longbow fixed indexer does not match the pinned chain, mempool or publication schema.");let c=[],u=[],y=0;for(let[s,m]of t.publications.entries())try{if(!m||typeof m!="object")throw new i("Invalid publication.");let r=m,n=r.itemsAbi;if(!Number.isSafeInteger(r.blockNumber)||Number(r.blockNumber)<0||Number(r.blockNumber)>Number(t.head))throw new i("Invalid publication block.");if(typeof n!="string"||!/^0x[0-9a-f]+$/i.test(n)||n.length>1e6||n.length<130||BigInt(`0x${n.slice(2,66)}`)!==32n||BigInt(`0x${n.slice(66,130)}`)>512n)throw new i("Invalid or oversized publication encoding.");let[w]=P(H,n);if(w.length!==r.items)throw new i("Publication count mismatch.");for(let b of w){y++;let e=b.offer;if(e.market.chainId!==BigInt(f)||d(e.market.midnight)!==g||b.ratifierData.length>32770)throw new i("Publication market or proof is unqualified.");let I=E(e.market);if(o.marketId!==void 0&&!h(I,String(o.marketId)))continue;let N=[_,S].find(O=>h(O.address,e.market.loanToken));c.push({marketId:I,offer:B(k,[e]),ratifierData:b.ratifierData,maker:d(e.maker),buy:e.buy,maturity:e.market.maturity.toString(),start:e.start.toString(),expiry:e.expiry.toString(),tick:e.tick.toString(),loanToken:N??null,directBuilderSupported:!!N&&/^0x0{40}$/i.test(e.callback)&&e.callbackData==="0x"&&T.includes(d(e.ratifier)),sourceBlock:String(r.blockNumber)})}}catch(r){u.push({publication:s,reason:l.plainError(r)})}return c.sort((s,m)=>BigInt(s.expiry)>BigInt(m.expiry)?-1:BigInt(s.expiry)<BigInt(m.expiry)?1:0),{chainId:f,midnight:g,mempool:D,indexedHead:String(t.head),decodedCount:y,matchingCount:c.length,offers:c.slice(0,Number(a)),incomplete:u.length>0||t.skipped!==0,rejected:u,warning:"Historical off-chain publications, not executable quotes. Expiry, consumption, authorization, signatures and liquidity are not verified here. Use morpho_midnight_status and preview morpho_midnight_take with the returned exact offer/proof; callback offers need a separately qualified builder. This read publishes nothing and creates no signature."}}catch(a){throw new i(l.plainError(a))}}}]});export{D as a,H as b,G as c};
@@ -1,2 +1,2 @@
1
- import{t as T}from"./AXHFNE6L.js";import{b as C,c as N,d as E}from"./3PU2SD3U.js";import{b as M}from"./WAKZWSHB.js";import{b as O,la as S}from"./V5YSJKRH.js";import{a as R}from"./P4UQGWCP.js";import{c as v}from"./SCG5HWMN.js";import{e as y}from"./NWNYJ26T.js";import{b as m,j as _}from"./TI727O2H.js";import{a as p}from"./XSD5NL7J.js";import{getAddress as x,isAddress as k}from"viem";function P(i){if(typeof i!="string"||!i.trim()||i.length>200)throw new p("Provide nonempty filter text of at most 200 characters.");return i}function $(i,u){if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>u)throw new p(`Choose a pagination integer from 0 to ${u}.`);return i}var w={morpho:{assess:"morpho_status",enter:"morpho_supply_collateral",exit:"morpho_withdraw_collateral"},steakhouse:{assess:"steakhouse_list",enter:"steakhouse_deposit",exit:"steakhouse_withdraw"},spark:{assess:"spark_list",enter:"spark_deposit",exit:"spark_withdraw"},netnet:{assess:"netnet_list",enter:"netnet_deposit",exit:"netnet_withdraw"},longbow:{assess:"longbow_list",enter:"longbow_deposit",exit:"longbow_withdraw"},grove:{assess:"grove_list",enter:"grove_deposit",exit:"grove_withdraw"},beefy:{assess:"beefy_list",enter:"beefy_deposit",exit:"beefy_withdraw"},uniswap:{assess:"uniswap_list_positions",enter:"uniswap_add",exit:"uniswap_remove"},layerbank:{assess:"layerbank_list",enter:"layerbank_deposit",exit:"layerbank_withdraw"}},h=_[m].vaults,L={steakhouse:[h.steakhouse.address],spark:[h.spark.address],netnet:[h.netnet.address],longbow:[h.longbowCore.address,h.longbowFrontier.address,h.longbowEth.address],grove:[h.groveAlm.address],beefy:R.vaults.map(i=>i.earnContractAddress),layerbank:[M]},U=new Set(T.map(i=>i.marketId.toLowerCase()));function q(i,u){return Object.hasOwn(L,i)&&typeof u=="string"&&k(u,{strict:!1})&&L[i].some(g=>g.toLowerCase()===u.toLowerCase())}var Z=i=>{let u=(t,n,r)=>({name:`merkl_${t}`,inputSchema:{type:"object",properties:n,additionalProperties:!1},execute:async(c,e)=>{try{let s=Object.keys(c).find(d=>!Object.hasOwn(n,d));if(s)throw new p(`Unsupported Merkl input: ${s}.`);return await r(c,e)}catch(s){throw new p(i.plainError(s))}}}),g={page:{type:"integer",minimum:0,maximum:1e4,description:"Zero-based page number."},items:{type:"integer",minimum:1,maximum:100,description:"Maximum entries per page, from 1 to 100."}},A=async(t,n)=>{let r=new URL(`https://api.merkl.xyz/v4/${t}`);for(let[c,e]of Object.entries(n))r.searchParams.set(c,e);return v(i.http,r.toString(),{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},c=>Array.isArray(c)||y(c))},b=t=>{let n=$(t.items??20,100);if(!n)throw new p("Choose at least one item per page.");return{page:String($(t.page??0,1e4)),items:String(n)}};return{tools:[u("opportunities",{...g,protocol:{type:"string",description:"Protocol identifier to filter opportunities."},name:{type:"string",description:"Opportunity name search text."},explorerAddress:{type:"string",description:"Pool or market contract address to filter opportunities."}},async t=>{let n={chainId:String(m),campaigns:"true",...b(t)};if(t.protocol!==void 0&&(n.mainProtocolId=P(t.protocol)),t.name!==void 0&&(n.name=P(t.name)),t.explorerAddress!==void 0){if(typeof t.explorerAddress!="string"||!k(t.explorerAddress,{strict:!1}))throw new p("Provide a pool or market explorer address.");n.explorerAddress=x(t.explorerAddress)}let r=await A("opportunities",n);if(!Array.isArray(r)||!r.every(e=>y(e)&&typeof e.id=="string"&&Number.isSafeInteger(e.chainId)))throw new p("Merkl returned unexpected opportunities.");return{opportunities:r.filter(e=>e.chainId===m).map(e=>{let s=(y(e.protocol)?e.protocol.id:void 0)??e.mainProtocolId??e.mainProtocol,d=typeof s=="string"?s.toLowerCase():"",o;d==="morpho"&&e.action==="LEND"?e.type==="MORPHOCOLLATERAL"?[e.marketId,e.identifier,e.explorerAddress].some(I=>typeof I=="string"&&U.has(I.toLowerCase()))&&(o=w.morpho):typeof e.type=="string"&&(e.type==="ERC20LOGPROCESSOR"||e.type.includes("MORPHOVAULT"))&&typeof e.explorerAddress=="string"&&k(e.explorerAddress,{strict:!1})&&x(e.explorerAddress)===_[m].vaults.steakhouse.address&&(o=w.steakhouse):d==="uniswap"?e.type==="UNISWAP_V4"&&e.action==="POOL"&&(o=w.uniswap):q(d,e.explorerAddress)&&(e.action==="LEND"||e.action==="STAKE")&&(o=w[d]);let l=e.action==="POOL"||o?.enter==="uniswap_add",a=l?E(e.campaigns,Math.floor(Date.now()/1e3)):void 0,f=l&&a?{lpWarning:`Illustration for $100; no deposit amount has been selected.
1
+ import{t as T}from"./XKLXVTSE.js";import{b as C,c as N,d as E}from"./3PU2SD3U.js";import{b as M}from"./WAKZWSHB.js";import{b as O,la as S}from"./V5YSJKRH.js";import{a as R}from"./P4UQGWCP.js";import{c as v}from"./SCG5HWMN.js";import{e as y}from"./NWNYJ26T.js";import{b as m,j as _}from"./TI727O2H.js";import{a as p}from"./XSD5NL7J.js";import{getAddress as x,isAddress as k}from"viem";function P(i){if(typeof i!="string"||!i.trim()||i.length>200)throw new p("Provide nonempty filter text of at most 200 characters.");return i}function $(i,u){if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>u)throw new p(`Choose a pagination integer from 0 to ${u}.`);return i}var w={morpho:{assess:"morpho_status",enter:"morpho_supply_collateral",exit:"morpho_withdraw_collateral"},steakhouse:{assess:"steakhouse_list",enter:"steakhouse_deposit",exit:"steakhouse_withdraw"},spark:{assess:"spark_list",enter:"spark_deposit",exit:"spark_withdraw"},netnet:{assess:"netnet_list",enter:"netnet_deposit",exit:"netnet_withdraw"},longbow:{assess:"longbow_list",enter:"longbow_deposit",exit:"longbow_withdraw"},grove:{assess:"grove_list",enter:"grove_deposit",exit:"grove_withdraw"},beefy:{assess:"beefy_list",enter:"beefy_deposit",exit:"beefy_withdraw"},uniswap:{assess:"uniswap_list_positions",enter:"uniswap_add",exit:"uniswap_remove"},layerbank:{assess:"layerbank_list",enter:"layerbank_deposit",exit:"layerbank_withdraw"}},h=_[m].vaults,L={steakhouse:[h.steakhouse.address],spark:[h.spark.address],netnet:[h.netnet.address],longbow:[h.longbowCore.address,h.longbowFrontier.address,h.longbowEth.address],grove:[h.groveAlm.address],beefy:R.vaults.map(i=>i.earnContractAddress),layerbank:[M]},U=new Set(T.map(i=>i.marketId.toLowerCase()));function q(i,u){return Object.hasOwn(L,i)&&typeof u=="string"&&k(u,{strict:!1})&&L[i].some(g=>g.toLowerCase()===u.toLowerCase())}var Z=i=>{let u=(t,n,r)=>({name:`merkl_${t}`,inputSchema:{type:"object",properties:n,additionalProperties:!1},execute:async(c,e)=>{try{let s=Object.keys(c).find(d=>!Object.hasOwn(n,d));if(s)throw new p(`Unsupported Merkl input: ${s}.`);return await r(c,e)}catch(s){throw new p(i.plainError(s))}}}),g={page:{type:"integer",minimum:0,maximum:1e4,description:"Zero-based page number."},items:{type:"integer",minimum:1,maximum:100,description:"Maximum entries per page, from 1 to 100."}},A=async(t,n)=>{let r=new URL(`https://api.merkl.xyz/v4/${t}`);for(let[c,e]of Object.entries(n))r.searchParams.set(c,e);return v(i.http,r.toString(),{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},c=>Array.isArray(c)||y(c))},b=t=>{let n=$(t.items??20,100);if(!n)throw new p("Choose at least one item per page.");return{page:String($(t.page??0,1e4)),items:String(n)}};return{tools:[u("opportunities",{...g,protocol:{type:"string",description:"Protocol identifier to filter opportunities."},name:{type:"string",description:"Opportunity name search text."},explorerAddress:{type:"string",description:"Pool or market contract address to filter opportunities."}},async t=>{let n={chainId:String(m),campaigns:"true",...b(t)};if(t.protocol!==void 0&&(n.mainProtocolId=P(t.protocol)),t.name!==void 0&&(n.name=P(t.name)),t.explorerAddress!==void 0){if(typeof t.explorerAddress!="string"||!k(t.explorerAddress,{strict:!1}))throw new p("Provide a pool or market explorer address.");n.explorerAddress=x(t.explorerAddress)}let r=await A("opportunities",n);if(!Array.isArray(r)||!r.every(e=>y(e)&&typeof e.id=="string"&&Number.isSafeInteger(e.chainId)))throw new p("Merkl returned unexpected opportunities.");return{opportunities:r.filter(e=>e.chainId===m).map(e=>{let s=(y(e.protocol)?e.protocol.id:void 0)??e.mainProtocolId??e.mainProtocol,d=typeof s=="string"?s.toLowerCase():"",o;d==="morpho"&&e.action==="LEND"?e.type==="MORPHOCOLLATERAL"?[e.marketId,e.identifier,e.explorerAddress].some(I=>typeof I=="string"&&U.has(I.toLowerCase()))&&(o=w.morpho):typeof e.type=="string"&&(e.type==="ERC20LOGPROCESSOR"||e.type.includes("MORPHOVAULT"))&&typeof e.explorerAddress=="string"&&k(e.explorerAddress,{strict:!1})&&x(e.explorerAddress)===_[m].vaults.steakhouse.address&&(o=w.steakhouse):d==="uniswap"?e.type==="UNISWAP_V4"&&e.action==="POOL"&&(o=w.uniswap):q(d,e.explorerAddress)&&(e.action==="LEND"||e.action==="STAKE")&&(o=w[d]);let l=e.action==="POOL"||o?.enter==="uniswap_add",a=l?E(e.campaigns,Math.floor(Date.now()/1e3)):void 0,f=l&&a?{lpWarning:`Illustration for $100; no deposit amount has been selected.
2
2
  ${C({apr:typeof e.apr=="number"?e.apr:a.aprPct,endDate:typeof e.endTimestamp=="number"||typeof e.endTimestamp=="string"?e.endTimestamp:a.endsAt,amountUsd:100,outOfRangeIncentivized:a.outOfRangeIncentivized,feeWeightPct:a.feeWeightPct,creator:d==="uniswap"?a.creator:void 0})}`}:{};return{...e,oak:{...o?{candidateTools:o}:{},...f,destinationVerificationRequired:!0,eligibility:"Read campaign conditions; no wallet eligibility has been verified."}}}),...b(t),hasMore:r.length===Number(n.items),summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Public, untrusted campaign data includes conditions and destinations. Candidate Oak tools require a matching verified market/vault and a supported entry AND exit. APR is indicative; no rewards are promised."}}),u("campaigns",{...g,creator:{type:"string",description:"Campaign creator address to filter."},tokenSymbol:{type:"string",description:"Reward token symbol to filter campaigns."},opportunityId:{type:"string",pattern:"^\\d{1,30}$",description:"Merkl opportunity identifier as a decimal string of 1 to 30 digits."}},async t=>{if(t.opportunityId!==void 0&&(t.creator!==void 0||t.tokenSymbol!==void 0))throw new p("Use creator and tokenSymbol without opportunityId; the opportunity endpoint does not support those filters.");if(t.opportunityId!==void 0&&(typeof t.opportunityId!="string"||!/^\d{1,30}$/.test(t.opportunityId)))throw new p("Provide an opportunityId as a decimal string of 1 to 30 digits.");let n={chainId:String(m),withOpportunity:"true",...b(t)};if(t.creator!==void 0){if(typeof t.creator!="string"||!k(t.creator,{strict:!1}))throw new p("Provide a creator address.");n.creatorAddress=x(t.creator)}t.tokenSymbol!==void 0&&(n.tokenSymbol=P(t.tokenSymbol));let r=t.opportunityId===void 0?"campaigns":`opportunities/${t.opportunityId}/campaigns`,c=await A(r,t.opportunityId===void 0?n:{}),e=t.opportunityId!==void 0&&y(c)?c:void 0;if(e&&e.chainId!==m)throw new p(`Merkl opportunity must be on chain ${m}.`);let s=t.opportunityId===void 0?c:e?.campaigns;if(!Array.isArray(s)||!s.every(f=>y(f)&&(typeof f.id=="string"||typeof f.id=="number")))throw new p("Merkl returned unexpected campaigns.");let d=e?s.filter(f=>f.distributionChainId===m):s,o=Number(n.page)*Number(n.items),l=t.opportunityId===void 0?d:d.slice(o,o+Number(n.items)),a=t.opportunityId===void 0?d.length===Number(n.items):o+Number(n.items)<d.length;return{campaigns:l,...e?{opportunity:{id:e.id,name:e.name,chainId:e.chainId,protocol:y(e.protocol)?{id:e.protocol.id,name:e.protocol.name}:void 0,explorerAddress:e.explorerAddress,identifier:e.identifier}}:{},chainId:m,...b(t),hasMore:a,summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Campaign rules, budgets, timing, exclusions and configuration are public API data; verify the reward distribution chain and destination before entering."}}),u("earning_status",{view:{enum:["active","breakdowns","stats","claims"],description:"active lists earning opportunities; breakdowns shows reward details; stats shows totals; claims lists claims."},...g},async(t,n)=>{if(!k(n,{strict:!1}))throw new p("Provide a valid connected wallet address.");let r=t.view??"active";if(!["active","breakdowns","stats","claims"].includes(String(r)))throw new p("Choose active, breakdowns, stats or claims.");let c=r==="claims"?"claims":r==="breakdowns"?`users/${n}/rewards/chains/${m}/breakdowns`:`users/${n}/rewards/${r==="active"?"active-opportunities":"stats"}`,{page:e,items:s}=b(t),d=r==="breakdowns"?{}:{chainId:String(m)};r==="claims"&&(d.recipient=n);let o=await A(c,d),l=Number(e)*Number(s),a=Array.isArray(o)?o:r==="breakdowns"&&y(o)&&Array.isArray(o.opportunities)?o.opportunities:void 0,f=a?Array.isArray(o)?a.slice(l,l+Number(s)):{...o,opportunities:a.slice(l,l+Number(s))}:o,D=r==="active"&&Array.isArray(a)&&a.length===0?`${O(S,{after_deposit:N()})} `:"";return{view:r,chainId:m,wallet:n,data:f,...a?{page:e,items:s,hasMore:l+Number(s)<a.length}:{},summary:`${D}Powered by Merkl \u2014 https://app.merkl.xyz. API earning attribution and history can lag onchain state; pending earnings are not claimable. Private or restricted attribution may be omitted by Merkl. Recheck merkl_rewards before a claim.`}})]}};export{Z as a};