@oakagentkit/core 0.3.1 → 0.3.3

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/{OLDQV43V.js → CM4DP2EZ.js} +1 -1
  31. package/build/dist/chunks/{AG2G7BHH.js → CU4PWGMJ.js} +1 -1
  32. package/build/dist/chunks/{M7CQPTRK.js → CXH46MHJ.js} +1 -1
  33. package/build/dist/chunks/{UYULQHZJ.js → FSYYD3OM.js} +1 -1
  34. package/build/dist/chunks/{Z2QV6EZY.js → HPY2ONAS.js} +1 -1
  35. package/build/dist/chunks/{AIYNFIG6.js → I3ZBOSSH.js} +1 -1
  36. package/build/dist/chunks/{W7OCS4AM.js → IZFED3R2.js} +1 -1
  37. package/build/dist/chunks/{HQIS3QI7.js → MDLJFCT4.js} +2 -2
  38. package/build/dist/chunks/{M6SQPOOL.js → OFWTO4N6.js} +1 -1
  39. package/build/dist/chunks/{QHV5GORV.js → SO6O7JK2.js} +1 -1
  40. package/build/dist/chunks/{HOBIXKGO.js → UCHJYWGU.js} +1 -1
  41. package/build/dist/chunks/{4NDIYRH5.js → WCI3FHWT.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 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"./IZFED3R2.js";import{c as I,e as A}from"./MDLJFCT4.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,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.3"}});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{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{a as R}from"./DFM4T6ZE.js";import{d as N}from"./HQIS3QI7.js";import{b as D,d as M,f as C}from"./4ZD5D2UP.js";import{t as E}from"./MQ5F2VOK.js";import{a}from"./XSD5NL7J.js";import{a as P}from"./JXOEJPJ4.js";import{decodeFunctionData as _,erc20Abi as X,formatUnits as $,getAddress as x,isAddress as Q,parseUnits as K,parseAbi as V,zeroAddress as f}from"viem";var be=300,m={permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",router:"0x204FAca1764B154221e35c0d20aBb3c525710498",factory:"0xd7e538e98A208fD19e46bc549FF4710C33664e18",limitOrders:"0x3126f62d604a0AA2de8788e3eC21dDd8F2a2f82a",fobo:"0x000DE658153f47f23e92973C8EB1e89762703676",usdg:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},T=["eth","fobo","usdg","msft","tsla","spcx","googl","amzn","aapl","nvda","meta"],b=(t,e=0)=>({type:"string",minLength:e,maxLength:t}),w=(t,e="string")=>({type:e,enum:t}),B={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},v={type:"string",pattern:"^[0-9]+$",description:"Exact input in token base units, as a decimal integer string."},U={type:"integer",minimum:1,maximum:100},L={token:B,amount:v,payWith:w(["pair","eth","usdg","fobo"]),slippageBps:{type:"integer",minimum:1,maximum:5e3}},Z={token:"FOBO coin contract address on chain 4663; obtain it from fobo_browse or fobo_token.",query:"Search FOBO coins and traders by name, ticker or address; omit to browse recent launches.",limit:"Maximum number of results, from 1 to 100.",side:"Trade direction: buy the coin or sell it back to the payment currency.",payWith:"Payment currency: pair uses the coin\u2019s own pair; trades also accept eth, usdg or fobo.",slippageBps:"Maximum loss against quoted output in basis points (50 = 0.5%); default 50.",hash:"Public transaction hash (0x followed by 64 hex digits) to look up on FOBO.",name:"New coin name, 1 to 32 characters.",ticker:"New coin ticker, 2 to 10 letters or digits; normalized to uppercase.",description:"Public description of the new coin, at most 280 characters.",imageUrl:"Optional public HTTPS image URL; omit for no image. Local uploads are unsupported.",links:"Optional public project links stored with the launched coin.",telegram:"Public Telegram URL.",discord:"Public Discord URL.",github:"Public GitHub URL.",website:"Public project website URL.",pair:"Pair currency: eth, fobo, usdg or a supported stock ticker; referral claims use this currency.",devBuyTokens:"Whole tokens in the initial buy, 0 to 50,000,000 (5% of supply); default 0.",vestMonths:"Initial-buy lock in months: 0, 1, 3, 6 or 12; default 0. A lock requires an initial buy.",limitMarketCapUsd:"Target market capitalization in whole USD, as a decimal string; not a per-token price.",expiresIn:"Order lifetime: 1h, 1d, 7d or 30d; default 7d.",maxFeePerFill:"Maximum keeper fee per fill in payment-token base units, as an exact decimal integer string.",orderId:"Positive numeric ID of the local wallet\u2019s limit order to cancel.",kind:"Claim creator fees, referral earnings or vesting tokens.",to:"Optional recipient address for a referral claim; omit for this wallet. Other claims always pay this wallet."},l=(t,e=[])=>({type:"object",additionalProperties:!1,required:e,properties:Object.fromEntries(Object.entries(t).map(([r,s])=>{let o=s;return[r,{...o,description:o.description??Z[r]}]}))}),Y={fobo_browse:l({query:b(64,1),limit:U}),fobo_token:l({token:B},["token"]),fobo_portfolio:l({}),fobo_leaderboard:l({limit:U}),fobo_claims:l({}),fobo_limit_orders:l({token:B}),fobo_quote:l({...L,side:w(["buy","sell"])},["token","side","amount"]),fobo_fee_schedule:l({}),fobo_limit_pay_tokens:l({}),fobo_transaction:l({hash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}},["hash"]),fobo_buy:l(L,["token","amount"]),fobo_sell:l(L,["token","amount"]),fobo_launch:l({name:b(32,1),ticker:{type:"string",pattern:"^\\$?[a-zA-Z0-9]{2,10}$"},description:b(280),imageUrl:{...b(2e3),pattern:"^https://"},links:l({telegram:b(200),discord:b(200),github:b(200),website:b(200)}),pair:w(T),devBuyTokens:{type:"integer",minimum:0,maximum:5e7},vestMonths:w([0,1,3,6,12],"integer"),maxInitialBuyAmount:{...v,description:"Maximum pair-token base units to spend on the initial buy, excluding the live launch fee. Required when devBuyTokens is positive."}},["name","ticker"]),fobo_limit_order:l({token:B,side:w(["buy","sell"]),payWith:b(42,2),amount:v,limitMarketCapUsd:{type:"string",pattern:"^\\d{1,30}(\\.\\d{1,18})?$"},expiresIn:w(["1h","1d","7d","30d"]),maxFeePerFill:v},["token","side","amount","limitMarketCapUsd","maxFeePerFill"]),fobo_cancel_limit_order:l({orderId:{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}},["orderId"]),fobo_claim:l({kind:w(["creator","referral","vesting"]),token:B,pair:w(T),to:B},["kind"])},ee={fobo_buy:"buy",fobo_sell:"sell",fobo_launch:"launch",fobo_limit_order:"limitOrder",fobo_cancel_limit_order:"cancel",fobo_claim:"claim"},te={buy:"prepare_trade",sell:"prepare_trade",launch:"prepare_launch",limitOrder:"prepare_limit_order",cancel:"prepare_cancel_limit_order",claim:"prepare_claim"};function g(t){if(!t||typeof t!="object"||Array.isArray(t))throw new a("FOBO returned an invalid answer. Ask for a fresh summary.");return t}function ne(t,e){function r(s,o){let d=s.properties;if(Object.keys(o).some(n=>!Object.hasOwn(d,n)))throw new a("Unexpected FOBO argument. Use the fields declared by the tool.");for(let n of s.required)if(o[n]===void 0)throw new a(`Missing FOBO argument: ${n}.`);for(let[n,i]of Object.entries(o)){let c=d[n];if(c.type==="object"){r(c,g(i));continue}if(c.type==="integer"){if(typeof i!="number"||!Number.isSafeInteger(i)||i<Number(c.minimum??0)||i>Number(c.maximum??Number.MAX_SAFE_INTEGER))throw new a(`Invalid FOBO argument: ${n}.`)}else if(typeof i!="string"||i.length<Number(c.minLength??0)||i.length>Number(c.maxLength??256)||typeof c.pattern=="string"&&!new RegExp(c.pattern).test(i))throw new a(`Invalid FOBO argument: ${n}.`);if(Array.isArray(c.enum)&&!c.enum.includes(i))throw new a(`Invalid FOBO argument: ${n}.`)}}if(r(Y[t],g(e)),t==="fobo_claim"&&(e.kind==="referral"?e.pair===void 0:e.token===void 0))throw new a("Referral claims need pair; creator and vesting claims need token.");if(t==="fobo_claim"&&e.kind!=="referral"&&e.to!==void 0)throw new a("Only referral claims may name another recipient.");if(t==="fobo_launch"){if(Number(e.vestMonths??0)>0&&Number(e.devBuyTokens??0)===0)throw new a("A vesting lock needs an initial buy.");if(Number(e.devBuyTokens??0)>0&&(typeof e.maxInitialBuyAmount!="string"||BigInt(e.maxInitialBuyAmount)===0n))throw new a("An initial buy needs maxInitialBuyAmount in pair-token base units. Ask the person for that spending cap.");if(e.imageUrl!==void 0){let s=new URL(String(e.imageUrl));if(s.protocol!=="https:"||s.username||s.password)throw new a("Use a public https image URL.")}}return structuredClone(e)}function y(t){let e=t.toLowerCase();if(e===f||e==="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")return{address:f,decimals:18};if(e===m.usdg.toLowerCase())return{address:m.usdg,decimals:6};if(e===m.fobo.toLowerCase())return{address:m.fobo,decimals:18};if(t==="eth")return{address:f,decimals:18};if(t==="usdg")return{address:m.usdg,decimals:6};if(t==="fobo")return{address:m.fobo,decimals:18};let r=R.tokens.find(s=>T.includes(t)&&s.symbol.toLowerCase()===t||s.token.toLowerCase()===e);if(r)return{address:x(r.token),decimals:18};throw new a("FOBO did not identify a supported pair currency. Ask for token details first.")}function A(t,e,r){if(typeof t!="string"||!/^\d{1,78}(\.\d{1,18})?$/.test(t)||(t.split(".")[1]?.length??0)>e)throw new a(`FOBO returned an invalid ${r}. Ask for a fresh quote.`);return K(t,e).toString()}function re(t,e,r,s){if(String(t.payWith).replace(/^\$/,"").toLowerCase()!==s.toLowerCase())throw new a("FOBO quote payment currency differs from the request.");if(t.slippageBps!==r)throw new a("FOBO quote slippage differs from the request.");let o=A(t.expectedOut,e,"quote output"),d=A(t.minOut,e,"quote minimum"),n=BigInt(o)*BigInt(1e4-r)/10000n;if(BigInt(d)<=0n||BigInt(d)>BigInt(o)||BigInt(d)<n)throw new a("FOBO quote minimum exceeds the approved slippage loss.");return{amountOut:o,minimum:d}}function W(t){let e=Object.fromEntries(Object.entries(t.request).filter(([r])=>!r.startsWith("_")&&r!=="maxInitialBuyAmount"));return typeof e.links=="string"&&(e.links=JSON.parse(e.links)),e.amount!==void 0&&(e.amount=$(BigInt(String(e.amount)),Number(t.request._inputDecimals))),e.maxFeePerFill!==void 0&&(e.maxFeePerFill=$(BigInt(String(e.maxFeePerFill)),Number(t.request._payDecimals))),(t.kind==="buy"||t.kind==="sell")&&(e.side=t.kind),t.kind==="claim"&&e.pair!==void 0&&(e.currency=e.pair,delete e.pair),{...e,account:t.wallet}}function S(t,e,r="0x0Af57F62982D03066ef917AcAd87F771c06528Ec"){let[s,o]=BigInt(t)<BigInt(e)?[t,e]:[e,t];return{currency0:s,currency1:o,fee:r===f?500:0,tickSpacing:r===f?10:60,hooks:r}}function j(t,e){let r=t===f?e:t;if(t!==f&&e!==f)throw new a("FOBO base-currency routes must pass through ETH.");if(r.toLowerCase()===m.usdg.toLowerCase())return S(t,e,f);if(r.toLowerCase()===m.fobo.toLowerCase())return S(t,e);throw new a("FOBO has not pinned a route between this pair and ETH. Use the token\u2019s own pair.")}function oe(t,e,r,s){let o=[];return r.toLowerCase()!==e.toLowerCase()&&(r!==f&&o.push(j(r,f)),e!==f&&o.push(j(f,e))),o.push(S(e,t)),s?o.reverse():o}function ie(t,e,r,s){let o=t.request,d=t.terms;if(t.kind==="buy"||t.kind==="sell")return{kind:"trade",currencyIn:o._currencyIn,currencyOut:o._currencyOut,amountIn:BigInt(d.amountIn),minOut:BigInt(d.minOut),now:e,pools:JSON.parse(String(o._pools)),...s?{permit:s}:{}};if(t.kind==="launch"){let i=(r?_({abi:D,data:r.data}).args[0]:void 0)?.devBuyMaxCost??BigInt(d.amountIn??"0");if(i>BigInt(d.amountIn??"0"))throw new a("FOBO launch exceeds the approved initial-buy spending cap. Nothing further was signed.");return{kind:"launch",name:String(o.name),ticker:String(o.ticker).replace(/^\$/,"").toUpperCase(),pair:y(String(o.pair)).address,devBuyTokens:BigInt(d.devBuyTokens??0)*10n**18n,devBuyMaxCost:i,vestMonths:d.vestMonths??0,launchFeeWei:BigInt(d.launchFeeWei),now:e}}if(t.kind==="limitOrder"){if(!r)throw new a("FOBO order is missing its unsigned transaction.");let n=_({abi:M,data:r.data});if(n.functionName!=="place")throw new a("FOBO order must call place.");let i=n.args[5],k={"1h":3600,"1d":86400,"7d":604800,"30d":2592e3}[String(o.expiresIn??"7d")],O=BigInt(t.quotedAt+k);if(i<O-60n||i>BigInt(e+k)+60n)throw new a("FOBO changed the approved order expiry. Nothing further was signed.");return{kind:"limitOrder",side:o.side==="buy"?0:1,token:d.token,payToken:y(String(o.payWith)).address,amount:BigInt(d.amountIn),limitPriceUsdE18:K(String(o.limitMarketCapUsd),18)/1000000000n,expiry:i,maxFeePerFill:BigInt(String(o.maxFeePerFill))}}if(t.kind==="cancel")return{kind:"cancel",orderId:BigInt(String(o.orderId))};if(o.kind==="creator")return{kind:"claim",claimKind:"creator",poolKey:JSON.parse(String(o._poolKey))};if(o.kind==="referral")return{kind:"claim",claimKind:"referral",currency:y(String(o.pair)).address,recipient:o.to??t.wallet};if(o.kind==="vesting"&&r)return{kind:"claim",claimKind:"vesting",lockId:_({abi:C,data:r.data}).args[0],beneficiary:t.wallet};throw new a("FOBO claim does not match a supported claim kind.")}function ae(t){let e={...g(t)};if(e.status==="needs_signature"&&e.transactions===void 0&&(e.transactions=[]),!["ready","needs_approval","needs_signature"].includes(String(e.status))||!Array.isArray(e.transactions)||e.transactions.length>32)throw new a("FOBO returned an unsupported preparation. Nothing further was signed. Ask for a fresh summary.");return e}function se(t,e,r){let s=g(e);if(![4663,"0x1237"].includes(s.chainId)||String(s.from).toLowerCase()!==t.wallet.toLowerCase()||BigInt(String(s.value??"0"))!==0n)throw new a("FOBO approval has the wrong wallet, chain or ETH value. Nothing further was signed.");let o=_({abi:X,data:String(s.data)});if(o.functionName!=="approve")throw new a("FOBO requested something other than an approval.");let d=o.args[0],n=t.kind==="launch"?m.factory:t.kind==="limitOrder"?m.limitOrders:m.permit2;if(d.toLowerCase()!==n.toLowerCase()||String(s.to).toLowerCase()!==String(t.request._currencyIn).toLowerCase()||t.terms.amountIn===void 0)throw new a("FOBO approval does not match the approved token and spender. Nothing further was signed.");return N(e,{kind:"approval",token:x(String(s.to)),spender:d,amount:BigInt(t.terms.amountIn)},t.wallet)}async function de(t,e,r,s,o){if(e.status==="needs_signature"){if(e.transactions.length)throw new a("FOBO attached unexpected transactions to a signature request.");return[]}if(!e.transactions.length||t.kind!=="claim"&&e.transactions.length!==1)throw new a("FOBO returned an unexpected transaction count. Nothing further was signed.");if(e.status==="needs_approval"){if(!["buy","sell","launch","limitOrder"].includes(t.kind))throw new a("This FOBO action must not need an approval.");return e.transactions.map(n=>se(t,n,r))}if(e.transactions.some(n=>String(g(n).data).toLowerCase().startsWith("0x095ea7b3")))throw new a("FOBO attached an approval to a ready action. Ask for a fresh summary.");if(t.kind==="claim"&&t.request.kind==="vesting"){let n=o??E({chainId:4663}).readContract,i=V(["function getLock(uint256 id) view returns ((address token,uint64 start,uint32 duration,address beneficiary,uint256 amount,uint256 claimed))"]);for(let c of e.transactions){let k=_({abi:C,data:c.data}).args[0],O=await n({address:"0x51d217Ecf7c0e4EbF54258444B9617D012Fd7D0a",abi:i,functionName:"getLock",args:[k]});if(O.beneficiary.toLowerCase()!==t.wallet.toLowerCase()||O.token.toLowerCase()!==String(t.request.token).toLowerCase())throw new a("FOBO vesting lock does not belong to this wallet and token. Nothing further was signed.")}}let d=e.transactions.map(n=>N(n,ie(t,r,n,s),t.wallet));if(t.kind==="launch"){let n=BigInt(t.terms.launchFeeWei??"0"),i=t.request.pair==="eth"?n+BigInt(t.terms.amountIn??"0"):n;if(d.some(c=>BigInt(c.value)>i||BigInt(c.value)<n))throw new a("FOBO launch exceeds the approved spending cap or changed its fee. Nothing further was signed.")}if(typeof t.request._prepared=="string"){let n=JSON.parse(t.request._prepared);if(d.length!==n.length||d.some((i,c)=>i.to.toLowerCase()!==n[c].to.toLowerCase()||i.data.toLowerCase()!==n[c].data.toLowerCase()||BigInt(i.value)!==BigInt(n[c].value)))throw new a("FOBO changed the approved terms. Nothing further was signed. Ask for a fresh summary.")}return d}function ce(t){let e="Oak fee: 0 bps on FOBO\u2019s own route.";if(t.kind==="buy"||t.kind==="sell"){let r=t.terms.tokenPoolTaxPercentNow;if(typeof r!="number"||!Number.isFinite(r)||r<0||r>100)throw new a("FOBO quote did not identify its current tax.");return`${e} FOBO's tax right now: ${r}%; included in the quoted output and minimum.`}return t.kind==="launch"?`${e} FOBO launch fee: ${$(BigInt(t.terms.launchFeeWei),18)} ETH (${t.terms.launchFeeWei} wei).`:t.kind==="limitOrder"?`${e} FOBO keeper fee: at most ${t.request.maxFeePerFill} pay-token base units per fill. Pool tax applies when the order fills; the future tax is not known at preparation.`:`${e} No additional FOBO fee for this ${t.kind==="cancel"?"cancellation":"claim"}; network fees are additional.`}async function we(t,e,r,s){let o=Object.entries(ee).find(([,u])=>u===e)?.[0];if(!o||!Q(s,{strict:!1}))throw new a("Provide a valid FOBO action and local wallet.");let d=ne(o,r),n={};for(let[u,p]of Object.entries(d))n[u]=typeof p=="object"?JSON.stringify(p):p;let i={version:1,kind:e,wallet:x(s),chainId:4663,request:n,terms:{},quotedAt:Math.floor(Date.now()/1e3)};if(e==="launch"){n.pair??="eth",n.devBuyTokens??=0,n.vestMonths??=0;let u=g(g(await t.call("get_fee_schedule",{})).launch);if(u.launchesPaused===!0)throw new a("FOBO launches are paused. Nothing was signed.");let p=y(String(n.pair));n._currencyIn=p.address,n._inputDecimals=p.decimals,i.preparation={status:"ready",transactions:[]},i.terms={launchFeeWei:A(u.feeEth,18,"launch fee"),devBuyTokens:Number(n.devBuyTokens),vestMonths:Number(n.vestMonths),amountIn:String(n.maxInitialBuyAmount??"0")}}else if(e==="buy"||e==="sell"||e==="limitOrder"){n.payWith??=e==="limitOrder"?"eth":"pair";let u=String(n.payWith),p=g(await t.call("get_token",{token:n.token}));if(String(p.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO token metadata does not match the requested token.");let H=y(String(p.pair).replace(/^\$/,"").toLowerCase());u==="pair"&&(u=String(p.pair).replace(/^\$/,"").toLowerCase());let F=y(u);n._payDecimals=F.decimals;let I=e==="limitOrder"?n.side:e;if(n._currencyIn=I==="sell"?String(n.token):F.address,n._currencyOut=I==="sell"?F.address:String(n.token),n._inputDecimals=I==="sell"?18:F.decimals,n._outputDecimals=I==="sell"?F.decimals:18,e!=="limitOrder"&&(n._pools=JSON.stringify(oe(x(String(n.token)),H.address,F.address,I==="sell"))),i.terms={token:x(String(n.token)),payWith:String(n.payWith),amountIn:String(n.amount)},BigInt(String(n.amount))===0n)throw new a("FOBO input amount must be positive.");if(e!=="limitOrder"){n.slippageBps??=50;let{account:J,...z}=W(i),h=g(await t.call("quote_trade",z)),G=A(h.amountIn,Number(n._inputDecimals),"quote input"),{minimum:q}=re(h,Number(n._outputDecimals),Number(n.slippageBps),u);if(G!==n.amount||BigInt(q)===0n||String(h.token).toLowerCase()!==String(n.token).toLowerCase()||h.side!==e)throw new a("FOBO quote does not match the requested trade. Nothing was signed.");if(i.terms.minOut=q,i.terms.slippageBps=Number(n.slippageBps),typeof h.tokenPoolTaxPercentNow!="number"||!Number.isFinite(h.tokenPoolTaxPercentNow)||h.tokenPoolTaxPercentNow<0||h.tokenPoolTaxPercentNow>100)throw new a("FOBO quote did not identify its current tax.");i.terms.tokenPoolTaxPercentNow=h.tokenPoolTaxPercentNow}}if(e==="claim"&&n.kind==="creator"){let u=g(await t.call("get_token",{token:n.token}));if(String(u.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO claim token metadata does not match.");n._poolKey=JSON.stringify(S(y(String(u.pair).replace(/^\$/,"").toLowerCase()).address,x(String(n.token))))}if(e!=="launch"){let u=ae(await t.call(te[e],W(i))),p=await de(i,u,i.quotedAt);if(i.preparation={status:u.status,transactions:p},e==="cancel"||e==="claim"||e==="limitOrder"){if(u.status==="needs_signature")throw new a("This FOBO action must not need a permit signature.");u.status==="ready"&&(n._prepared=JSON.stringify(p))}}let c=e==="launch"?`Launch ${P(String(n.name))} (${P(String(n.ticker))}), pair ${n.pair}, initial buy ${n.devBuyTokens} tokens, lock ${n.vestMonths} months.`:e==="limitOrder"?`Place a FOBO ${n.side} order for ${n.token}, limit market cap ${n.limitMarketCapUsd} USD, expiry ${n.expiresIn??"7d"}, maximum keeper fee ${n.maxFeePerFill} pay-token base units per fill.`:e==="claim"?`Claim FOBO ${n.kind} earnings${n.token?` for ${n.token}`:` in ${n.pair}`} to ${n.to??s}.`:e==="cancel"?`Cancel FOBO order ${n.orderId} and refund ${s}.`:`${e} on FOBO for ${n.token}.`,k=e==="launch"?`Launch fee ${i.terms.launchFeeWei} wei; initial-buy spending cap ${i.terms.amountIn} pair-token base units.`:`Exact input ${i.terms.amountIn??"0"} base units.`,O=`${c}
1
+ import{a as R}from"./DFM4T6ZE.js";import{d as N}from"./MDLJFCT4.js";import{b as D,d as M,f as C}from"./4ZD5D2UP.js";import{t as E}from"./MQ5F2VOK.js";import{a}from"./XSD5NL7J.js";import{a as P}from"./JXOEJPJ4.js";import{decodeFunctionData as _,erc20Abi as X,formatUnits as $,getAddress as x,isAddress as Q,parseUnits as K,parseAbi as V,zeroAddress as f}from"viem";var be=300,m={permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",router:"0x204FAca1764B154221e35c0d20aBb3c525710498",factory:"0xd7e538e98A208fD19e46bc549FF4710C33664e18",limitOrders:"0x3126f62d604a0AA2de8788e3eC21dDd8F2a2f82a",fobo:"0x000DE658153f47f23e92973C8EB1e89762703676",usdg:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},T=["eth","fobo","usdg","msft","tsla","spcx","googl","amzn","aapl","nvda","meta"],b=(t,e=0)=>({type:"string",minLength:e,maxLength:t}),w=(t,e="string")=>({type:e,enum:t}),B={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},v={type:"string",pattern:"^[0-9]+$",description:"Exact input in token base units, as a decimal integer string."},U={type:"integer",minimum:1,maximum:100},L={token:B,amount:v,payWith:w(["pair","eth","usdg","fobo"]),slippageBps:{type:"integer",minimum:1,maximum:5e3}},Z={token:"FOBO coin contract address on chain 4663; obtain it from fobo_browse or fobo_token.",query:"Search FOBO coins and traders by name, ticker or address; omit to browse recent launches.",limit:"Maximum number of results, from 1 to 100.",side:"Trade direction: buy the coin or sell it back to the payment currency.",payWith:"Payment currency: pair uses the coin\u2019s own pair; trades also accept eth, usdg or fobo.",slippageBps:"Maximum loss against quoted output in basis points (50 = 0.5%); default 50.",hash:"Public transaction hash (0x followed by 64 hex digits) to look up on FOBO.",name:"New coin name, 1 to 32 characters.",ticker:"New coin ticker, 2 to 10 letters or digits; normalized to uppercase.",description:"Public description of the new coin, at most 280 characters.",imageUrl:"Optional public HTTPS image URL; omit for no image. Local uploads are unsupported.",links:"Optional public project links stored with the launched coin.",telegram:"Public Telegram URL.",discord:"Public Discord URL.",github:"Public GitHub URL.",website:"Public project website URL.",pair:"Pair currency: eth, fobo, usdg or a supported stock ticker; referral claims use this currency.",devBuyTokens:"Whole tokens in the initial buy, 0 to 50,000,000 (5% of supply); default 0.",vestMonths:"Initial-buy lock in months: 0, 1, 3, 6 or 12; default 0. A lock requires an initial buy.",limitMarketCapUsd:"Target market capitalization in whole USD, as a decimal string; not a per-token price.",expiresIn:"Order lifetime: 1h, 1d, 7d or 30d; default 7d.",maxFeePerFill:"Maximum keeper fee per fill in payment-token base units, as an exact decimal integer string.",orderId:"Positive numeric ID of the local wallet\u2019s limit order to cancel.",kind:"Claim creator fees, referral earnings or vesting tokens.",to:"Optional recipient address for a referral claim; omit for this wallet. Other claims always pay this wallet."},l=(t,e=[])=>({type:"object",additionalProperties:!1,required:e,properties:Object.fromEntries(Object.entries(t).map(([r,s])=>{let o=s;return[r,{...o,description:o.description??Z[r]}]}))}),Y={fobo_browse:l({query:b(64,1),limit:U}),fobo_token:l({token:B},["token"]),fobo_portfolio:l({}),fobo_leaderboard:l({limit:U}),fobo_claims:l({}),fobo_limit_orders:l({token:B}),fobo_quote:l({...L,side:w(["buy","sell"])},["token","side","amount"]),fobo_fee_schedule:l({}),fobo_limit_pay_tokens:l({}),fobo_transaction:l({hash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}},["hash"]),fobo_buy:l(L,["token","amount"]),fobo_sell:l(L,["token","amount"]),fobo_launch:l({name:b(32,1),ticker:{type:"string",pattern:"^\\$?[a-zA-Z0-9]{2,10}$"},description:b(280),imageUrl:{...b(2e3),pattern:"^https://"},links:l({telegram:b(200),discord:b(200),github:b(200),website:b(200)}),pair:w(T),devBuyTokens:{type:"integer",minimum:0,maximum:5e7},vestMonths:w([0,1,3,6,12],"integer"),maxInitialBuyAmount:{...v,description:"Maximum pair-token base units to spend on the initial buy, excluding the live launch fee. Required when devBuyTokens is positive."}},["name","ticker"]),fobo_limit_order:l({token:B,side:w(["buy","sell"]),payWith:b(42,2),amount:v,limitMarketCapUsd:{type:"string",pattern:"^\\d{1,30}(\\.\\d{1,18})?$"},expiresIn:w(["1h","1d","7d","30d"]),maxFeePerFill:v},["token","side","amount","limitMarketCapUsd","maxFeePerFill"]),fobo_cancel_limit_order:l({orderId:{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}},["orderId"]),fobo_claim:l({kind:w(["creator","referral","vesting"]),token:B,pair:w(T),to:B},["kind"])},ee={fobo_buy:"buy",fobo_sell:"sell",fobo_launch:"launch",fobo_limit_order:"limitOrder",fobo_cancel_limit_order:"cancel",fobo_claim:"claim"},te={buy:"prepare_trade",sell:"prepare_trade",launch:"prepare_launch",limitOrder:"prepare_limit_order",cancel:"prepare_cancel_limit_order",claim:"prepare_claim"};function g(t){if(!t||typeof t!="object"||Array.isArray(t))throw new a("FOBO returned an invalid answer. Ask for a fresh summary.");return t}function ne(t,e){function r(s,o){let d=s.properties;if(Object.keys(o).some(n=>!Object.hasOwn(d,n)))throw new a("Unexpected FOBO argument. Use the fields declared by the tool.");for(let n of s.required)if(o[n]===void 0)throw new a(`Missing FOBO argument: ${n}.`);for(let[n,i]of Object.entries(o)){let c=d[n];if(c.type==="object"){r(c,g(i));continue}if(c.type==="integer"){if(typeof i!="number"||!Number.isSafeInteger(i)||i<Number(c.minimum??0)||i>Number(c.maximum??Number.MAX_SAFE_INTEGER))throw new a(`Invalid FOBO argument: ${n}.`)}else if(typeof i!="string"||i.length<Number(c.minLength??0)||i.length>Number(c.maxLength??256)||typeof c.pattern=="string"&&!new RegExp(c.pattern).test(i))throw new a(`Invalid FOBO argument: ${n}.`);if(Array.isArray(c.enum)&&!c.enum.includes(i))throw new a(`Invalid FOBO argument: ${n}.`)}}if(r(Y[t],g(e)),t==="fobo_claim"&&(e.kind==="referral"?e.pair===void 0:e.token===void 0))throw new a("Referral claims need pair; creator and vesting claims need token.");if(t==="fobo_claim"&&e.kind!=="referral"&&e.to!==void 0)throw new a("Only referral claims may name another recipient.");if(t==="fobo_launch"){if(Number(e.vestMonths??0)>0&&Number(e.devBuyTokens??0)===0)throw new a("A vesting lock needs an initial buy.");if(Number(e.devBuyTokens??0)>0&&(typeof e.maxInitialBuyAmount!="string"||BigInt(e.maxInitialBuyAmount)===0n))throw new a("An initial buy needs maxInitialBuyAmount in pair-token base units. Ask the person for that spending cap.");if(e.imageUrl!==void 0){let s=new URL(String(e.imageUrl));if(s.protocol!=="https:"||s.username||s.password)throw new a("Use a public https image URL.")}}return structuredClone(e)}function y(t){let e=t.toLowerCase();if(e===f||e==="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")return{address:f,decimals:18};if(e===m.usdg.toLowerCase())return{address:m.usdg,decimals:6};if(e===m.fobo.toLowerCase())return{address:m.fobo,decimals:18};if(t==="eth")return{address:f,decimals:18};if(t==="usdg")return{address:m.usdg,decimals:6};if(t==="fobo")return{address:m.fobo,decimals:18};let r=R.tokens.find(s=>T.includes(t)&&s.symbol.toLowerCase()===t||s.token.toLowerCase()===e);if(r)return{address:x(r.token),decimals:18};throw new a("FOBO did not identify a supported pair currency. Ask for token details first.")}function A(t,e,r){if(typeof t!="string"||!/^\d{1,78}(\.\d{1,18})?$/.test(t)||(t.split(".")[1]?.length??0)>e)throw new a(`FOBO returned an invalid ${r}. Ask for a fresh quote.`);return K(t,e).toString()}function re(t,e,r,s){if(String(t.payWith).replace(/^\$/,"").toLowerCase()!==s.toLowerCase())throw new a("FOBO quote payment currency differs from the request.");if(t.slippageBps!==r)throw new a("FOBO quote slippage differs from the request.");let o=A(t.expectedOut,e,"quote output"),d=A(t.minOut,e,"quote minimum"),n=BigInt(o)*BigInt(1e4-r)/10000n;if(BigInt(d)<=0n||BigInt(d)>BigInt(o)||BigInt(d)<n)throw new a("FOBO quote minimum exceeds the approved slippage loss.");return{amountOut:o,minimum:d}}function W(t){let e=Object.fromEntries(Object.entries(t.request).filter(([r])=>!r.startsWith("_")&&r!=="maxInitialBuyAmount"));return typeof e.links=="string"&&(e.links=JSON.parse(e.links)),e.amount!==void 0&&(e.amount=$(BigInt(String(e.amount)),Number(t.request._inputDecimals))),e.maxFeePerFill!==void 0&&(e.maxFeePerFill=$(BigInt(String(e.maxFeePerFill)),Number(t.request._payDecimals))),(t.kind==="buy"||t.kind==="sell")&&(e.side=t.kind),t.kind==="claim"&&e.pair!==void 0&&(e.currency=e.pair,delete e.pair),{...e,account:t.wallet}}function S(t,e,r="0x0Af57F62982D03066ef917AcAd87F771c06528Ec"){let[s,o]=BigInt(t)<BigInt(e)?[t,e]:[e,t];return{currency0:s,currency1:o,fee:r===f?500:0,tickSpacing:r===f?10:60,hooks:r}}function j(t,e){let r=t===f?e:t;if(t!==f&&e!==f)throw new a("FOBO base-currency routes must pass through ETH.");if(r.toLowerCase()===m.usdg.toLowerCase())return S(t,e,f);if(r.toLowerCase()===m.fobo.toLowerCase())return S(t,e);throw new a("FOBO has not pinned a route between this pair and ETH. Use the token\u2019s own pair.")}function oe(t,e,r,s){let o=[];return r.toLowerCase()!==e.toLowerCase()&&(r!==f&&o.push(j(r,f)),e!==f&&o.push(j(f,e))),o.push(S(e,t)),s?o.reverse():o}function ie(t,e,r,s){let o=t.request,d=t.terms;if(t.kind==="buy"||t.kind==="sell")return{kind:"trade",currencyIn:o._currencyIn,currencyOut:o._currencyOut,amountIn:BigInt(d.amountIn),minOut:BigInt(d.minOut),now:e,pools:JSON.parse(String(o._pools)),...s?{permit:s}:{}};if(t.kind==="launch"){let i=(r?_({abi:D,data:r.data}).args[0]:void 0)?.devBuyMaxCost??BigInt(d.amountIn??"0");if(i>BigInt(d.amountIn??"0"))throw new a("FOBO launch exceeds the approved initial-buy spending cap. Nothing further was signed.");return{kind:"launch",name:String(o.name),ticker:String(o.ticker).replace(/^\$/,"").toUpperCase(),pair:y(String(o.pair)).address,devBuyTokens:BigInt(d.devBuyTokens??0)*10n**18n,devBuyMaxCost:i,vestMonths:d.vestMonths??0,launchFeeWei:BigInt(d.launchFeeWei),now:e}}if(t.kind==="limitOrder"){if(!r)throw new a("FOBO order is missing its unsigned transaction.");let n=_({abi:M,data:r.data});if(n.functionName!=="place")throw new a("FOBO order must call place.");let i=n.args[5],k={"1h":3600,"1d":86400,"7d":604800,"30d":2592e3}[String(o.expiresIn??"7d")],O=BigInt(t.quotedAt+k);if(i<O-60n||i>BigInt(e+k)+60n)throw new a("FOBO changed the approved order expiry. Nothing further was signed.");return{kind:"limitOrder",side:o.side==="buy"?0:1,token:d.token,payToken:y(String(o.payWith)).address,amount:BigInt(d.amountIn),limitPriceUsdE18:K(String(o.limitMarketCapUsd),18)/1000000000n,expiry:i,maxFeePerFill:BigInt(String(o.maxFeePerFill))}}if(t.kind==="cancel")return{kind:"cancel",orderId:BigInt(String(o.orderId))};if(o.kind==="creator")return{kind:"claim",claimKind:"creator",poolKey:JSON.parse(String(o._poolKey))};if(o.kind==="referral")return{kind:"claim",claimKind:"referral",currency:y(String(o.pair)).address,recipient:o.to??t.wallet};if(o.kind==="vesting"&&r)return{kind:"claim",claimKind:"vesting",lockId:_({abi:C,data:r.data}).args[0],beneficiary:t.wallet};throw new a("FOBO claim does not match a supported claim kind.")}function ae(t){let e={...g(t)};if(e.status==="needs_signature"&&e.transactions===void 0&&(e.transactions=[]),!["ready","needs_approval","needs_signature"].includes(String(e.status))||!Array.isArray(e.transactions)||e.transactions.length>32)throw new a("FOBO returned an unsupported preparation. Nothing further was signed. Ask for a fresh summary.");return e}function se(t,e,r){let s=g(e);if(![4663,"0x1237"].includes(s.chainId)||String(s.from).toLowerCase()!==t.wallet.toLowerCase()||BigInt(String(s.value??"0"))!==0n)throw new a("FOBO approval has the wrong wallet, chain or ETH value. Nothing further was signed.");let o=_({abi:X,data:String(s.data)});if(o.functionName!=="approve")throw new a("FOBO requested something other than an approval.");let d=o.args[0],n=t.kind==="launch"?m.factory:t.kind==="limitOrder"?m.limitOrders:m.permit2;if(d.toLowerCase()!==n.toLowerCase()||String(s.to).toLowerCase()!==String(t.request._currencyIn).toLowerCase()||t.terms.amountIn===void 0)throw new a("FOBO approval does not match the approved token and spender. Nothing further was signed.");return N(e,{kind:"approval",token:x(String(s.to)),spender:d,amount:BigInt(t.terms.amountIn)},t.wallet)}async function de(t,e,r,s,o){if(e.status==="needs_signature"){if(e.transactions.length)throw new a("FOBO attached unexpected transactions to a signature request.");return[]}if(!e.transactions.length||t.kind!=="claim"&&e.transactions.length!==1)throw new a("FOBO returned an unexpected transaction count. Nothing further was signed.");if(e.status==="needs_approval"){if(!["buy","sell","launch","limitOrder"].includes(t.kind))throw new a("This FOBO action must not need an approval.");return e.transactions.map(n=>se(t,n,r))}if(e.transactions.some(n=>String(g(n).data).toLowerCase().startsWith("0x095ea7b3")))throw new a("FOBO attached an approval to a ready action. Ask for a fresh summary.");if(t.kind==="claim"&&t.request.kind==="vesting"){let n=o??E({chainId:4663}).readContract,i=V(["function getLock(uint256 id) view returns ((address token,uint64 start,uint32 duration,address beneficiary,uint256 amount,uint256 claimed))"]);for(let c of e.transactions){let k=_({abi:C,data:c.data}).args[0],O=await n({address:"0x51d217Ecf7c0e4EbF54258444B9617D012Fd7D0a",abi:i,functionName:"getLock",args:[k]});if(O.beneficiary.toLowerCase()!==t.wallet.toLowerCase()||O.token.toLowerCase()!==String(t.request.token).toLowerCase())throw new a("FOBO vesting lock does not belong to this wallet and token. Nothing further was signed.")}}let d=e.transactions.map(n=>N(n,ie(t,r,n,s),t.wallet));if(t.kind==="launch"){let n=BigInt(t.terms.launchFeeWei??"0"),i=t.request.pair==="eth"?n+BigInt(t.terms.amountIn??"0"):n;if(d.some(c=>BigInt(c.value)>i||BigInt(c.value)<n))throw new a("FOBO launch exceeds the approved spending cap or changed its fee. Nothing further was signed.")}if(typeof t.request._prepared=="string"){let n=JSON.parse(t.request._prepared);if(d.length!==n.length||d.some((i,c)=>i.to.toLowerCase()!==n[c].to.toLowerCase()||i.data.toLowerCase()!==n[c].data.toLowerCase()||BigInt(i.value)!==BigInt(n[c].value)))throw new a("FOBO changed the approved terms. Nothing further was signed. Ask for a fresh summary.")}return d}function ce(t){let e="Oak fee: 0 bps on FOBO\u2019s own route.";if(t.kind==="buy"||t.kind==="sell"){let r=t.terms.tokenPoolTaxPercentNow;if(typeof r!="number"||!Number.isFinite(r)||r<0||r>100)throw new a("FOBO quote did not identify its current tax.");return`${e} FOBO's tax right now: ${r}%; included in the quoted output and minimum.`}return t.kind==="launch"?`${e} FOBO launch fee: ${$(BigInt(t.terms.launchFeeWei),18)} ETH (${t.terms.launchFeeWei} wei).`:t.kind==="limitOrder"?`${e} FOBO keeper fee: at most ${t.request.maxFeePerFill} pay-token base units per fill. Pool tax applies when the order fills; the future tax is not known at preparation.`:`${e} No additional FOBO fee for this ${t.kind==="cancel"?"cancellation":"claim"}; network fees are additional.`}async function we(t,e,r,s){let o=Object.entries(ee).find(([,u])=>u===e)?.[0];if(!o||!Q(s,{strict:!1}))throw new a("Provide a valid FOBO action and local wallet.");let d=ne(o,r),n={};for(let[u,p]of Object.entries(d))n[u]=typeof p=="object"?JSON.stringify(p):p;let i={version:1,kind:e,wallet:x(s),chainId:4663,request:n,terms:{},quotedAt:Math.floor(Date.now()/1e3)};if(e==="launch"){n.pair??="eth",n.devBuyTokens??=0,n.vestMonths??=0;let u=g(g(await t.call("get_fee_schedule",{})).launch);if(u.launchesPaused===!0)throw new a("FOBO launches are paused. Nothing was signed.");let p=y(String(n.pair));n._currencyIn=p.address,n._inputDecimals=p.decimals,i.preparation={status:"ready",transactions:[]},i.terms={launchFeeWei:A(u.feeEth,18,"launch fee"),devBuyTokens:Number(n.devBuyTokens),vestMonths:Number(n.vestMonths),amountIn:String(n.maxInitialBuyAmount??"0")}}else if(e==="buy"||e==="sell"||e==="limitOrder"){n.payWith??=e==="limitOrder"?"eth":"pair";let u=String(n.payWith),p=g(await t.call("get_token",{token:n.token}));if(String(p.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO token metadata does not match the requested token.");let H=y(String(p.pair).replace(/^\$/,"").toLowerCase());u==="pair"&&(u=String(p.pair).replace(/^\$/,"").toLowerCase());let F=y(u);n._payDecimals=F.decimals;let I=e==="limitOrder"?n.side:e;if(n._currencyIn=I==="sell"?String(n.token):F.address,n._currencyOut=I==="sell"?F.address:String(n.token),n._inputDecimals=I==="sell"?18:F.decimals,n._outputDecimals=I==="sell"?F.decimals:18,e!=="limitOrder"&&(n._pools=JSON.stringify(oe(x(String(n.token)),H.address,F.address,I==="sell"))),i.terms={token:x(String(n.token)),payWith:String(n.payWith),amountIn:String(n.amount)},BigInt(String(n.amount))===0n)throw new a("FOBO input amount must be positive.");if(e!=="limitOrder"){n.slippageBps??=50;let{account:J,...z}=W(i),h=g(await t.call("quote_trade",z)),G=A(h.amountIn,Number(n._inputDecimals),"quote input"),{minimum:q}=re(h,Number(n._outputDecimals),Number(n.slippageBps),u);if(G!==n.amount||BigInt(q)===0n||String(h.token).toLowerCase()!==String(n.token).toLowerCase()||h.side!==e)throw new a("FOBO quote does not match the requested trade. Nothing was signed.");if(i.terms.minOut=q,i.terms.slippageBps=Number(n.slippageBps),typeof h.tokenPoolTaxPercentNow!="number"||!Number.isFinite(h.tokenPoolTaxPercentNow)||h.tokenPoolTaxPercentNow<0||h.tokenPoolTaxPercentNow>100)throw new a("FOBO quote did not identify its current tax.");i.terms.tokenPoolTaxPercentNow=h.tokenPoolTaxPercentNow}}if(e==="claim"&&n.kind==="creator"){let u=g(await t.call("get_token",{token:n.token}));if(String(u.address).toLowerCase()!==String(n.token).toLowerCase())throw new a("FOBO claim token metadata does not match.");n._poolKey=JSON.stringify(S(y(String(u.pair).replace(/^\$/,"").toLowerCase()).address,x(String(n.token))))}if(e!=="launch"){let u=ae(await t.call(te[e],W(i))),p=await de(i,u,i.quotedAt);if(i.preparation={status:u.status,transactions:p},e==="cancel"||e==="claim"||e==="limitOrder"){if(u.status==="needs_signature")throw new a("This FOBO action must not need a permit signature.");u.status==="ready"&&(n._prepared=JSON.stringify(p))}}let c=e==="launch"?`Launch ${P(String(n.name))} (${P(String(n.ticker))}), pair ${n.pair}, initial buy ${n.devBuyTokens} tokens, lock ${n.vestMonths} months.`:e==="limitOrder"?`Place a FOBO ${n.side} order for ${n.token}, limit market cap ${n.limitMarketCapUsd} USD, expiry ${n.expiresIn??"7d"}, maximum keeper fee ${n.maxFeePerFill} pay-token base units per fill.`:e==="claim"?`Claim FOBO ${n.kind} earnings${n.token?` for ${n.token}`:` in ${n.pair}`} to ${n.to??s}.`:e==="cancel"?`Cancel FOBO order ${n.orderId} and refund ${s}.`:`${e} on FOBO for ${n.token}.`,k=e==="launch"?`Launch fee ${i.terms.launchFeeWei} wei; initial-buy spending cap ${i.terms.amountIn} pair-token base units.`:`Exact input ${i.terms.amountIn??"0"} base units.`,O=`${c}
2
2
  Leaves wallet: ${k}
3
3
  Comes back: ${i.terms.minOut?`at least ${i.terms.minOut} output base units`:e==="launch"?"the launched token and any initial buy, subject to the stated lock":"the approved order or claim proceeds to the named recipient"}.
4
4
  Fees: no Oak swap fee on FOBO's route. ${ce(i)}
@@ -1,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 W(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"),W(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"),c=T(n.gas,"gas");i(c>=21000n&&c<=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 W(a),m(a,e.spender,"approval spender differs from the approved action"),{...J(r,a,e.amount),gasLimit:c.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(u=>l(u.poolKey.hooks,o.hook))&&t.legs.every((u,b)=>M(u.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(u=>l(u.poolKey.hooks,o.hook)||M(u.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 u=e.permit;i(u,"swap encodes an unexpected permit"),m(u.details.token,e.currencyIn,"permit token differs from the trade input"),i(T(u.details.amount,"permit amount",160)===e.amountIn&&e.amountIn<w(160),"permit amount differs from the exact trade input"),m(u.spender,o.router,"permit spender must be the Universal Router");let b=T(u.sigDeadline,"permit deadline");i(Number.isSafeInteger(u.details.expiration)&&u.details.expiration>e.now&&BigInt(u.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,u.details.token)&&g.amount===e.amountIn&&g.expiration===u.details.expiration&&g.nonce===u.details.nonce&&l(g.spender,u.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,u,b,g,z,V,Z]=t.args;i((a===0||a===1)&&a===e.side,"limit order side differs"),m(u,e.token,"limit order token differs"),m(b,e.payToken,"limit order pay token differs"),i(g===p(e.amount,"order amount")&&g>0n&&z===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:c.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 c=3;d[c]!=="URI: https://fobo.fun"&&d[c]!=="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[c]??"")&&d[c+1]==="",r),c+=2),i(["URI: https://fobo.fun","URI: https://fobo.fun/"].includes(d[c]??""),r),c+=1,d[c]?.startsWith("Version:")&&(i(d[c]==="Version: 1",r),c++),d[c]?.startsWith("Chain ID:")&&(i(d[c]==="Chain ID: 4663",r),c++),i(/^Nonce: [a-zA-Z0-9]{8,128}$/.test(d[c]??""),r);let O=d[c+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===c+2,r);let f=Math.floor(Date.parse(O)/1e3);i(Number.isFinite(f)&&f<=s+2&&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{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{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 +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};