@oakagentkit/core 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/dist/api/addresses.d.ts +1 -1
- package/build/dist/api/addresses.js +1 -1
- package/build/dist/api/amounts.js +1 -1
- package/build/dist/api/canonical.js +1 -1
- package/build/dist/api/chain.js +1 -1
- package/build/dist/api/errors.d.ts +1 -0
- package/build/dist/api/errors.js +1 -1
- package/build/dist/api/gas.d.ts +5 -0
- package/build/dist/api/gas.js +1 -0
- package/build/dist/api/grandfather.js +1 -1
- package/build/dist/api/history.js +1 -1
- package/build/dist/api/http.js +1 -1
- package/build/dist/api/identity-link.js +1 -1
- package/build/dist/api/merkle.js +1 -1
- package/build/dist/api/metadata.js +1 -1
- package/build/dist/api/module.js +1 -1
- package/build/dist/api/modules/beefy/index.js +1 -1
- package/build/dist/api/modules/clanker/index.js +1 -1
- package/build/dist/api/modules/erc8004/index.d.ts +11 -0
- package/build/dist/api/modules/erc8004/index.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/heyresearch/index.js +1 -1
- package/build/dist/api/modules/hoodag/index.js +1 -1
- package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
- package/build/dist/api/modules/hoodlock/index.js +1 -1
- package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
- package/build/dist/api/modules/hookr/create-cancel.js +1 -1
- package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
- package/build/dist/api/modules/hookr/index.js +1 -1
- package/build/dist/api/modules/kyberswap/index.js +1 -1
- package/build/dist/api/modules/lighter/index.js +1 -1
- package/build/dist/api/modules/longbow/index.js +1 -1
- package/build/dist/api/modules/meridian/index.js +1 -1
- package/build/dist/api/modules/meridian/markets.js +1 -1
- package/build/dist/api/modules/meridian/rfq.js +1 -1
- package/build/dist/api/modules/merkl/index.js +1 -1
- package/build/dist/api/modules/morpho/index.js +1 -1
- package/build/dist/api/modules/netnet/index.js +1 -1
- package/build/dist/api/modules/orbio/index.js +1 -1
- package/build/dist/api/modules/pons/claim.js +1 -1
- package/build/dist/api/modules/pons/index.js +1 -1
- package/build/dist/api/modules/pons/launch-status.js +1 -1
- package/build/dist/api/modules/pons/prices.js +1 -1
- package/build/dist/api/modules/pons/trade.js +1 -1
- package/build/dist/api/modules/poolstrade/index.js +1 -1
- package/build/dist/api/modules/priors/index.js +1 -1
- package/build/dist/api/modules/relay/inbound.d.ts +2 -0
- package/build/dist/api/modules/relay/inbound.js +1 -1
- package/build/dist/api/modules/relay/index.js +1 -1
- package/build/dist/api/modules/relay/outbound-status.js +1 -1
- package/build/dist/api/modules/spark/index.js +1 -1
- package/build/dist/api/modules/steakhouse/index.js +1 -1
- package/build/dist/api/modules/tickerspring/index.js +1 -1
- package/build/dist/api/modules/uniswap/index.js +1 -1
- package/build/dist/api/modules/uniswap/v3.js +1 -1
- package/build/dist/api/modules/uniswap/v4.js +1 -1
- package/build/dist/api/modules/velora/index.js +1 -1
- package/build/dist/api/positions.js +1 -1
- package/build/dist/api/pricenote.js +1 -1
- package/build/dist/api/prices.js +1 -1
- package/build/dist/api/pricing.js +1 -1
- package/build/dist/api/routes.js +1 -1
- package/build/dist/api/secret-fields.js +1 -1
- package/build/dist/api/simulate.js +1 -1
- package/build/dist/api/swap.d.ts +5 -1
- package/build/dist/api/swap.js +1 -1
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/api/tx.js +1 -1
- package/build/dist/api/types.d.ts +3 -0
- package/build/dist/api/vendor-limits.js +1 -1
- package/build/dist/chunks/{OOSNTGDJ.js → 5B3UVWMV.js} +1 -1
- package/build/dist/chunks/5BP72XOA.js +1 -0
- package/build/dist/chunks/5SH3C7XP.js +1 -0
- package/build/dist/chunks/{YEE3KKTA.js → 6YQ2RX5I.js} +1 -1
- package/build/dist/chunks/{64EN6Y7E.js → 74X7PXPR.js} +1 -1
- package/build/dist/chunks/{B5RZYFQC.js → 7I6TXFXR.js} +1 -1
- package/build/dist/chunks/A5O3SRHY.js +1 -0
- package/build/dist/chunks/{D45AODDL.js → B2LA6VVF.js} +1 -1
- package/build/dist/chunks/{ZERWRK6X.js → CWQ5WXZQ.js} +1 -1
- package/build/dist/chunks/{YTHDLCHL.js → F3TOOLFQ.js} +1 -1
- package/build/dist/chunks/GOIVHR4B.js +1 -0
- package/build/dist/chunks/{47PKSOXA.js → M643PYHO.js} +1 -1
- package/build/dist/chunks/{P7Q6MJZH.js → MEZH7RPA.js} +1 -1
- package/build/dist/chunks/{AE6YEEZP.js → NDHEJGWR.js} +1 -1
- package/build/dist/chunks/NNJLMS7F.js +1 -0
- package/build/dist/chunks/{ZKOMJGNH.js → PQHU5A3U.js} +1 -1
- package/build/dist/chunks/{UL2L7NHO.js → R5CBH2CR.js} +1 -1
- package/build/dist/chunks/{VZPFBWVH.js → RYOVSHKO.js} +1 -1
- package/build/dist/chunks/{75D6Q7L3.js → SUQ6PIAV.js} +1 -1
- package/build/dist/chunks/{KFMNCJXJ.js → SXBGOGYQ.js} +1 -1
- package/build/dist/chunks/{LZK6C5LT.js → T4IYMYZD.js} +1 -1
- package/build/dist/chunks/{IABIXUNX.js → TFYLOWFO.js} +1 -1
- package/build/dist/chunks/{ZUAXW2ZD.js → TU3KHOZK.js} +1 -1
- package/build/dist/chunks/{SGDWO7XI.js → UB5U6SI2.js} +1 -1
- package/build/dist/chunks/UIJWIFGV.js +1 -0
- package/build/dist/chunks/{VZWOWR6G.js → VBWJOG3N.js} +1 -1
- package/build/dist/chunks/{KP7VSXIQ.js → WFE3NXBF.js} +1 -1
- package/build/dist/chunks/XAB4OIE3.js +1 -0
- package/build/dist/chunks/XEN45QST.js +1 -0
- package/build/dist/chunks/{MGEJPRXP.js → XKZOMGC3.js} +1 -1
- package/build/dist/chunks/{JMPOXXNJ.js → XTUXR43N.js} +1 -1
- package/build/dist/chunks/{UZH4FQEL.js → Y2SGXWFM.js} +1 -1
- package/build/dist/chunks/Z3FZWNAJ.js +1 -0
- package/build/dist/chunks/Z53DADZ4.js +1 -0
- package/build/dist/chunks/ZJUNO5N7.js +1 -0
- package/build/dist/chunks/ZZLHDHOT.js +1 -0
- package/package.json +9 -13
- package/build/dist/chunks/24JYIH53.js +0 -1
- package/build/dist/chunks/25EOXUBI.js +0 -1
- package/build/dist/chunks/4P6XI564.js +0 -1
- package/build/dist/chunks/6YU3JLQQ.js +0 -1
- package/build/dist/chunks/BH3CI6WO.js +0 -1
- package/build/dist/chunks/CUBRTOMA.js +0 -1
- package/build/dist/chunks/FSSCJNAQ.js +0 -1
- package/build/dist/chunks/S3YSJ7XH.js +0 -1
- package/build/dist/chunks/T5E4OJEU.js +0 -1
- package/build/dist/chunks/VBV366XQ.js +0 -1
- package/build/dist/chunks/XUL6NKAK.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as W}from"../../../chunks/XTUXR43N.js";import{a as J,b as V,e as E,i as G,n as b,o as Q,w as X,x as D,y as U}from"../../../chunks/XEN45QST.js";import{b as H}from"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import{a as R}from"../../../chunks/MEZH7RPA.js";import{c as z}from"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import{a as C}from"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import{a as c,i as j}from"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import{a as K}from"../../../chunks/7I6TXFXR.js";import{a as o}from"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";import{randomUUID as re}from"node:crypto";import{erc20Abi as ae}from"viem";var S=j[c].routes.kyberswap.address,Y="https://aggregator-api.kyberswap.com/robinhood/api/v1",Z="Quoted output is net of venue fees. Oak swap fee: 0.",ne=(1n<<256n)-1n;function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ee(e){return _(e)&&e.code===0&&_(e.data)}function P(e,t=!1){if(typeof e!="string")throw new o("Amount must be an integer string in base units.");let n=K(e);if(n>ne||t&&n===0n)throw new o("Swap amount must be positive and within the uint256 range.");return n.toString()}function y(e,t){return typeof e=="string"&&e.toLowerCase()===t.toLowerCase()}function $(e){if(!y(e.routerAddress,S)||e.spender!==void 0&&!y(e.spender,S))throw new o("KyberSwap router or spender does not match the evidenced deployment.");if(e.chainId!==void 0&&e.chainId!==c)throw new o("KyberSwap response is for a different chain.")}function te(e){if(typeof e!="string")throw new o("Provide a token address on chain 4663.");return C(e),H(e)}async function oe(e,t){if(b(t))return{address:t,symbol:"ETH",decimals:18,chainId:c};let[n,m]=await Promise.all([R(e,c,t,"symbol"),R(e,c,t,"decimals")]);if(typeof n!="string"||!n.trim()||!Number.isInteger(m)||m<0||m>255)throw new o("Token metadata could not be read on chain 4663.");return{address:t,symbol:n,decimals:m,chainId:c}}function h(e){if(BigInt(Math.floor(Date.now()/1e3))>=BigInt(e.expiresAt))throw new o("Quote has expired. Request a fresh quote.")}function ie(e){let t=new Map,n=async()=>{let r=e.clientFor(c);if(await r.getChainId()!==c)throw new o("KyberSwap requires an RPC on chain 4663.");return r},m={name:"kyberswap",async quote(r,a,d=!1){try{C(a);let i=te(r.from),s=te(r.to);if(y(i,s))throw new o("Choose two different token addresses.");let u=P(r.amountIn,!0),w=r.slippageBps===void 0?V:r.slippageBps;Q("1",w);let O=String(Math.floor(Date.now()/1e3)+J),A=await n(),[k,x]=await Promise.all([oe(A,i),oe(A,s)]),N=new URL(`${Y}/routes`);N.search=new URLSearchParams({tokenIn:b(i)?E:i,tokenOut:b(s)?E:s,amountIn:u}).toString();let L=await W(e.http,N.toString(),ee),F=L.value;$(F.data);let f=F.data.routeSummary;if(!_(f)||!y(f.tokenIn,i)||!y(f.tokenOut,s)||P(f.amountIn,!0)!==u)throw new o("KyberSwap route does not match the requested tokens and amount.");f.routerAddress!==void 0&&$(f);let v=P(f.amountOut,!0),I=Q(v,w);if(I==="0")throw new o("KyberSwap minimum output must be positive.");let p={quoteId:`kyberswap:${re()}`,provider:"kyberswap",from:i,to:s,wallet:a,amountIn:u,amountOut:v,minAmountOut:I,router:S,spender:S,value:b(i)?u:"0",chainId:c,slippageBps:w,expiresAt:String(Math.min(Number(O),L.expiresAt)),oakFee:"0",feeDisclosure:Z,input:{token:k,amount:u},output:{token:x,amount:v},minimumOutput:{token:x,amount:I}},T={quote:p,wallet:a,prepare:async()=>{if(h(p),T.tx)return structuredClone(T.quote);let l=await z(e.http,`${Y}/route/build`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({routeSummary:f,sender:a,recipient:a,slippageTolerance:w})},ee);if($(l.data),P(l.data.amountIn,!0)!==u)throw new o("KyberSwap built input amount does not match the route.");let g=P(l.data.amountOut,!0);if(BigInt(g)<BigInt(I))throw new o("KyberSwap built output is below the route minimum.");if(typeof l.data.data!="string")throw new o("KyberSwap did not return swap calldata.");let q=l.data.data,M=X(q).toString();if(D(q,I,!0),D(q,Q(g,w),!0),BigInt(M)>BigInt(g))throw new o("KyberSwap calldata minimum exceeds the built output.");d||(p.amountOut=g,p.minAmountOut=M,p.output.amount=g,p.minimumOutput.amount=M);let B=e.unsignedTx({to:S,data:q,value:P(l.data.transactionValue),chainId:c,description:`Swap ${e.formatAmount(u,k.decimals)} ${k.symbol} for at least ${e.formatAmount(p.minAmountOut,x.decimals)} ${x.symbol} via KyberSwap. ${Z}`});return U(B,p),h(p),p.data=B.data,T.tx=B,structuredClone(p)}};h(p);for(let[l,g]of t)BigInt(g.quote.expiresAt)<=BigInt(Math.floor(Date.now()/1e3))&&t.delete(l);return t.size>=G&&t.delete(t.keys().next().value),t.set(p.quoteId,T),d?structuredClone(p):await T.prepare()}catch(i){throw new o(e.plainError(i))}},async quotePrices(r,a){return m.quote(r,a,!0)},async prepareQuote(r,a){let d=t.get(r);if(!d)throw new o("Quote is unknown or expired. Request a fresh quote.");if(!y(a,d.wallet))throw new o("Quote belongs to a different wallet.");return d.prepare()},async readAllowance(r,a){let d=t.get(r);if(!d)throw new o("Quote is unknown or expired. Request a fresh quote.");if(h(d.quote),!y(a,d.wallet))throw new o("Quote belongs to a different wallet.");let i=await n(),s=d.quote.input.token.address;if(b(s))return"0";let u=await i.readContract({address:s,abi:ae,functionName:"allowance",args:[a,S]});if(typeof u!="bigint"||u<0n||u>ne)throw new o("Token allowance could not be read.");return h(d.quote),u.toString()},async build(r,a,d={}){try{C(a);let i=t.get(r);if(!i)throw new o("Quote is unknown or expired. Request a fresh quote.");let{quote:s}=i;if(h(s),!y(a,i.wallet))throw new o("Quote belongs to a different wallet.");await m.prepareQuote(r,a);let u=[],w=s.input.token.address,O=K(d.allowance??await m.readAllowance(r,a));b(w)||O<BigInt(s.input.amount)&&u.push(e.approval(w,S,s.input.amount,c)),h(s);let A={...i.tx};U(A,s),u.push(A);let k=await e.preview(u,a);return h(s),{txs:u,preview:k,summary:`${A.description} ${k.summary}`}}catch(i){throw new o(e.plainError(i))}}};return m}function se(e){let t={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"};return[{name:"kyberswap_quote",inputSchema:{type:"object",additionalProperties:!1,required:["from","to","amountIn"],properties:{from:t,to:t,amountIn:{type:"string",pattern:"^[0-9]+$"},slippageBps:{type:"integer",minimum:0,maximum:9999}}},execute:(n,m)=>e.quote({from:n.from,to:n.to,amountIn:n.amountIn,...n.slippageBps!==void 0?{slippageBps:n.slippageBps}:{}},m)},{name:"kyberswap_swap",inputSchema:{type:"object",additionalProperties:!1,required:["quoteId"],properties:{quoteId:{type:"string",minLength:1}}},execute:(n,m)=>e.build(n.quoteId,m)}]}function ue(e){let t=ie(e);return{name:"kyberswap",tools:se(t),swapProvider:t}}var Se=e=>({tools:ue(e).tools});export{ue as createModule,Se as createModulePart,ie as createSwapProvider};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as A}from"../../../chunks/
|
|
1
|
+
import{c as A}from"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import{b as M}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/VBWJOG3N.js";import{a as y,d as v,j as L}from"../../../chunks/5BP72XOA.js";import{c as D}from"../../../chunks/7I6TXFXR.js";import{a as d,d as x}from"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";var b="https://api.rh.lighter.xyz",U={chainId:y,address:L,symbol:"USDG",decimals:v};function w(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function u(){throw new d("Lighter returned an unexpected funding response.")}function I(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function _(e){return typeof e=="string"&&e.length>0&&e.length<=100&&e.trim()===e}function g(e,t){let r=e[t];return(!Array.isArray(r)||r.length===0||!r.every(w))&&u(),r}function T(e){let t=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(e);(!t||e.length>150)&&u();let r=t[3]??"",m=Number(t[4]??0),a=r.length-m;(!Number.isSafeInteger(m)||Math.abs(a)>250)&&u();let n=BigInt(`${t[1]}${t[2]}${r}`);return a<0?{coefficient:n*10n**BigInt(-a),decimals:0}:{coefficient:n,decimals:a}}function f(e,t,r=0){let m=e.coefficient*t;return`${m<0n?"-":""}${D((m<0n?-m:m).toString(),e.decimals+r)}`}function N(e){(typeof e!="number"||!Number.isFinite(e))&&u();let t=T(String(e));return{rate_1h_pct:f(t,125n,1),rate_8h_pct:f(t,100n),rate_annualized_pct:f(t,109500n),direction:e<0?"short":"long"}}function V(e){(typeof e.rate!="string"||!/^\d+(\.\d+)?$/.test(e.rate)||e.direction!=="long"&&e.direction!=="short")&&u();let t=T(e.rate),r=e.direction==="short"?-1n:1n;return{rate_1h_pct:f(t,r),rate_8h_pct:f(t,r*8n),rate_annualized_pct:f(t,r*8760n),direction:e.direction}}function P(e,t){let r,m;return async()=>r&&Date.now()<r.expires?r.value:(m||(m=e().then(a=>(r={value:a,expires:Date.now()+t},a)).finally(()=>{m=void 0})),m)}function q(e){if(!w(e)||Object.keys(e).some(t=>t!=="symbol"&&t!=="historyHours"))throw new d("Provide only a perpetual market symbol and optional historyHours.");if(e.symbol!==void 0&&(!_(e.symbol)||!e.symbol.trim()))throw new d("Provide a perpetual market symbol.");if(e.historyHours!==void 0&&(e.symbol===void 0||typeof e.historyHours!="number"||!Number.isInteger(e.historyHours)||e.historyHours<1||e.historyHours>168))throw new d("History requires a perpetual market symbol and 1 to 168 whole hours.");return{symbol:e.symbol?.toUpperCase(),historyHours:e.historyHours}}var E=e=>{async function t(a){return A(e.http,`${b}${a}`,{method:"GET",headers:{"user-agent":"oak-core/0.1.0"}},n=>w(n)&&n.code===200)}let r=P(async()=>{let a=await t("/api/v1/orderBookDetails?filter=perp"),n=new Set,c=new Set,o=[];for(let s of g(a,"order_book_details")){if(s.market_type==="spot"||typeof s.status=="string"&&s.status!=="active")continue;(s.market_type!=="perp"||s.status!=="active"||!I(s.market_id)||!_(s.symbol)||s.quote_asset_id!==void 0&&s.quote_asset_id!==0&&s.quote_asset_id!==3)&&u();let l=s.symbol.toUpperCase();(n.has(s.market_id)||c.has(l))&&u(),n.add(s.market_id),c.add(l),o.push({market_id:s.market_id,symbol:l})}if(!o.length)throw new d("Lighter returned no active perpetual markets.");return o},6e5),m=P(async()=>{let a=await t("/api/v1/funding-rates"),n=new Set,c=g(a,"funding_rates").filter(o=>o.exchange==="lighter").map(o=>((!I(o.market_id)||!_(o.symbol)||n.has(o.market_id))&&u(),n.add(o.market_id),{market_id:o.market_id,symbol:o.symbol.toUpperCase(),exchange:"lighter",...N(o.rate)}));if(!c.length)throw new d("Lighter returned no funding rates.");return{rates:c,observed_at:String(Math.floor(Date.now()/1e3))}},3e4);return{tools:[{name:"lighter_funding",inputSchema:{type:"object",additionalProperties:!1,properties:{symbol:{type:"string",minLength:1,maxLength:100,description:"Perpetual market ticker from the Lighter RH directory; omit for all current rates."},historyHours:{type:"integer",minimum:1,maximum:168,description:"Fetch hourly settled funding for the selected symbol over this many hours."}},dependentRequired:{historyHours:["symbol"]}},async execute(a){try{let n=q(a),c=await r(),o=n.symbol===void 0?void 0:c.find(i=>i.symbol===n.symbol);if(n.symbol!==void 0&&!o)throw new d("That active perpetual market is not available on Lighter RH.");let s=await m(),l=s.rates.filter(i=>!o||i.market_id===o.market_id);if(!l.length)throw new d("Lighter returned no funding rate for that perpetual market.");for(let i of l)c.some(R=>R.market_id===i.market_id&&R.symbol===i.symbol)||u();let k={venue:"lighter-rh",chainId:y,collateral:{...U},source:`${b}/api/v1/funding-rates`,observed_at:s.observed_at,timestamp_unit:"seconds",current_timestamp_kind:"observed_at",rate_unit:"percent",annualization:"simple, 365 days; indicative, not a forecast",rates:l.map(i=>({...i}))};if(n.historyHours===void 0||!o)return k;let p=Math.floor(Date.now()/1e3),h=p-n.historyHours*3600,$=new URLSearchParams({market_id:String(o.market_id),resolution:"1h",start_timestamp:String(h),end_timestamp:String(p),count_back:String(n.historyHours)}),S=await t(`/api/v1/fundings?${$}`);S.resolution!=="1h"&&u();let H=new Set,C=g(S,"fundings").map(i=>((typeof i.timestamp!="number"||!Number.isSafeInteger(i.timestamp)||i.timestamp%3600!==0||i.timestamp<h||i.timestamp>p||H.has(i.timestamp))&&u(),H.add(i.timestamp),{...o,exchange:"lighter",timestamp:String(i.timestamp),...V(i)}));return{...k,history:C,history_source:`${b}/api/v1/fundings`,start_timestamp:String(h),end_timestamp:String(p)}}catch(n){throw new d(x(n))}}}]}},O=e=>M("lighter",[E(e)]);export{O as createModule,E as createModulePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as N,o as M}from"../../../chunks/
|
|
1
|
+
import{b as N,o as M}from"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/74X7PXPR.js";import{b as I}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import{a as b}from"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import{a as l,i as $}from"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import{a as D}from"../../../chunks/7I6TXFXR.js";import{a as i}from"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";import{encodeFunctionData as k,getAddress as y,parseAbi as R}from"viem";var d=R(["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)"]),_=R(["function deposit() payable"]),g=$[l],H=(1n<<256n)-1n,A=[{key:"core",name:"Longbow Core USDG",vault:g.vaults.longbowCore.address,asset:g.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"frontier",name:"Longbow Frontier USDG",vault:g.vaults.longbowFrontier.address,asset:g.tokens.USDG.address,symbol:"USDG",decimals:6},{key:"eth",name:"Longbow ETH",vault:g.vaults.longbowEth.address,asset:g.tokens.WETH.address,symbol:"WETH",decimals:18}];function U(s,w){if(typeof s!="string")throw new i(`${w} must be a positive integer string in base units.`);let c=D(s);if(c===0n||c>H)throw new i(`${w} must be positive and within the uint256 range.`);return c}function f(s){if(typeof s!="bigint"||s<0n||s>H)throw new i("Longbow returned an invalid integer response.");return s}function F(s){if(typeof s!="string")throw new i("Provide the address of a current Longbow vault.");let w=A.find(c=>c.vault.toLowerCase()===s.toLowerCase());if(!w)throw new i("Provide the address of a current Longbow vault. Legacy vaults are not supported.");return w}function C(s,w){if(Object.keys(s).some(c=>!w.includes(c)))throw new i("Unsupported Longbow input. Use the fields in the tool schema.")}var j=s=>{async function w(t){try{return await t()}catch(e){throw new i(s.plainError(e))}}async function c(){let t=s.clientFor(l);if(await t.getChainId()!==l)throw new i("Longbow requires a client on chain 4663.");return t}async function v(t,e){let[a,r,o]=await Promise.all([t.readContract({address:e.vault,abi:d,functionName:"asset"}),t.readContract({address:e.vault,abi:d,functionName:"decimals"}),t.readContract({address:e.asset,abi:d,functionName:"decimals"})]);if(typeof a!="string"||a.toLowerCase()!==e.asset.toLowerCase())throw new i("Longbow vault asset does not match the recorded deployment.");if(r!==18||o!==e.decimals)throw new i("Longbow token decimals do not match the recorded deployment.");return{vault:e.vault,key:e.key,name:e.name,asset:{address:y(e.asset),symbol:e.symbol,decimals:o,chainId:l},share:{address:e.vault,symbol:`${e.key} shares`,decimals:r,chainId:l}}}async function E(t,e,a,r){let o=M(a.amount,N);if(BigInt(o)===0n)throw new i("The expected output is too small for a nonzero simulation minimum.");let n=await s.preview(t,e);if(n.changes.filter(m=>m.token.chainId===a.token.chainId&&m.token.address.toLowerCase()===a.token.address.toLowerCase()&&m.token.decimals===a.token.decimals).reduce((m,h)=>m+BigInt(h.amount),0n)<BigInt(o))throw new i("Longbow simulated output is below the expected minimum.");let u=n.changes.map(({token:m,amount:h})=>{let L=h.startsWith("-");return`${L?"-":"+"}${s.formatAmount(L?h.slice(1):h,m.decimals)} ${m.symbol} (${m.address}, chain ${m.chainId})`}).join("; ");return{txs:t,preview:n,expectedOutput:a,minimumOutput:{token:a.token,amount:o},minimumEnforcedOnchain:!1,summary:`${r} ${u}. Simulation only; no on-chain minimum is enforced by these ERC-4626 calls. ${n.summary}`}}async function W(t){C(t,[]);let e=await c();return Promise.all(A.map(async a=>{let[r,o,n,p]=await Promise.all([v(e,a),e.readContract({address:a.vault,abi:d,functionName:"totalAssets"}),e.readContract({address:a.vault,abi:d,functionName:"performanceFee"}),e.readContract({address:a.vault,abi:d,functionName:"managementFee"})]);return{...r,totalAssets:{token:r.asset,amount:f(o).toString()},fees:{performanceFeeE18:f(n).toString(),managementFeeE18:f(p).toString()},caveat:"Morpho V2 max views can be zero even when writes succeed. Simulate the requested action; listing does not prove availability."}}))}async function O(t,e){C(t,["vault","amount","wrapEth"]),b(e);let a=F(t.vault),r=U(t.amount,"Deposit amount");if(t.wrapEth!==void 0&&typeof t.wrapEth!="boolean")throw new i("wrapEth must be a boolean.");if(t.wrapEth&&a.asset.toLowerCase()!==g.tokens.WETH.address.toLowerCase())throw new i("Only a WETH vault accepts explicit ETH wrapping.");let o=await c(),n=await v(o,a),p=f(await o.readContract({address:n.vault,abi:d,functionName:"previewDeposit",args:[r]})),u=[];return t.wrapEth&&u.push(s.unsignedTx({to:n.asset.address,data:k({abi:_,functionName:"deposit"}),value:r.toString(),chainId:l,description:`Wrap ${s.formatAmount(r.toString(),18)} ETH into WETH for ${n.name}.`})),u.push(s.approval(n.asset.address,n.vault,r.toString(),l)),u.push(s.unsignedTx({to:n.vault,data:k({abi:d,functionName:"deposit",args:[r,y(e)]}),value:"0",chainId:l,description:`Deposit ${s.formatAmount(r.toString(),n.asset.decimals)} ${n.asset.symbol} into ${n.name}.`})),E(u,e,{token:n.share,amount:p.toString()},`Deposit into ${n.name}.`)}async function G(t,e){C(t,["vault","shares"]),b(e);let a=F(t.vault),r=t.shares==="all"?void 0:U(t.shares,"Redeem shares"),o=await c(),n=await v(o,a),p=f(await o.readContract({address:n.vault,abi:d,functionName:"balanceOf",args:[e]})),u=r??p;if(u===0n||u>p)throw new i("The wallet has insufficient Longbow shares for this redemption.");let m=f(await o.readContract({address:n.vault,abi:d,functionName:"previewRedeem",args:[u]})),h=[s.unsignedTx({to:n.vault,data:k({abi:d,functionName:"redeem",args:[u,y(e),y(e)]}),value:"0",chainId:l,description:`Redeem ${s.formatAmount(u.toString(),n.share.decimals)} shares from ${n.name} into ${n.asset.symbol}.`})];return E(h,e,{token:n.asset,amount:m.toString()},`Redeem from ${n.name}.`)}let P={type:"string",enum:A.map(t=>t.vault),description:"Current vault address on chain 4663."},S={type:"string",pattern:"^[0-9]+$",description:"Positive integer base units, never a human-unit decimal."},T=(t,e,a,r)=>({name:t,inputSchema:{type:"object",properties:e,required:a,additionalProperties:!1},execute:(o,n)=>w(()=>r(o,n))});return{tools:[T("longbow_list",{},[],W),T("longbow_deposit",{vault:P,amount:S,wrapEth:{type:"boolean",default:!1,description:"Explicitly wrap this amount of native ETH before depositing into the WETH vault."}},["vault","amount"],O),T("longbow_withdraw",{vault:P,shares:{anyOf:[S,{const:"all"}],description:"Share base units (18 decimals), or all for the fresh wallet share balance. Returns the underlying asset, including WETH."}},["vault","shares"],G)],positions:t=>w(async()=>{b(t);let e=await c();return(await Promise.all(A.map(async r=>{let o=await v(e,r),n=f(await e.readContract({address:o.vault,abi:d,functionName:"balanceOf",args:[t]}));if(n===0n)return[];let p=f(await e.readContract({address:o.vault,abi:d,functionName:"previewRedeem",args:[n]}));return[{module:"longbow",id:`${l}:${o.vault.toLowerCase()}`,chainId:l,assets:[{token:o.asset,amount:p.toString()}],description:`${o.name}: ${s.formatAmount(n.toString(),o.share.decimals)} shares (${o.share.address}, ${o.share.decimals} decimals). Underlying is a preview, not a guaranteed redemption.`}]}))).flat()})}};function Q(s){return I("longbow",[j(s)])}export{Q as createModule,j as createModulePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{a as o}from"../../../chunks/NDHEJGWR.js";import{b as t}from"../../../chunks/TFYLOWFO.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/74X7PXPR.js";import{b as r}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";var i=e=>r("meridian",[t(e),o(e)]);export{i as createModule};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"../../../chunks/
|
|
1
|
+
import{a,b}from"../../../chunks/TFYLOWFO.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{a as createMarketsPart,b as createModulePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../../../chunks/
|
|
1
|
+
import{a}from"../../../chunks/NDHEJGWR.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/74X7PXPR.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{a as createModulePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as v}from"../../../chunks/
|
|
1
|
+
import{c as v}from"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import{b as M}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import{a as g}from"../../../chunks/VBWJOG3N.js";import{a as c,i as A}from"../../../chunks/5BP72XOA.js";import{a as P}from"../../../chunks/7I6TXFXR.js";import{a as m}from"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";import{encodeAbiParameters as I,encodeFunctionData as S,keccak256 as T,parseAbi as E}from"viem";var h=A[c].merkl.distributor.address,k="Claim rewards on Merkl (Powered by Merkl \u2014 https://app.merkl.xyz)",x=`${k}. No claimable rewards on Robinhood Chain. Pending rewards must settle into a Merkle root before they can be claimed.`,b=E(["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 w(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function C(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{64}$/.test(r)}function y(){throw new m("Merkl returned an unexpected response. Please refetch rewards.")}function $(r){typeof r!="string"&&y();let a=P(r);if(a>=1n<<256n)throw new m("The Merkl reward amount exceeds the uint256 range.");return a.toString()}function N(r){let a=[],p=new Set;for(let s of r)if((!w(s)||!w(s.chain)||!Number.isSafeInteger(s.chain.id))&&y(),s.chain.id===c){Array.isArray(s.rewards)||y();for(let e of s.rewards){if((!w(e)||typeof e.distributionLayer!="string"||!w(e.token))&&y(),e.distributionLayer!=="TREE"||(Number.isSafeInteger(e.token.chainId)||y(),e.token.chainId!==c)||(Array.isArray(e.proofs)||y(),!e.proofs.length))continue;(!e.proofs.every(C)||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)&&y(),g(e.token.address);let t=$(e.amount),n=$(e.pending);if(BigInt(t)===0n)continue;let o=e.token.address.toLowerCase();if(p.has(o))throw new m("Merkl returned duplicate token leaves. Please refetch rewards.");p.add(o),a.push({token:{address:e.token.address,chainId:c,decimals:e.token.decimals,symbol:e.token.symbol},amount:t,pending:n,proofs:e.proofs})}}return a}function j(r,a,p){let s=T(I([{type:"address"},{type:"address"},{type:"uint256"}],[r,a.token.address,BigInt(a.amount)]));for(let e of a.proofs){let t=BigInt(s)<BigInt(e)?[s,e]:[e,s];s=T(I([{type:"bytes32"},{type:"bytes32"}],t))}if(s.toLowerCase()!==p.toLowerCase())throw new m("The Merkl proof does not match the active root. Please refetch rewards.")}function R(r){if(!w(r)||Object.keys(r).length)throw new m("This Merkl tool takes no arguments and uses the connected wallet.")}var B=r=>{async function a(t){try{return await t()}catch(n){throw new m(r.plainError(n))}}function p(t){let n=t.amount.startsWith("-"),o=n?t.amount.slice(1):t.amount;return`${n?"-":""}${r.formatAmount(o,t.token.decimals)} ${t.token.symbol} (${t.token.address}, chain ${t.token.chainId}, ${t.token.decimals} decimals)`}async function s(t){g(t);let n=await v(r.http,`https://api.merkl.xyz/v4/users/${t}/rewards/summary?chainId=${c}`,{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},l=>Array.isArray(l)),o=N(n);if(!o.length)return[];let i=r.clientFor(c),d=[];for(let l of o){let f=await i.readContract({address:h,abi:b,functionName:"claimed",args:[t,l.token.address]});if(!Array.isArray(f)||typeof f[0]!="bigint"||f[0]<0n||f[0]>=1n<<208n)throw new m("The Merkl claimed balance could not be read. Please try again.");BigInt(l.amount)<=f[0]||d.push({...l,claimed:f[0].toString(),claimable:(BigInt(l.amount)-f[0]).toString()})}if(!d.length)return[];let u=await i.readContract({address:h,abi:b,functionName:"getMerkleRoot"});if(!C(u))throw new m("The active Merkl root could not be read. Please try again.");for(let l of d)j(t,l,u);return d}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)=>a(async()=>{R(t);let o=await s(n);return{rewards:o.map(({proofs:i,...d})=>d),summary:o.length?`${k}. Claimable reward leaves: ${o.map(i=>p({token:i.token,amount:i.claimable})).join("; ")}. Wrapped leaves may transfer underlying tokens; claim preview shows the received assets. Pending rewards are excluded.`:x}})},{name:"merkl_claim",description:k,inputSchema:{type:"object",properties:{},additionalProperties:!1,description:k},execute:(t,n)=>a(async()=>{R(t);let o=await s(n);if(!o.length)return{txs:[],summary:x};let i=[r.unsignedTx({to:h,chainId:c,value:"0",description:k,data:S({abi:b,functionName:"claim",args:[o.map(()=>n),o.map(u=>u.token.address),o.map(u=>BigInt(u.amount)),o.map(u=>u.proofs)]})})],d=await r.preview(i,n);return{txs:i,summary:`${k}. Prepared unsigned claim. Expected wallet changes: ${d.changes.length?d.changes.map(p).join("; "):"no token transfers in simulation"}. ${d.summary}`}})}],positions:t=>a(async()=>(await s(t)).map(n=>({module:"merkl",id:`${c}:${n.token.address.toLowerCase()}`,chainId:c,assets:[{token:n.token,amount:n.claimable}],description:`${k}. Unclaimed reward leaf; wrapped rewards may transfer underlying assets. Pending rewards are excluded.`})))}},_=r=>M("merkl",[B(r)]);export{_ as createModule,B as createModulePart};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as de,c as ue,d as me}from"../../../chunks/KFMNCJXJ.js";import"../../../chunks/6YU3JLQQ.js";import"../../../chunks/D45AODDL.js";import"../../../chunks/24JYIH53.js";import{e as ce,f as I}from"../../../chunks/VBV366XQ.js";import{a as le}from"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import{b as ie}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import{a as D}from"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import{a as u,i as N}from"../../../chunks/25EOXUBI.js";import{a as H}from"../../../chunks/B5RZYFQC.js";import{a as d,c as se}from"../../../chunks/T5E4OJEU.js";import{a as oe}from"../../../chunks/XN4WDN3O.js";import{decodeAbiParameters as _,encodeAbiParameters as Te,encodeFunctionData as T,erc20Abi as re,getAddress as b,isAddress as he,keccak256 as Pe,parseAbi as z,parseAbiParameters as $}from"viem";var we="morpho",Me="https://api.morpho.org/graphql",v=b(N[u].morpho.morpho_blue.address),ve=b(N[u].morpho.adaptive_curve_irm.address),Ce=b(N[u].morpho.USDG.address),V=b(N[u].morpho.WETH.address),ne=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],U=120n,K=1000000n,Q=1n,L=10n**18n,Be=10n**36n,fe=(1n<<128n)-1n,xe=(1n<<256n)-1n,E=z(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)"]),$e=z(["function price() view returns (uint256)"]),Ie=z(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_e=z(["function deposit() payable"]);function j(e,t){return e===0n?0n:(e+t-1n)/t}function rt(e,t,o){return e*(o+K)/(t+Q)}function Oe(e,t,o){return j(e*(o+K),t+Q)}function ke(e,t,o){return e*(t+Q)/(o+K)}function q(e,t,o){return j(e*(t+Q),o+K)}function X(e,t,o){return e*t/Be*o/L}function Re(e,t,o){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),o)}`:e.formatAmount(t,o)}function J(e,t){let o=[],r={};for(let i of t.changes){let a=Re(e,i.amount,i.token.decimals);o.push({token:i.token,amount:i.amount,formattedAmount:a}),r[i.token.address.toLowerCase()]=a}return{formattedChanges:o,formattedNetOutflows:r}}function Ee(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new d("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function ye(e){if(!e||typeof e!="object")throw new d("Morpho marketParams must be an object.");for(let n of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof n!="string"||!he(n,{strict:!1}))throw new d("Morpho marketParams contains an invalid address.");let t=b(e.loanToken),o=b(e.collateralToken),r=b(e.oracle),i=b(e.irm),a=typeof e.lltv=="bigint"?e.lltv:H(String(e.lltv));if(t===I||o===I||r===I)throw new d("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(a<=0n||a>=L)throw new d("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:o,oracle:r,irm:i,lltv:a}}function pe(e){let t=ye(e),o=Te($("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return Pe(o)}function ae(e){let t=e.toLowerCase();return t===le.toLowerCase()||t===ce.toLowerCase()||t===I.toLowerCase()}function Y(e,t){let o=t??e.wallet;if(!o)throw new d("Provide a valid wallet address.");return D(o),b(o)}async function O(e,t,o){if(typeof e.call=="function"){let r=await e.call({to:t,data:o});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:o},"latest"]});if(typeof r=="string")return r}throw new d(`Unable to execute eth_call on contract ${t}.`)}async function R(e,t,o=u){if(D(t),ae(t))return{...de,chainId:o};let r=b(t),i=r.toLowerCase();if(o===u){if(i===Ce.toLowerCase())return ue;if(i===V.toLowerCase())return me}let[a,n]=await Promise.all([O(e,r,T({abi:re,functionName:"symbol"})),O(e,r,T({abi:re,functionName:"decimals"}))]),[s]=_($("string"),a),[l]=_($("uint8"),n);return{address:r,symbol:s,decimals:Number(l),chainId:o}}async function be(e,t){let o=await O(e,v,T({abi:E,functionName:"idToMarketParams",args:[t]})),[r,i,a,n,s]=_($("address, address, address, address, uint256"),o);return{loanToken:b(r),collateralToken:b(i),oracle:b(a),irm:b(n),lltv:s}}async function Se(e,t){let o=await O(e,v,T({abi:E,functionName:"market",args:[t]})),[r,i,a,n,s,l]=_($("uint128, uint128, uint128, uint128, uint128, uint128"),o);return{totalSupplyAssets:r,totalSupplyShares:i,totalBorrowAssets:a,totalBorrowShares:n,lastUpdate:s,fee:l}}async function W(e,t,o){let r=await O(e,v,T({abi:E,functionName:"position",args:[t,b(o)]})),[i,a,n]=_($("uint256, uint128, uint128"),r);return{supplyShares:i,borrowShares:a,collateral:n}}async function Z(e,t){let o=await O(e,b(t),T({abi:$e,functionName:"price"})),[r]=_($("uint256"),o);return r}async function Le(e,t,o){if(t.irm===I)return 0n;let r=await O(e,b(t.irm),T({abi:Ie,functionName:"borrowRateView",args:[t,o]})),[i]=_($("uint256"),r);return i}function Ne(e,t,o){let r=o>e.lastUpdate?o-e.lastUpdate:0n,i=t*r,a=j(i*i,2n*L),n=j(a*i,3n*L);return e.totalBorrowAssets+j(e.totalBorrowAssets*(i+a+n),L)}async function F(e,t,o,r=0n){let[i,a]=await Promise.all([e.getBlock({blockTag:"latest"}),Le(e,t,o)]),n=BigInt(Math.ceil(Date.now()/1e3)),s=(i.timestamp>n?i.timestamp:n)+r;return{totalBorrowAssets:Ne(o,a,s),accruedThrough:s,rate:a}}async function He(e,t,o){let r=await O(e,b(t),T({abi:re,functionName:"balanceOf",args:[b(o)]})),[i]=_($("uint256"),r);return i}async function G(e,t,o=!1){let r=t.marketId,i=t.marketParams;if(!r&&!i)throw new d("Provide either marketId or marketParams for the Morpho Blue market.");let a=i?ye(i):void 0,n=a?pe(a):void 0,s=r!==void 0?Ee(r):void 0;if(s&&n&&s!==n.toLowerCase())throw new d(`MarketParams tuple hash (${n}) does not match marketId (${s}).`);let l=s??n;if(o&&!ne.includes(l))throw new d("Morpho actions require a known market with a pinned oracle.");let[c,p]=await Promise.all([be(e,l),Se(e,l)]);if(c.loanToken===I||c.collateralToken===I||c.lltv===0n||p.lastUpdate===0n)throw new d(`Morpho market ${l} is not initialized on chain ${u}.`);let m=pe(c);if(m.toLowerCase()!==l.toLowerCase())throw new d(`On-chain idToMarketParams tuple hash (${m}) does not match marketId (${l}).`);if(a&&!(a.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&a.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&a.oracle.toLowerCase()===c.oracle.toLowerCase()&&a.irm.toLowerCase()===c.irm.toLowerCase()&&a.lltv===c.lltv))throw new d(`Provided marketParams tuple does not match on-chain idToMarketParams for ${l}.`);return{marketId:l,marketParams:c,marketState:p}}function ee(e){if(e.assets!==void 0&&e.amount!==void 0)throw new d("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new d("Provide an amount as a base-unit integer string.");let o=H(t);if(o<=0n||o>fe)throw new d("Asset amount must be greater than zero and fit in uint128.");return o}function te(e,t){for(let o of["onBehalf","receiver"])if(e[o]!==void 0&&(typeof e[o]!="string"||e[o].toLowerCase()!==t.toLowerCase()))throw new d(`Morpho ${o} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new d("Morpho callback data must be empty (0x).")}async function De(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=e.clientFor(u),{marketId:n,marketParams:s}=await G(a,t,!0),l=await R(a,s.collateralToken,u),c=s.collateralToken.toLowerCase()===V.toLowerCase(),p=typeof t.collateralToken=="string"?(D(t.collateralToken),b(t.collateralToken)):void 0,m=!!t.wrapNative||p!==void 0&&ae(p);if(p&&!ae(p)&&p.toLowerCase()!==s.collateralToken.toLowerCase())throw new d(`Collateral token ${p} does not match market collateral ${s.collateralToken}.`);if(m&&!c)throw new d("Native ETH wrapping is only supported when market collateralToken is WETH.");let h=ee(t),f=h.toString(),w=e.formatAmount(f,l.decimals),k=[];m&&k.push(e.unsignedTx({chainId:u,to:V,data:T({abi:_e,functionName:"deposit"}),value:f,description:`Wrap ${w} ETH into WETH at ${V}.`})),k.push(e.approval(s.collateralToken,v,f,u)),k.push(e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"supplyCollateral",args:[s,h,i,"0x"]}),value:"0",description:`Supply ${w} ${l.symbol} (${f} base units) collateral to Morpho market ${n}.`}));let S=await e.preview(k,r),{formattedChanges:y,formattedNetOutflows:g}=J(e,S);return{action:"morpho_supply_collateral",chainId:u,marketId:n,marketParams:{loanToken:s.loanToken,collateralToken:s.collateralToken,oracle:s.oracle,irm:s.irm,lltv:s.lltv.toString()},collateralToken:l,assets:f,formattedAssets:w,onBehalf:i,txs:k,steps:k,summary:`${m?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${l.symbol} collateral to Morpho Blue market ${n}.`,preview:S,formattedChanges:y,formattedNetOutflows:g}}async function Ue(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=r,n=e.clientFor(u),{marketId:s,marketParams:l,marketState:c}=await G(n,t,!0),[p,m,h,f]=await Promise.all([R(n,l.loanToken,u),W(n,s,i),Z(n,l.oracle),F(n,l,c,U)]),w=ee(t),k=w.toString(),S=e.formatAmount(k,p.decimals),y=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(w>y)throw new d(`Insufficient market liquidity: requested ${k} base units, available ${y.toString()} base units.`);let g=X(m.collateral,h,l.lltv),C=q(m.borrowShares,f.totalBorrowAssets,c.totalBorrowShares);if(m.collateral===0n||C+w>g)throw new d(`Insufficient collateral or unhealthy borrow: total debt ${(C+w).toString()} exceeds max borrow ${g.toString()} base units.`);let P=Oe(w,f.totalBorrowAssets,c.totalBorrowShares),x=[e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"borrow",args:[l,w,0n,i,a]}),value:"0",description:`Borrow ${S} ${p.symbol} (${k} base units) from Morpho market ${s}.`})],M=await e.preview(x,r),{formattedChanges:A,formattedNetOutflows:Ae}=J(e,M);return{action:"morpho_borrow",chainId:u,marketId:s,marketParams:{loanToken:l.loanToken,collateralToken:l.collateralToken,oracle:l.oracle,irm:l.irm,lltv:l.lltv.toString()},loanToken:p,assets:k,formattedAssets:S,borrowShares:P.toString(),onBehalf:i,receiver:a,txs:x,steps:x,summary:`Borrow ${S} ${p.symbol} from Morpho Blue market ${s}.`,preview:M,formattedChanges:A,formattedNetOutflows:Ae}}async function je(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=e.clientFor(u);if(t.shares!==void 0){let A=H(t.shares);if(A<=0n||A===xe||A>fe)throw new d("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(t.repayAll===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new d("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new d("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:n,marketParams:s,marketState:l}=await G(a,t,!0),[c,p,m]=await Promise.all([R(a,s.loanToken,u),W(a,n,i),He(a,s.loanToken,r)]);if(p.borrowShares===0n)throw new d(`Position has no active borrow debt on Morpho market ${n}.`);let h=0n,f=0n;if(t.repayAll===!0)f=p.borrowShares;else if(t.shares!==void 0){let A=H(t.shares);if(A>p.borrowShares)throw new d(`Repay shares (${A.toString()}) exceed current position borrowShares (${p.borrowShares.toString()}).`);f=A}else h=ee(t);let w=f>0n?await F(a,s,l,U):void 0,k=f>0n?q(f,w.totalBorrowAssets,l.totalBorrowShares):h;if(m<k)throw new d(`Insufficient loan token balance for repayment: wallet holds ${m.toString()} base units, but ${k.toString()} base units are required (including accrued interest).`);let S=k.toString(),y=e.formatAmount(S,c.decimals),g=e.approval(s.loanToken,v,S,u),C=e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"repay",args:[s,h,f,i,"0x"]}),value:"0",description:f>0n?`Repay ${f.toString()} borrow shares (${y} ${c.symbol}) on Morpho market ${n}.`:`Repay ${y} ${c.symbol} (${h.toString()} base units) on Morpho market ${n}.`}),P=[g,C],B=await e.preview(P,r),{formattedChanges:x,formattedNetOutflows:M}=J(e,B);return{action:"morpho_repay",chainId:u,marketId:n,marketParams:{loanToken:s.loanToken,collateralToken:s.collateralToken,oracle:s.oracle,irm:s.irm,lltv:s.lltv.toString()},loanToken:c,repayAssets:h.toString(),repayShares:f.toString(),requiredAssets:S,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:U.toString()}:{},formattedRequiredAssets:y,onBehalf:i,txs:P,steps:P,summary:f>0n?`Repay ${f.toString()} borrow shares (approval up to ${y} ${c.symbol}) on Morpho Blue market ${n}. Refresh if signing/inclusion takes more than ${U} seconds.`:`Repay ${y} ${c.symbol} on Morpho Blue market ${n}.`,preview:B,formattedChanges:x,formattedNetOutflows:M}}async function qe(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=r,n=e.clientFor(u),{marketId:s,marketParams:l,marketState:c}=await G(n,t,!0),[p,m,h,f]=await Promise.all([R(n,l.collateralToken,u),W(n,s,i),Z(n,l.oracle),F(n,l,c,U)]),w=t.withdrawAll===!0?m.collateral:ee(t);if(w<=0n||w>m.collateral)throw new d(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${m.collateral.toString()} base units.`);if(m.borrowShares>0n){let x=m.collateral-w,M=X(x,h,l.lltv),A=q(m.borrowShares,f.totalBorrowAssets,c.totalBorrowShares);if(A>M)throw new d(`Unhealthy collateral withdrawal: remaining max borrow ${M.toString()} would fall below current debt ${A.toString()} base units.`)}let k=w.toString(),S=e.formatAmount(k,p.decimals),g=[e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"withdrawCollateral",args:[l,w,i,a]}),value:"0",description:`Withdraw ${S} ${p.symbol} (${k} base units) collateral from Morpho market ${s}.`})],C=await e.preview(g,r),{formattedChanges:P,formattedNetOutflows:B}=J(e,C);return{action:"morpho_withdraw_collateral",chainId:u,marketId:s,marketParams:{loanToken:l.loanToken,collateralToken:l.collateralToken,oracle:l.oracle,irm:l.irm,lltv:l.lltv.toString()},collateralToken:p,assets:k,formattedAssets:S,onBehalf:i,receiver:a,txs:g,steps:g,summary:`Withdraw ${S} ${p.symbol} collateral from Morpho Blue market ${s}.`,preview:C,formattedChanges:P,formattedNetOutflows:B}}async function We(e,t){let o=`query Markets($chainId: Int!) {
|
|
1
|
+
import{b as de,c as ue,d as me}from"../../../chunks/SXBGOGYQ.js";import"../../../chunks/UIJWIFGV.js";import"../../../chunks/B2LA6VVF.js";import"../../../chunks/NNJLMS7F.js";import{e as ce,f as I}from"../../../chunks/XEN45QST.js";import{a as le}from"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import{b as ie}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import{a as D}from"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import{a as u,i as N}from"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import{a as H}from"../../../chunks/7I6TXFXR.js";import{a as d,d as se}from"../../../chunks/Z3FZWNAJ.js";import{a as oe}from"../../../chunks/XN4WDN3O.js";import{decodeAbiParameters as _,encodeAbiParameters as Te,encodeFunctionData as T,erc20Abi as re,getAddress as b,isAddress as he,keccak256 as Pe,parseAbi as z,parseAbiParameters as $}from"viem";var we="morpho",Me="https://api.morpho.org/graphql",v=b(N[u].morpho.morpho_blue.address),ve=b(N[u].morpho.adaptive_curve_irm.address),Ce=b(N[u].morpho.USDG.address),V=b(N[u].morpho.WETH.address),ne=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],U=120n,K=1000000n,Q=1n,L=10n**18n,Be=10n**36n,fe=(1n<<128n)-1n,xe=(1n<<256n)-1n,E=z(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)"]),$e=z(["function price() view returns (uint256)"]),Ie=z(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_e=z(["function deposit() payable"]);function j(e,t){return e===0n?0n:(e+t-1n)/t}function rt(e,t,o){return e*(o+K)/(t+Q)}function Oe(e,t,o){return j(e*(o+K),t+Q)}function ke(e,t,o){return e*(t+Q)/(o+K)}function q(e,t,o){return j(e*(t+Q),o+K)}function X(e,t,o){return e*t/Be*o/L}function Re(e,t,o){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),o)}`:e.formatAmount(t,o)}function J(e,t){let o=[],r={};for(let i of t.changes){let a=Re(e,i.amount,i.token.decimals);o.push({token:i.token,amount:i.amount,formattedAmount:a}),r[i.token.address.toLowerCase()]=a}return{formattedChanges:o,formattedNetOutflows:r}}function Ee(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new d("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function ye(e){if(!e||typeof e!="object")throw new d("Morpho marketParams must be an object.");for(let n of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof n!="string"||!he(n,{strict:!1}))throw new d("Morpho marketParams contains an invalid address.");let t=b(e.loanToken),o=b(e.collateralToken),r=b(e.oracle),i=b(e.irm),a=typeof e.lltv=="bigint"?e.lltv:H(String(e.lltv));if(t===I||o===I||r===I)throw new d("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(a<=0n||a>=L)throw new d("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:o,oracle:r,irm:i,lltv:a}}function pe(e){let t=ye(e),o=Te($("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return Pe(o)}function ae(e){let t=e.toLowerCase();return t===le.toLowerCase()||t===ce.toLowerCase()||t===I.toLowerCase()}function Y(e,t){let o=t??e.wallet;if(!o)throw new d("Provide a valid wallet address.");return D(o),b(o)}async function O(e,t,o){if(typeof e.call=="function"){let r=await e.call({to:t,data:o});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:o},"latest"]});if(typeof r=="string")return r}throw new d(`Unable to execute eth_call on contract ${t}.`)}async function R(e,t,o=u){if(D(t),ae(t))return{...de,chainId:o};let r=b(t),i=r.toLowerCase();if(o===u){if(i===Ce.toLowerCase())return ue;if(i===V.toLowerCase())return me}let[a,n]=await Promise.all([O(e,r,T({abi:re,functionName:"symbol"})),O(e,r,T({abi:re,functionName:"decimals"}))]),[s]=_($("string"),a),[l]=_($("uint8"),n);return{address:r,symbol:s,decimals:Number(l),chainId:o}}async function be(e,t){let o=await O(e,v,T({abi:E,functionName:"idToMarketParams",args:[t]})),[r,i,a,n,s]=_($("address, address, address, address, uint256"),o);return{loanToken:b(r),collateralToken:b(i),oracle:b(a),irm:b(n),lltv:s}}async function Se(e,t){let o=await O(e,v,T({abi:E,functionName:"market",args:[t]})),[r,i,a,n,s,l]=_($("uint128, uint128, uint128, uint128, uint128, uint128"),o);return{totalSupplyAssets:r,totalSupplyShares:i,totalBorrowAssets:a,totalBorrowShares:n,lastUpdate:s,fee:l}}async function W(e,t,o){let r=await O(e,v,T({abi:E,functionName:"position",args:[t,b(o)]})),[i,a,n]=_($("uint256, uint128, uint128"),r);return{supplyShares:i,borrowShares:a,collateral:n}}async function Z(e,t){let o=await O(e,b(t),T({abi:$e,functionName:"price"})),[r]=_($("uint256"),o);return r}async function Le(e,t,o){if(t.irm===I)return 0n;let r=await O(e,b(t.irm),T({abi:Ie,functionName:"borrowRateView",args:[t,o]})),[i]=_($("uint256"),r);return i}function Ne(e,t,o){let r=o>e.lastUpdate?o-e.lastUpdate:0n,i=t*r,a=j(i*i,2n*L),n=j(a*i,3n*L);return e.totalBorrowAssets+j(e.totalBorrowAssets*(i+a+n),L)}async function F(e,t,o,r=0n){let[i,a]=await Promise.all([e.getBlock({blockTag:"latest"}),Le(e,t,o)]),n=BigInt(Math.ceil(Date.now()/1e3)),s=(i.timestamp>n?i.timestamp:n)+r;return{totalBorrowAssets:Ne(o,a,s),accruedThrough:s,rate:a}}async function He(e,t,o){let r=await O(e,b(t),T({abi:re,functionName:"balanceOf",args:[b(o)]})),[i]=_($("uint256"),r);return i}async function G(e,t,o=!1){let r=t.marketId,i=t.marketParams;if(!r&&!i)throw new d("Provide either marketId or marketParams for the Morpho Blue market.");let a=i?ye(i):void 0,n=a?pe(a):void 0,s=r!==void 0?Ee(r):void 0;if(s&&n&&s!==n.toLowerCase())throw new d(`MarketParams tuple hash (${n}) does not match marketId (${s}).`);let l=s??n;if(o&&!ne.includes(l))throw new d("Morpho actions require a known market with a pinned oracle.");let[c,p]=await Promise.all([be(e,l),Se(e,l)]);if(c.loanToken===I||c.collateralToken===I||c.lltv===0n||p.lastUpdate===0n)throw new d(`Morpho market ${l} is not initialized on chain ${u}.`);let m=pe(c);if(m.toLowerCase()!==l.toLowerCase())throw new d(`On-chain idToMarketParams tuple hash (${m}) does not match marketId (${l}).`);if(a&&!(a.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&a.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&a.oracle.toLowerCase()===c.oracle.toLowerCase()&&a.irm.toLowerCase()===c.irm.toLowerCase()&&a.lltv===c.lltv))throw new d(`Provided marketParams tuple does not match on-chain idToMarketParams for ${l}.`);return{marketId:l,marketParams:c,marketState:p}}function ee(e){if(e.assets!==void 0&&e.amount!==void 0)throw new d("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new d("Provide an amount as a base-unit integer string.");let o=H(t);if(o<=0n||o>fe)throw new d("Asset amount must be greater than zero and fit in uint128.");return o}function te(e,t){for(let o of["onBehalf","receiver"])if(e[o]!==void 0&&(typeof e[o]!="string"||e[o].toLowerCase()!==t.toLowerCase()))throw new d(`Morpho ${o} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new d("Morpho callback data must be empty (0x).")}async function De(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=e.clientFor(u),{marketId:n,marketParams:s}=await G(a,t,!0),l=await R(a,s.collateralToken,u),c=s.collateralToken.toLowerCase()===V.toLowerCase(),p=typeof t.collateralToken=="string"?(D(t.collateralToken),b(t.collateralToken)):void 0,m=!!t.wrapNative||p!==void 0&&ae(p);if(p&&!ae(p)&&p.toLowerCase()!==s.collateralToken.toLowerCase())throw new d(`Collateral token ${p} does not match market collateral ${s.collateralToken}.`);if(m&&!c)throw new d("Native ETH wrapping is only supported when market collateralToken is WETH.");let h=ee(t),f=h.toString(),w=e.formatAmount(f,l.decimals),k=[];m&&k.push(e.unsignedTx({chainId:u,to:V,data:T({abi:_e,functionName:"deposit"}),value:f,description:`Wrap ${w} ETH into WETH at ${V}.`})),k.push(e.approval(s.collateralToken,v,f,u)),k.push(e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"supplyCollateral",args:[s,h,i,"0x"]}),value:"0",description:`Supply ${w} ${l.symbol} (${f} base units) collateral to Morpho market ${n}.`}));let S=await e.preview(k,r),{formattedChanges:y,formattedNetOutflows:g}=J(e,S);return{action:"morpho_supply_collateral",chainId:u,marketId:n,marketParams:{loanToken:s.loanToken,collateralToken:s.collateralToken,oracle:s.oracle,irm:s.irm,lltv:s.lltv.toString()},collateralToken:l,assets:f,formattedAssets:w,onBehalf:i,txs:k,steps:k,summary:`${m?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${l.symbol} collateral to Morpho Blue market ${n}.`,preview:S,formattedChanges:y,formattedNetOutflows:g}}async function Ue(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=r,n=e.clientFor(u),{marketId:s,marketParams:l,marketState:c}=await G(n,t,!0),[p,m,h,f]=await Promise.all([R(n,l.loanToken,u),W(n,s,i),Z(n,l.oracle),F(n,l,c,U)]),w=ee(t),k=w.toString(),S=e.formatAmount(k,p.decimals),y=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(w>y)throw new d(`Insufficient market liquidity: requested ${k} base units, available ${y.toString()} base units.`);let g=X(m.collateral,h,l.lltv),C=q(m.borrowShares,f.totalBorrowAssets,c.totalBorrowShares);if(m.collateral===0n||C+w>g)throw new d(`Insufficient collateral or unhealthy borrow: total debt ${(C+w).toString()} exceeds max borrow ${g.toString()} base units.`);let P=Oe(w,f.totalBorrowAssets,c.totalBorrowShares),x=[e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"borrow",args:[l,w,0n,i,a]}),value:"0",description:`Borrow ${S} ${p.symbol} (${k} base units) from Morpho market ${s}.`})],M=await e.preview(x,r),{formattedChanges:A,formattedNetOutflows:Ae}=J(e,M);return{action:"morpho_borrow",chainId:u,marketId:s,marketParams:{loanToken:l.loanToken,collateralToken:l.collateralToken,oracle:l.oracle,irm:l.irm,lltv:l.lltv.toString()},loanToken:p,assets:k,formattedAssets:S,borrowShares:P.toString(),onBehalf:i,receiver:a,txs:x,steps:x,summary:`Borrow ${S} ${p.symbol} from Morpho Blue market ${s}.`,preview:M,formattedChanges:A,formattedNetOutflows:Ae}}async function je(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=e.clientFor(u);if(t.shares!==void 0){let A=H(t.shares);if(A<=0n||A===xe||A>fe)throw new d("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(t.repayAll===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new d("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new d("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:n,marketParams:s,marketState:l}=await G(a,t,!0),[c,p,m]=await Promise.all([R(a,s.loanToken,u),W(a,n,i),He(a,s.loanToken,r)]);if(p.borrowShares===0n)throw new d(`Position has no active borrow debt on Morpho market ${n}.`);let h=0n,f=0n;if(t.repayAll===!0)f=p.borrowShares;else if(t.shares!==void 0){let A=H(t.shares);if(A>p.borrowShares)throw new d(`Repay shares (${A.toString()}) exceed current position borrowShares (${p.borrowShares.toString()}).`);f=A}else h=ee(t);let w=f>0n?await F(a,s,l,U):void 0,k=f>0n?q(f,w.totalBorrowAssets,l.totalBorrowShares):h;if(m<k)throw new d(`Insufficient loan token balance for repayment: wallet holds ${m.toString()} base units, but ${k.toString()} base units are required (including accrued interest).`);let S=k.toString(),y=e.formatAmount(S,c.decimals),g=e.approval(s.loanToken,v,S,u),C=e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"repay",args:[s,h,f,i,"0x"]}),value:"0",description:f>0n?`Repay ${f.toString()} borrow shares (${y} ${c.symbol}) on Morpho market ${n}.`:`Repay ${y} ${c.symbol} (${h.toString()} base units) on Morpho market ${n}.`}),P=[g,C],B=await e.preview(P,r),{formattedChanges:x,formattedNetOutflows:M}=J(e,B);return{action:"morpho_repay",chainId:u,marketId:n,marketParams:{loanToken:s.loanToken,collateralToken:s.collateralToken,oracle:s.oracle,irm:s.irm,lltv:s.lltv.toString()},loanToken:c,repayAssets:h.toString(),repayShares:f.toString(),requiredAssets:S,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:U.toString()}:{},formattedRequiredAssets:y,onBehalf:i,txs:P,steps:P,summary:f>0n?`Repay ${f.toString()} borrow shares (approval up to ${y} ${c.symbol}) on Morpho Blue market ${n}. Refresh if signing/inclusion takes more than ${U} seconds.`:`Repay ${y} ${c.symbol} on Morpho Blue market ${n}.`,preview:B,formattedChanges:x,formattedNetOutflows:M}}async function qe(e,t,o){let r=Y(t,o);te(t,r);let i=r,a=r,n=e.clientFor(u),{marketId:s,marketParams:l,marketState:c}=await G(n,t,!0),[p,m,h,f]=await Promise.all([R(n,l.collateralToken,u),W(n,s,i),Z(n,l.oracle),F(n,l,c,U)]),w=t.withdrawAll===!0?m.collateral:ee(t);if(w<=0n||w>m.collateral)throw new d(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${m.collateral.toString()} base units.`);if(m.borrowShares>0n){let x=m.collateral-w,M=X(x,h,l.lltv),A=q(m.borrowShares,f.totalBorrowAssets,c.totalBorrowShares);if(A>M)throw new d(`Unhealthy collateral withdrawal: remaining max borrow ${M.toString()} would fall below current debt ${A.toString()} base units.`)}let k=w.toString(),S=e.formatAmount(k,p.decimals),g=[e.unsignedTx({chainId:u,to:v,data:T({abi:E,functionName:"withdrawCollateral",args:[l,w,i,a]}),value:"0",description:`Withdraw ${S} ${p.symbol} (${k} base units) collateral from Morpho market ${s}.`})],C=await e.preview(g,r),{formattedChanges:P,formattedNetOutflows:B}=J(e,C);return{action:"morpho_withdraw_collateral",chainId:u,marketId:s,marketParams:{loanToken:l.loanToken,collateralToken:l.collateralToken,oracle:l.oracle,irm:l.irm,lltv:l.lltv.toString()},collateralToken:p,assets:k,formattedAssets:S,onBehalf:i,receiver:a,txs:g,steps:g,summary:`Withdraw ${S} ${p.symbol} collateral from Morpho Blue market ${s}.`,preview:C,formattedChanges:P,formattedNetOutflows:B}}async function We(e,t){let o=`query Markets($chainId: Int!) {
|
|
2
2
|
markets(first: 1000, where: { chainId_in: [$chainId] }) {
|
|
3
3
|
items {
|
|
4
4
|
marketId chain { id } lltv listed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b}from"../../../chunks/
|
|
1
|
+
import{b}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import{a as h}from"../../../chunks/VBWJOG3N.js";import{a,d as y,i as g}from"../../../chunks/5BP72XOA.js";import{a as C}from"../../../chunks/7I6TXFXR.js";import{a as d}from"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";import{encodeFunctionData as v,parseAbi as $}from"viem";var r=g[a].vaults.netnet.address,l={address:g[a].tokens.USDG.address,chainId:a,decimals:y,symbol:"USDG"},w={address:r,chainId:a,decimals:18,symbol:"nnUSDG"},u=$(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function balanceOf(address owner) view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),P={type:"string",pattern:"^[0-9]+$",description:"Positive USDG amount in integer base units (6 decimals)."},G="Preview amounts are estimates; these ERC-4626 calls have no on-chain minimum output argument. No transaction was sent.";function D(n){if(typeof n!="string")throw new d("Provide an integer amount string in base units.");let i=C(n);if(i<=0n||i>=1n<<256n)throw new d("Amount must be positive and fit in uint256.");return i}function N(n,i){if(Object.keys(n).some(f=>!i.includes(f)))throw new d("Unsupported NetNet argument.")}var T=n=>{async function i(e){try{return await e()}catch(t){throw new d(n.plainError(t))}}async function f(){let e=n.clientFor(a);if(await e.getChainId()!==a)throw new d("NetNet requires chain 4663.");let[t,s]=await Promise.all([e.readContract({address:r,abi:u,functionName:"asset"}),e.readContract({address:r,abi:u,functionName:"decimals"})]);if(t.toLowerCase()!==l.address.toLowerCase())throw new d("NetNet does not report the pinned USDG asset.");if(s!==w.decimals)throw new d("NetNet share decimals do not match the pinned metadata.");return e}async function S(e,t,s){let o=await n.preview(e,t),p=o.changes.map(({token:c,amount:m})=>{let A=m.startsWith("-");return`${A?"-":"+"}${n.formatAmount(A?m.slice(1):m,c.decimals)} ${c.symbol}`}).join(", ");return{txs:e,preview:o,summary:`${s} ${o.summary} ${p?`Estimated changes: ${p}. `:""}${G}`}}async function U(e){return i(async()=>{h(e);let t=await f(),s=await t.readContract({address:r,abi:u,functionName:"balanceOf",args:[e]});if(s===0n)return[];let o=await t.readContract({address:r,abi:u,functionName:"convertToAssets",args:[s]});return[{module:"netnet",id:`${a}:${r}`,chainId:a,assets:[{token:{...l},amount:o.toString()}],description:`${n.formatAmount(s.toString(),w.decimals)} nnUSDG shares in NetNet Credit (${r}); underlying USDG is an estimate, not a liquidity guarantee.`}]})}return{positions:U,tools:[{name:"netnet_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:e=>i(async()=>{N(e,[]);let s=await(await f()).readContract({address:r,abi:u,functionName:"totalAssets"});return[{address:r,name:"NetNet Credit",chainId:a,asset:{...l},shares:{...w},totalAssets:{token:{...l},amount:s.toString()}}]})},{name:"netnet_deposit",inputSchema:{type:"object",properties:{amount:P},required:["amount"],additionalProperties:!1},execute:(e,t)=>i(async()=>{N(e,["amount"]),h(t);let s=D(e.amount);await f();let o=[n.approval(l.address,r,s.toString(),a),n.unsignedTx({to:r,data:v({abi:u,functionName:"deposit",args:[s,t]}),value:"0",chainId:a,description:`Deposit ${n.formatAmount(s.toString(),l.decimals)} USDG into NetNet Credit.`})];return S(o,t,"Approve the exact USDG amount, then deposit into NetNet Credit.")})},{name:"netnet_withdraw",inputSchema:{type:"object",properties:{amount:{anyOf:[P,{const:"max",description:"Redeem the fresh full nnUSDG share balance."}]}},required:["amount"],additionalProperties:!1},execute:(e,t)=>i(async()=>{N(e,["amount"]),h(t);let s=e.amount==="max"?void 0:D(e.amount),o=await f(),p,c;if(s===void 0){let m=await o.readContract({address:r,abi:u,functionName:"balanceOf",args:[t]});if(m===0n)throw new d("This wallet has no NetNet shares to redeem.");p=v({abi:u,functionName:"redeem",args:[m,t,t]}),c=`Redeem all ${n.formatAmount(m.toString(),w.decimals)} nnUSDG shares for USDG.`}else p=v({abi:u,functionName:"withdraw",args:[s,t,t]}),c=`Withdraw ${n.formatAmount(s.toString(),l.decimals)} USDG from NetNet Credit (unmeasured on the recorded fork; full exit uses amount "max" redeem).`;return S([n.unsignedTx({to:r,data:p,value:"0",chainId:a,description:c})],t,c)})}]}};function R(n){return b("netnet",[T(n)])}export{R as createModule,T as createModulePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as G,o as U}from"../../../chunks/
|
|
1
|
+
import{b as G,o as U}from"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/74X7PXPR.js";import{b as j}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import{a as H}from"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import{a as l,d as q,i as E,j as D}from"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import{a as _}from"../../../chunks/7I6TXFXR.js";import{a as i}from"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";import{decodeEventLog as M,encodeFunctionData as tt,erc20Abi as R,pad as Q,parseAbi as W,toEventSelector as P,zeroAddress as et}from"viem";var $=E[l].orbio.credit.address,g=E[l].orbio.exchange.address,a={address:$,chainId:l,symbol:"CREDIT",decimals:6},O={address:D,chainId:l,symbol:"USDG",decimals:q},J=(1n<<256n)-1n,B=W(["function buyAndActivate(uint256 usdgIn, uint256 minCreditOut, bytes32 activationRef, uint256 maxFills) returns (uint256 creditOut, uint256 usdgSpent, uint256 activationId)","function getActivationQuote(uint256 usdgIn, uint256 maxFills) view returns (uint256 grossCredit, uint256 inputAmount, uint256 exchangeFee, uint256 fills, uint256 unknown, uint256 netActivated, uint256 activationFee)"]),k=W(["event Activated(uint256 indexed activationId, address indexed by, bytes32 indexed ref, uint256 amount)","event ActivationFeeCharged(uint256 indexed activationId, uint256 fee)"]),nt=P(k[0]),it=P(k[1]),ot=P("Transfer(address,address,uint256)"),K={status:"unverified",reason:"Off-chain spendable credit requires a separate service canary. An on-chain activation does not prove service credit."};function c(t,e){return{token:{...t},amount:e.toString()}}function z(t,e){if(typeof t!="string")throw new i(`${e} must be an integer string in base units.`);let o=_(t);if(o<=0n||o>J)throw new i(`${e} must be positive and fit uint256.`);return o}function L(t){if(typeof t!="bigint"||t<0n||t>J)throw new i("Orbio returned an invalid on-chain amount.");return t}function V(t,e){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(o=>!e.includes(o)))throw new i("Unsupported Orbio argument.")}function C(t,e){return t.toLowerCase()===e.toLowerCase()}async function X(t){let e=t.clientFor(l);if(await e.getChainId()!==l)throw new i(`Orbio requires chain ${l}.`);return e}async function at(t,e,o){V(e,["usdgIn","minCreditOut","maxFills"]),H(o);let d=z(e.usdgIn,"usdgIn"),u=e.maxFills===void 0?16:e.maxFills;if(typeof u!="number"||!Number.isInteger(u)||u<1||u>64)throw new i("maxFills must be an integer from 1 to 64.");let x=e.minCreditOut===void 0?void 0:z(e.minCreditOut,"minCreditOut"),I=await(await X(t)).readContract({address:g,abi:B,functionName:"getActivationQuote",args:[d,BigInt(u)]});if(!Array.isArray(I)||I.length!==7)throw new i("Orbio returned an invalid activation quote.");let[f,s,v,b,F,h,r]=I.map(L);if(f===0n||s!==d||b<1n||b>BigInt(u)||v>s||h===0n||h+r!==f)throw new i("Orbio returned an inconsistent activation quote.");let m=x??BigInt(U(f.toString(),G));if(m<=1n||m>f)throw new i("minCreditOut must exceed one base unit and be no greater than quoted gross CREDIT.");let T=Q(o.toLowerCase(),{size:32}),n=[t.approval(D,g,d.toString(),l),t.unsignedTx({to:g,chainId:l,value:"0",data:tt({abi:B,functionName:"buyAndActivate",args:[d,m,T,BigInt(u)]}),description:"Buy CREDIT and burn it for activation using the wallet reference."})],w=await t.preview(n,o),A=w.changes.map(p=>{let S=p.amount.startsWith("-"),Z=S?p.amount.slice(1):p.amount;return`${S?"-":""}${t.formatAmount(Z,p.token.decimals)} ${p.token.symbol} (${p.token.address}, chain ${p.token.chainId})`}).join("; "),y=(p,S)=>`${t.formatAmount(p.toString(),S.decimals)} ${S.symbol}`,Y=`Approve exactly ${y(d,O)} to Exchange, then buy and burn ${y(f,a)} (quoted). Gross minimum: ${y(m,a)}; exchange fee: ${y(v,O)}; activation fee: ${y(r,a)}; net activation: ${y(h,a)}. CREDIT is burned for activation, not transferred into the wallet. Off-chain spendable credit remains unverified. ${w.summary}${A?` Preview changes: ${A}.`:""}`;return{...{txs:n,summary:Y},preview:w,activationRef:T,spendableCredit:{...K},quote:{usdgIn:c(O,s),grossCredit:c(a,f),minCreditOut:c(a,m),exchangeFee:c(O,v),activationFee:c(a,r),netActivated:c(a,h),fills:b.toString(),unknownWord:F.toString()}}}async function rt(t,e,o){if(V(e,["transactionHash"]),H(o),e.transactionHash!==void 0&&(typeof e.transactionHash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.transactionHash)))throw new i("Provide a valid activation transaction hash.");let d=await X(t),[u,x]=await Promise.all([d.readContract({address:$,abi:R,functionName:"balanceOf",args:[o]}),d.readContract({address:$,abi:R,functionName:"totalSupply"})]),N=c(a,L(u)),I=c(a,L(x)),f={walletCredit:N,totalSupply:I,spendableCredit:{...K}};if(e.transactionHash===void 0)return{...f,activation:null};let s=await d.getTransactionReceipt({hash:e.transactionHash});if(s.status!=="success"||!C(s.from,o)||!s.to||!C(s.to,g)||s.transactionHash.toLowerCase()!==e.transactionHash.toLowerCase())throw new i("The transaction is not a successful Orbio activation from this wallet.");let v=Q(o.toLowerCase(),{size:32}),b=s.logs.filter(n=>C(n.address,$)),F=b.filter(n=>n.topics[0]?.toLowerCase()===nt);if(F.length!==1)throw new i("The receipt must contain one CREDIT activation.");let h=F[0],r=M({abi:k,eventName:"Activated",data:h.data,topics:h.topics,strict:!0}).args;if(!C(r.by,g)||r.ref.toLowerCase()!==v||r.amount===0n)throw new i("The CREDIT activation does not match Exchange and this wallet reference.");let m=b.filter(n=>n.topics[0]?.toLowerCase()===it).map(n=>M({abi:k,eventName:"ActivationFeeCharged",data:n.data,topics:n.topics,strict:!0}).args).filter(n=>n.activationId===r.activationId);if(m.length!==1||m[0].fee>r.amount)throw new i("The activation fee is missing or inconsistent.");let T=b.filter(n=>n.topics[0]?.toLowerCase()===ot).reduce((n,w)=>{let A=M({abi:R,eventName:"Transfer",data:w.data,topics:w.topics,strict:!0}).args;return n+(C(A.from,g)&&C(A.to,et)?A.value:0n)},0n);if(T!==r.amount)throw new i("The CREDIT burn does not match the activation amount.");return{...f,activation:{status:"onchain_success",id:r.activationId.toString(),transactionHash:s.transactionHash,blockNumber:s.blockNumber.toString(),by:g,ref:v,grossCredit:c(a,r.amount),burnedCredit:c(a,T),activationFee:c(a,m[0].fee),netActivated:c(a,r.amount-m[0].fee),note:"Receipt inclusion only; finality and off-chain spendable credit are not established. totalSupply is a current read, not a historical supply delta."}}}var st=t=>{let e=o=>async(d,u)=>{try{return await o(t,d,u)}catch(x){throw new i(t.plainError(x))}};return{tools:[{name:"orbio_buy_credit",inputSchema:{type:"object",additionalProperties:!1,required:["usdgIn"],properties:{usdgIn:{type:"string",pattern:"^[0-9]+$",description:"USDG base units (6 decimals) on chain 4663."},minCreditOut:{type:"string",pattern:"^[0-9]+$",description:"Gross CREDIT minimum before activation fee; defaults to the quoted gross amount minus shared slippage."},maxFills:{type:"integer",minimum:1,maximum:64,default:16}}},execute:e(at)},{name:"orbio_credit_status",inputSchema:{type:"object",additionalProperties:!1,properties:{transactionHash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$",description:"Optional buyAndActivate receipt to inspect for this wallet."}}},execute:e(rt)}]}};function ht(t){return j("orbio",[st(t)])}export{ht as createModule,st as createModulePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../../../chunks/
|
|
1
|
+
import{a}from"../../../chunks/5SH3C7XP.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{a as createModulePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,c as m}from"../../../chunks/
|
|
1
|
+
import{a as o,c as m}from"../../../chunks/GOIVHR4B.js";import{a as t}from"../../../chunks/5SH3C7XP.js";import{c as a}from"../../../chunks/B2LA6VVF.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import{b as r}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";var i=e=>r("pons",[a(e),m(e),t(e)],o(e));export{i as createModule};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d}from"../../../chunks/
|
|
1
|
+
import{a,b,c,d}from"../../../chunks/B2LA6VVF.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{d as createLaunchStatusPart,c as createModulePart,a as readLaunchStatus,b as readLaunches};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../../../chunks/
|
|
1
|
+
import{a}from"../../../chunks/F3TOOLFQ.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{a as readPonsEthRatio};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"../../../chunks/
|
|
1
|
+
import{a,b,c}from"../../../chunks/GOIVHR4B.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/74X7PXPR.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{a as createCurveSwapProvider,c as createModulePart,b as createTradePart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"../../../chunks/
|
|
1
|
+
import{a,b,c}from"../../../chunks/UIJWIFGV.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/74X7PXPR.js";import"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{c as createModule,b as createModulePart,a as recoverLaunches};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as se,o as ae}from"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import{c as re}from"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import{b as ie}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import{a as U}from"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import{a as w,d as $,i as G}from"../../../chunks/25EOXUBI.js";import{a as N}from"../../../chunks/B5RZYFQC.js";import{a as m}from"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";import{decodeEventLog as ye,decodeFunctionResult as Ce,encodeFunctionData as M,getAddress as C,parseAbi as j}from"viem";var Pe="https://priors.trade/api/check",Q=604800n,de=50n,le=10000n,ce=5000000n,ue=500000000n,ee=86400n,pe=2592000n,ve="0x6982e39521a070a3c40782548bfbed6dc8f566ef",$e=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],n={pool:C(G[4663].priors.pool.address),lens:C(G[4663].priors.lens.address),usdg:C(G[4663].priors.usdg.address),registry:C(G[4663].priors.registry.address),stockVault:C(G[4663].priors.stockVault.address)},z={address:n.usdg,symbol:"USDG",decimals:$,chainId:w},g=j(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool v1Checked, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 qualifiedRepaid, uint256 qualifiedVolume, uint256 lateRepayments, uint256 scorePoints)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),De=j(["function available(uint256 agentId) view returns (uint256)"]),te=j(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),ge=j(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Re(e){return e.chainId===w&&e.address.toLowerCase()===n.usdg.toLowerCase()}function Oe(e,t){let r=t.amount.trim(),l=r.startsWith("-"),b=l||r.startsWith("+")?r.slice(1):r,k=e.formatAmount(b,t.token.decimals),T=Re(t.token)?"USDG":t.token.address;return`${l?"-":"+"}${k} ${T}`}function W(e,t,r){if(!r.length)return t;let l=r.map(b=>Oe(e,b)).join(", ");return`${t} Preview changes: ${l}.`}function me(e,t,r,l){let b=e[t]===void 0?void 0:N(e[t]),k=e[r]===void 0?void 0:N(e[r]);if(b!==void 0)return b;if(k!==void 0)return k;throw new m(`Provide ${l} as an integer string in base units ("${t}" or "${r}").`)}async function he(e,t){try{return C(await e.clientFor(w).readContract({address:n.registry,abi:te,functionName:"ownerOf",args:[t]}))}catch{throw new m(`Could not read the owner of ERC-8004 agent ${t} from registry ${n.registry}. Check the agent ID and retry when the registry is available.`)}}function F(e,t){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let r=BigInt(e.trim());if(r>0n)return r}throw new m(`Provide a positive integer ${t}.`)}function ke(e,t){let r=t!==void 0?F(t,"agentId"):void 0,l=[];for(let b of e)if(!(!b||typeof b.address!="string")&&b.address.toLowerCase()===n.pool.toLowerCase()&&!(!Array.isArray(b.topics)||b.topics.length===0))try{let k=ye({abi:g,eventName:"Borrowed",data:b.data,topics:b.topics});if(r!==void 0&&k.args.agentId!==r)continue;l.push(k.args.loanId)}catch{continue}return l.length===0?null:l[l.length-1].toString()}function fe(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],v1Checked:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),qualifiedRepaid:BigInt(e[18]),qualifiedVolume:BigInt(e[19]),lateRepayments:BigInt(e[20]),scorePoints:BigInt(e[21])}}function H(e,t){return{loanId:e,agentId:BigInt(t[0]),sponsorId:BigInt(t[1]),principal:BigInt(t[2]),fee:BigInt(t[3]),sponsorCut:BigInt(t[4]),reserveCut:BigInt(t[5]),premium:BigInt(t[6]),owner:C(String(t[7])),issuedAt:BigInt(t[8]),dueAt:BigInt(t[9]),defaultableAt:BigInt(t[10]),minScoreTerm:BigInt(t[11]),closedAt:BigInt(t[12]),status:Number(t[13])}}async function oe(e,t){let r=e.clientFor(w),l=await r.readContract({address:n.registry,abi:te,functionName:"balanceOf",args:[t]});if(l<=0n)return[];let b=l>10n?10:Number(l),k=Array.from({length:b},(T,o)=>BigInt(o));return Promise.all(k.map(T=>r.readContract({address:n.registry,abi:te,functionName:"tokenOfOwnerByIndex",args:[t,T]})))}async function be(e,t,r){if(t.agentId!==void 0&&t.agentId!==null&&String(t.agentId).trim()!=="")return F(t.agentId,"agentId");let l=await oe(e,r);if(l.length===0)throw new m("Priors borrowing requires an already-funded ERC-8004 credit line on CreditPoolV2; this wallet owns no ERC-8004 agent identity and Oak does not perform credit-line enrollment or sponsorship.");return l[0]}async function we(e,t,r){let l=e.clientFor(w),b=await he(e,t),[k,T]=await Promise.all([l.readContract({address:n.pool,abi:g,functionName:"delegateOf",args:[t]}),l.readContract({address:n.pool,abi:g,functionName:"isController",args:[t,r]})]),o=C(k);if(!T)throw new m(`Wallet ${r} is not an on-chain controller for ERC-8004 agent ${t} (ownerOf=${b}, delegateOf=${o}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:b,delegate:o}}function Le(e,t){if(!t.enrolled||t.isRoot||t.sponsor===0n)throw new m(`ERC-8004 agent ${e} does not have an enrolled, sponsor-backed non-root credit line on CreditPoolV2 (enrolled=${t.enrolled}, sponsor=${t.sponsor}, isRoot=${t.isRoot}). Priors actions require an already-funded ERC-8004 credit line.`);if(t.defaulted||t.frozen)throw new m(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${t.defaulted}, frozen=${t.frozen}).`);let r=t.delegatedIn>t.principalOut?t.delegatedIn-t.principalOut:0n;if(r<=0n)throw new m(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${t.delegatedIn}, principalOut=${t.principalOut}).`);return r}function Be(e){let t=e.borrowReceiptLogs??(ne(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(t))return[];let r=[];for(let l of t)ne(l)&&(typeof l.address!="string"||!Array.isArray(l.topics)||typeof l.data!="string"||r.push({address:l.address,topics:l.topics,data:l.data}));return r}var Se=e=>{let t={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(o,I){U(I);let a=C(I),i=a;if(o.receiver!==void 0&&(typeof o.receiver!="string"||o.receiver.trim().toLowerCase()!==a.toLowerCase()))throw new m("Priors receiver must be the signing wallet.");let c=me(o,"assets","amount","USDG deposit amount");if(c<=0n)throw new m("Deposit amount must be greater than zero.");let p=o.minShares===void 0?void 0:N(o.minShares),s=e.approval(n.usdg,n.pool,c.toString(),w);if(p===void 0){let u;try{let A=await e.clientFor(w).simulateCalls({account:a,calls:[{to:s.to,data:s.data},{to:n.pool,data:M({abi:g,functionName:"deposit",args:[c,i,0n]})}]}),[B,O]=A.results;if(B?.status!=="success"||O?.status!=="success")throw new m("Approval or deposit simulation failed.");u=Ce({abi:g,functionName:"deposit",data:O.data})}catch(A){throw new m(`Could not simulate Priors deposit shares: ${e.plainError(A)}`)}if(p=N(ae(u.toString(),o.slippageBps??se)),p===0n)throw new m("The simulated deposit cannot provide a positive minimum share amount.")}let h=e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"deposit",args:[c,i,p]}),value:"0",chainId:w,description:`Deposit ${c} USDG base units into Priors CreditPoolV2 (${n.pool}) for ${i}.`}),y=[s,h],d=await e.preview(y,a),L=`Approve ${e.formatAmount(c.toString(),$)} USDG and deposit into Priors CreditPoolV2 (${n.pool}) for ${i} (minShares=${p}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:y,summary:W(e,L,d.changes)}}},r={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(o,I){U(I);let a=C(I),i=a;if(o.receiver!==void 0&&(typeof o.receiver!="string"||o.receiver.trim().toLowerCase()!==a.toLowerCase()))throw new m("Priors receiver must be the signing wallet.");let c=e.clientFor(w),p=o.shares!==void 0?N(o.shares):await c.readContract({address:n.pool,abi:g,functionName:"shares",args:[a]});if(p<=0n)throw new m(`Wallet ${a} has no Priors CreditPoolV2 shares to withdraw.`);let[s,h,y]=await Promise.all([c.readContract({address:n.pool,abi:g,functionName:"convertToAssets",args:[p]}),c.readContract({address:n.pool,abi:g,functionName:"lastDepositAt",args:[a]}),c.getBlock()]),d=h>0n&&y.timestamp<h+Q,S=d?s*de/le:0n,L=s-S,A=[e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"withdraw",args:[p,i]}),value:"0",chainId:w,description:`Withdraw ${p} shares from Priors CreditPoolV2 (${n.pool}) to ${i}.`})],B=await e.preview(A,a),O=e.formatAmount(L.toString(),$),_=e.formatAmount(s.toString(),$),D=e.formatAmount(S.toString(),$),P=d?`inside 7-day MIN_HOLD: ${D} USDG (0.5%) early-exit fee stays in pool, net payout ${O} USDG from ${_} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${O} USDG`,v=`Withdraw ${p} shares from Priors CreditPoolV2 (${n.pool}) to ${i} (${P}).`;return{txs:A,summary:W(e,v,B.changes)}}},l={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400").'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional maximum origination fee in USDG base units (defaults to exact quoteFee result)."}}},async execute(o,I){U(I);let a=C(I),i=a;if(o.recipient!==void 0&&(typeof o.recipient!="string"||o.recipient.trim().toLowerCase()!==a.toLowerCase()))throw new m("Priors recipient must be the signing wallet.");let c=await be(e,o,a);await we(e,c,a);let p=e.clientFor(w),s=await p.readContract({address:n.pool,abi:g,functionName:"getAgent",args:[c]}),h=fe(s),y=Le(c,h),d=me(o,"principal","amount","USDG borrow principal");if(d<ce||d>ue)throw new m(`Borrow principal must be between ${ce} (5 USDG) and ${ue} (500 USDG) base units.`);if(d>y)throw new m(`Borrow principal ${d} exceeds available credit line capacity ${y} USDG base units for agent ${c}.`);let S=o.term!==void 0&&String(o.term).trim()!==""?F(o.term,"term"):ee;if(S<ee||S>pe)throw new m(`Loan term must be between ${ee} (1 day) and ${pe} (30 days) seconds.`);let L=await p.readContract({address:n.pool,abi:g,functionName:"quoteFee",args:[c,d,S]}),u=L[0],A=o.maxFee!==void 0?N(o.maxFee):u;if(A<u)throw new m(`Provided maxFee ${A} is below the quoted fixed origination fee ${u} USDG base units.`);let B=d+u,O=d+A,D=[e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"borrow",args:[c,d,S,i,A]}),value:"0",chainId:w,description:`Borrow ${d} USDG base units on Priors CreditPoolV2 for agent ${c} to ${i} (quoted fee ${u}, expected debt ${B}, maxFee ${A}, debt ceiling ${O}).`})],P=await e.preview(D,a),v=e.formatAmount(d.toString(),$),x=e.formatAmount(u.toString(),$),E=e.formatAmount(B.toString(),$),X=e.formatAmount(A.toString(),$),J=e.formatAmount(O.toString(),$),V=L[1]+L[3],q=L[2],Y=u-V-q,Z=`Borrow ${v} USDG for ERC-8004 agent ${c} to recipient ${i} on Priors CreditPoolV2 (${n.pool}) for ${S}s: expected fixed origination fee ${x} USDG (${u} base units), expected total repayment due ${E} USDG (${B} base units); fee ceiling ${X} USDG (${A} base units), debt ceiling ${J} USDG (${O} base units). Fee recipient on repayment: CreditPoolV2 (${n.pool}), allocating the quoted fee to sponsor ${h.sponsor} (${V} base units including premium), reserve (${q} base units), and lenders (${Y} base units).`;return{txs:D,summary:W(e,Z,P.changes)}}},b={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay (defaults to exact fixed principal + fee)."}}},async execute(o,I){U(I);let a=C(I),i=await be(e,o,a);await we(e,i,a);let c=e.clientFor(w),p;if(o.loanId!==void 0&&o.loanId!==null&&String(o.loanId).trim()!=="")p=F(o.loanId,"loanId");else{let D=Be(o);if(D.length>0){let P=ke(D,i);P!==null&&(p=BigInt(P))}}let s;if(p!==void 0){let D=await c.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[p]}),P=H(p,D);if(P.agentId!==i)throw new m(`Loan ${p} belongs to agent ${P.agentId}, not agent ${i}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(P.status!==1)throw new m(`Loan ${p} for agent ${i} is not active (status=${P.status}).`);s=P}else{let D=await c.readContract({address:n.pool,abi:g,functionName:"loansOf",args:[i]});if(D.length===0)throw new m(`ERC-8004 agent ${i} has no recorded loans on Priors CreditPoolV2.`);let v=(await Promise.all(D.map(async x=>{let E=await c.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[x]});return H(x,E)}))).filter(x=>x.agentId===i&&x.status===1);if(v.length===0)throw new m(`ERC-8004 agent ${i} has no active loans to repay.`);s=v[v.length-1]}let h=s.principal+s.fee,y=o.maxDue!==void 0?N(o.maxDue):h;if(y<h)throw new m(`Provided maxDue ${y} is below the exact fixed loan debt ${h} USDG base units (principal ${s.principal} + fixed fee ${s.fee}).`);let d=e.approval(n.usdg,n.pool,h.toString(),w),S=e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"repay",args:[s.loanId,i,y]}),value:"0",chainId:w,description:`Repay fixed debt ${h} USDG base units (principal ${s.principal} + fee ${s.fee}) for loan ${s.loanId} (agent ${i}).`}),L=[d,S],u=await e.preview(L,a),A=e.formatAmount(h.toString(),$),B=e.formatAmount(s.principal.toString(),$),O=e.formatAmount(s.fee.toString(),$),_=`Approve and repay ${A} USDG (${h} base units: ${B} USDG principal + ${O} USDG fixed fee) for Priors loan ${s.loanId} (agent ${i}).`;return{txs:L,summary:W(e,_,u.changes)}}},k={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(o,I){U(I);let a=C(I),i=e.clientFor(w),[c,p,s,h]=await Promise.all([i.readContract({address:n.pool,abi:g,functionName:"shares",args:[a]}),i.readContract({address:n.pool,abi:g,functionName:"lastDepositAt",args:[a]}),i.getBlock(),i.readContract({address:n.stockVault,abi:ge,functionName:"assetList"})]),y=c>0n?await i.readContract({address:n.pool,abi:g,functionName:"convertToAssets",args:[c]}):0n,d=c>0n&&p>0n&&s.timestamp<p+Q,S=d?y*de/le:0n,L=y-S,u=null;if(o.agentId!==void 0&&o.agentId!==null&&String(o.agentId).trim()!=="")u=F(o.agentId,"agentId");else{let v=await oe(e,a);v.length>0&&(u=v[0])}let A=null,B=!1,O=[],_=null,D=null;if(u!==null){let[v,x,E,X,J,V]=await Promise.all([i.readContract({address:n.pool,abi:g,functionName:"getAgent",args:[u]}),i.readContract({address:n.pool,abi:g,functionName:"loansOf",args:[u]}),i.readContract({address:n.lens,abi:De,functionName:"available",args:[u]}),i.readContract({address:n.stockVault,abi:ge,functionName:"borrowRoom",args:[u]}),i.readContract({address:n.pool,abi:g,functionName:"delegateOf",args:[u]}),i.readContract({address:n.pool,abi:g,functionName:"isController",args:[u,a]})]),q=await he(e,u),Y=C(J),Z=V,f=fe(v),Ae=f.delegatedIn>f.principalOut?f.delegatedIn-f.principalOut:0n;B=f.enrolled&&!f.isRoot&&!f.defaulted&&!f.frozen&&f.sponsor>0n&&f.delegatedIn>0n,_=E.toString(),D=X.toString();let Ie=await Promise.all(x.map(async R=>{let K=await i.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[R]});return H(R,K)}));for(let R of Ie)if(R.agentId===u&&R.status===1){let K=R.principal+R.fee;O.push({loanId:R.loanId.toString(),agentId:R.agentId.toString(),sponsorId:R.sponsorId.toString(),principal:R.principal.toString(),fee:R.fee.toString(),due:K.toString(),dueAt:R.dueAt.toString(),issuedAt:R.issuedAt.toString(),owner:R.owner,token:z})}A={agentId:u.toString(),owner:q,delegate:Y,isAuthorizedController:Z,enrolled:f.enrolled,isRoot:f.isRoot,defaulted:f.defaulted,frozen:f.frozen,sponsorId:f.sponsor.toString(),delegatedIn:f.delegatedIn.toString(),delegatedOut:f.delegatedOut.toString(),principalOut:f.principalOut.toString(),availableCapacity:Ae.toString(),activeLoansCount:f.activeLoans.toString(),loansRepaid:f.loansRepaid.toString(),volumeRepaid:f.volumeRepaid.toString(),feesPaid:f.feesPaid.toString(),scorePoints:f.scorePoints.toString()}}let P=null;if(o.includeApiCheck){let v=u!==null?`agent=${u.toString()}`:`address=${a}`;P={...await re(e.http,`${Pe}?${v}`,{method:"GET"},ne),grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:w,blockNumber:s.number?.toString()??null,blockTimestamp:s.timestamp.toString(),wallet:a,token:z,contracts:n,lender:{shares:c.toString(),grossAssets:y.toString(),earlyExitFeeAssets:S.toString(),netWithdrawAssets:L.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:d,minHoldSeconds:Q.toString()},hasFundedLine:B,agentId:u!==null?u.toString():null,agent:A,activeLoans:O,lens:{address:n.lens,available:_,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:n.stockVault,borrowRoom:D,onchainAssetCount:h.length,hostedMcpStockCount:35,extraNonStockAsset:C(ve),zeroCapAssets:$e.map(v=>C(v)),caveat:"StockVault metadata is read-only status for already-funded lines (36 on-chain assets including PT-USDG-25MAR2027; CLSK and RGTI have lineCap=0), not an enrollment workflow."},apiCheck:P,limitations:["Borrowing and repayment require an already-funded ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet); Oak does not perform root staking, sponsorship, or credit-line enrollment.","Loan debt is fixed principal + quoteFee origination fee; variable interest is never invented.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}};async function T(o){U(o);let I=C(o),a=e.clientFor(w),[i,c]=await Promise.all([a.readContract({address:n.pool,abi:g,functionName:"shares",args:[I]}),oe(e,I)]),p=[];if(i>0n){let s=await a.readContract({address:n.pool,abi:g,functionName:"convertToAssets",args:[i]});p.push({module:"priors",id:`priors:lender:${I.toLowerCase()}`,chainId:w,assets:[{token:z,amount:s.toString()}],description:`Priors CreditPoolV2 lender position (${i} shares = ${e.formatAmount(s.toString(),$)} USDG gross).`})}for(let s of c){let h=await a.readContract({address:n.pool,abi:g,functionName:"loansOf",args:[s]}),y=await Promise.all(h.map(async d=>{let S=await a.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[d]});return H(d,S)}));for(let d of y)if(d.agentId===s&&d.status===1){let S=d.principal+d.fee;p.push({module:"priors",id:`priors:loan:${d.loanId.toString()}`,chainId:w,assets:[{token:z,amount:S.toString()}],description:`Priors CreditPoolV2 active loan ${d.loanId} for agent ${s} (fixed due ${e.formatAmount(S.toString(),$)} USDG = ${d.principal} principal + ${d.fee} fee).`})}}return p}return{tools:[t,r,l,b,k],positions:T}},Ve=Se,xe=e=>ie("priors",[Se(e)]),qe=xe;export{Pe as PRIORS_API_CHECK_URL,le as PRIORS_BPS_DENOMINATOR,n as PRIORS_CONTRACTS,de as PRIORS_EARLY_EXIT_FEE_BPS,ue as PRIORS_MAX_LOAN_USDG,pe as PRIORS_MAX_TERM_SECONDS,Q as PRIORS_MIN_HOLD_SECONDS,ce as PRIORS_MIN_LOAN_USDG,ee as PRIORS_MIN_TERM_SECONDS,z as PRIORS_USDG_TOKEN,xe as createModule,Se as createModulePart,qe as createPriorsModule,Ve as createPriorsPart,ke as recoverBorrowedLoanId};
|
|
1
|
+
import{b as se,o as ae}from"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import{c as re}from"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import{b as ie}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import{a as U}from"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import{a as S,d as $,i as G}from"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import{a as _}from"../../../chunks/7I6TXFXR.js";import{a as f}from"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";import{decodeEventLog as ye,decodeFunctionResult as Ce,encodeFunctionData as M,getAddress as C,parseAbi as j,parseAbiItem as ve}from"viem";var Pe="https://priors.trade/api/check",Q=604800n,de=50n,le=10000n,ce=5000000n,ue=500000000n,ee=86400n,pe=2592000n,$e="0x6982e39521a070a3c40782548bfbed6dc8f566ef",De=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],o={pool:C(G[4663].priors.pool.address),lens:C(G[4663].priors.lens.address),usdg:C(G[4663].priors.usdg.address),registry:C(G[4663].priors.registry.address),stockVault:C(G[4663].priors.stockVault.address)},z={address:o.usdg,symbol:"USDG",decimals:$,chainId:S},g=j(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool v1Checked, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 qualifiedRepaid, uint256 qualifiedVolume, uint256 lateRepayments, uint256 scorePoints)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),Re=j(["function available(uint256 agentId) view returns (uint256)"]),he=j(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),ge=j(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function te(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ke(e){return e.chainId===S&&e.address.toLowerCase()===o.usdg.toLowerCase()}function Le(e,t){let r=t.amount.trim(),c=r.startsWith("-"),m=c||r.startsWith("+")?r.slice(1):r,D=e.formatAmount(m,t.token.decimals),T=ke(t.token)?"USDG":t.token.address;return`${c?"-":"+"}${D} ${T}`}function W(e,t,r){if(!r.length)return t;let c=r.map(m=>Le(e,m)).join(", ");return`${t} Preview changes: ${c}.`}function fe(e,t,r,c){let m=e[t]===void 0?void 0:_(e[t]),D=e[r]===void 0?void 0:_(e[r]);if(m!==void 0)return m;if(D!==void 0)return D;throw new f(`Provide ${c} as an integer string in base units ("${t}" or "${r}").`)}async function oe(e,t,r){try{return C(await e.clientFor(S).readContract({address:o.registry,abi:he,functionName:"ownerOf",args:[t],blockNumber:r}))}catch{throw new f(`Could not read the owner of ERC-8004 agent ${t} from registry ${o.registry}. Check the agent ID and retry when the registry is available.`)}}function F(e,t){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let r=BigInt(e.trim());if(r>0n)return r}throw new f(`Provide a positive integer ${t}.`)}function Oe(e,t){let r=t!==void 0?F(t,"agentId"):void 0,c=[];for(let m of e)if(!(!m||typeof m.address!="string")&&m.address.toLowerCase()===o.pool.toLowerCase()&&!(!Array.isArray(m.topics)||m.topics.length===0))try{let D=ye({abi:g,eventName:"Borrowed",data:m.data,topics:m.topics});if(r!==void 0&&D.args.agentId!==r)continue;c.push(D.args.loanId)}catch{continue}return c.length===0?null:c[c.length-1].toString()}function me(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],v1Checked:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),qualifiedRepaid:BigInt(e[18]),qualifiedVolume:BigInt(e[19]),lateRepayments:BigInt(e[20]),scorePoints:BigInt(e[21])}}function H(e,t){return{loanId:e,agentId:BigInt(t[0]),sponsorId:BigInt(t[1]),principal:BigInt(t[2]),fee:BigInt(t[3]),sponsorCut:BigInt(t[4]),reserveCut:BigInt(t[5]),premium:BigInt(t[6]),owner:C(String(t[7])),issuedAt:BigInt(t[8]),dueAt:BigInt(t[9]),defaultableAt:BigInt(t[10]),minScoreTerm:BigInt(t[11]),closedAt:BigInt(t[12]),status:Number(t[13])}}async function ne(e,t){let r=e.clientFor(S),c=await r.getBlockNumber({cacheTime:0}),m=await r.readContract({address:o.registry,abi:he,functionName:"balanceOf",args:[t],blockNumber:c});if(m===0n)return[];if(typeof m!="bigint"||m<0n)throw new f("Registry balance is unavailable. Retry or provide an explicit agentId.");let D=[],T=new Set,n=c;for(;;){let w=n>9999999n?n-9999999n:0n,d=await r.getLogs({address:o.registry,event:ve("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:t},fromBlock:w,toBlock:n,strict:!0});for(let i of d){let a=i.args.tokenId;if(i.removed||T.has(a))continue;if(T.add(a),(await oe(e,a,c)).toLowerCase()===t.toLowerCase()&&D.push(a),BigInt(D.length)===m)return D.sort((s,h)=>s<h?-1:s>h?1:0)}if(w===0n)throw new f("Owned identities could not all be located. Retry or provide an explicit agentId.");n=w-1n}}async function be(e,t,r){if(t.agentId!==void 0&&t.agentId!==null&&String(t.agentId).trim()!=="")return F(t.agentId,"agentId");let c=await ne(e,r);if(c.length===0)throw new f("Priors borrowing requires an already-funded ERC-8004 credit line on CreditPoolV2; this wallet owns no ERC-8004 agent identity and Oak does not perform credit-line enrollment or sponsorship.");return c[0]}async function we(e,t,r){let c=e.clientFor(S),m=await oe(e,t),[D,T]=await Promise.all([c.readContract({address:o.pool,abi:g,functionName:"delegateOf",args:[t]}),c.readContract({address:o.pool,abi:g,functionName:"isController",args:[t,r]})]),n=C(D);if(!T)throw new f(`Wallet ${r} is not an on-chain controller for ERC-8004 agent ${t} (ownerOf=${m}, delegateOf=${n}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:m,delegate:n}}function Be(e,t){if(!t.enrolled||t.isRoot||t.sponsor===0n)throw new f(`ERC-8004 agent ${e} does not have an enrolled, sponsor-backed non-root credit line on CreditPoolV2 (enrolled=${t.enrolled}, sponsor=${t.sponsor}, isRoot=${t.isRoot}). Priors actions require an already-funded ERC-8004 credit line.`);if(t.defaulted||t.frozen)throw new f(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${t.defaulted}, frozen=${t.frozen}).`);let r=t.delegatedIn>t.principalOut?t.delegatedIn-t.principalOut:0n;if(r<=0n)throw new f(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${t.delegatedIn}, principalOut=${t.principalOut}).`);return r}function xe(e){let t=e.borrowReceiptLogs??(te(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(t))return[];let r=[];for(let c of t)te(c)&&(typeof c.address!="string"||!Array.isArray(c.topics)||typeof c.data!="string"||r.push({address:c.address,topics:c.topics,data:c.data}));return r}var Se=e=>{let t={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(n,w){U(w);let d=C(w),i=d;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==d.toLowerCase()))throw new f("Priors receiver must be the signing wallet.");let a=fe(n,"assets","amount","USDG deposit amount");if(a<=0n)throw new f("Deposit amount must be greater than zero.");let u=n.minShares===void 0?void 0:_(n.minShares),s=e.approval(o.usdg,o.pool,a.toString(),S);if(u===void 0){let p;try{let A=await e.clientFor(S).simulateCalls({account:d,calls:[{to:s.to,data:s.data},{to:o.pool,data:M({abi:g,functionName:"deposit",args:[a,i,0n]})}]}),[B,L]=A.results;if(B?.status!=="success"||L?.status!=="success")throw new f("Approval or deposit simulation failed.");p=Ce({abi:g,functionName:"deposit",data:L.data})}catch(A){throw new f(`Could not simulate Priors deposit shares: ${e.plainError(A)}`)}if(u=_(ae(p.toString(),n.slippageBps??se)),u===0n)throw new f("The simulated deposit cannot provide a positive minimum share amount.")}let h=e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"deposit",args:[a,i,u]}),value:"0",chainId:S,description:`Deposit ${a} USDG base units into Priors CreditPoolV2 (${o.pool}) for ${i}.`}),y=[s,h],l=await e.preview(y,d),O=`Approve ${e.formatAmount(a.toString(),$)} USDG and deposit into Priors CreditPoolV2 (${o.pool}) for ${i} (minShares=${u}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:y,summary:W(e,O,l.changes)}}},r={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(n,w){U(w);let d=C(w),i=d;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==d.toLowerCase()))throw new f("Priors receiver must be the signing wallet.");let a=e.clientFor(S),u=n.shares!==void 0?_(n.shares):await a.readContract({address:o.pool,abi:g,functionName:"shares",args:[d]});if(u<=0n)throw new f(`Wallet ${d} has no Priors CreditPoolV2 shares to withdraw.`);let[s,h,y]=await Promise.all([a.readContract({address:o.pool,abi:g,functionName:"convertToAssets",args:[u]}),a.readContract({address:o.pool,abi:g,functionName:"lastDepositAt",args:[d]}),a.getBlock()]),l=h>0n&&y.timestamp<h+Q,I=l?s*de/le:0n,O=s-I,A=[e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"withdraw",args:[u,i]}),value:"0",chainId:S,description:`Withdraw ${u} shares from Priors CreditPoolV2 (${o.pool}) to ${i}.`})],B=await e.preview(A,d),L=e.formatAmount(O.toString(),$),N=e.formatAmount(s.toString(),$),R=e.formatAmount(I.toString(),$),v=l?`inside 7-day MIN_HOLD: ${R} USDG (0.5%) early-exit fee stays in pool, net payout ${L} USDG from ${N} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${L} USDG`,P=`Withdraw ${u} shares from Priors CreditPoolV2 (${o.pool}) to ${i} (${v}).`;return{txs:A,summary:W(e,P,B.changes)}}},c={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400").'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional maximum origination fee in USDG base units (defaults to exact quoteFee result)."}}},async execute(n,w){U(w);let d=C(w),i=d;if(n.recipient!==void 0&&(typeof n.recipient!="string"||n.recipient.trim().toLowerCase()!==d.toLowerCase()))throw new f("Priors recipient must be the signing wallet.");let a=await be(e,n,d);await we(e,a,d);let u=e.clientFor(S),s=await u.readContract({address:o.pool,abi:g,functionName:"getAgent",args:[a]}),h=me(s),y=Be(a,h),l=fe(n,"principal","amount","USDG borrow principal");if(l<ce||l>ue)throw new f(`Borrow principal must be between ${ce} (5 USDG) and ${ue} (500 USDG) base units.`);if(l>y)throw new f(`Borrow principal ${l} exceeds available credit line capacity ${y} USDG base units for agent ${a}.`);let I=n.term!==void 0&&String(n.term).trim()!==""?F(n.term,"term"):ee;if(I<ee||I>pe)throw new f(`Loan term must be between ${ee} (1 day) and ${pe} (30 days) seconds.`);let O=await u.readContract({address:o.pool,abi:g,functionName:"quoteFee",args:[a,l,I]}),p=O[0],A=n.maxFee!==void 0?_(n.maxFee):p;if(A<p)throw new f(`Provided maxFee ${A} is below the quoted fixed origination fee ${p} USDG base units.`);let B=l+p,L=l+A,R=[e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"borrow",args:[a,l,I,i,A]}),value:"0",chainId:S,description:`Borrow ${l} USDG base units on Priors CreditPoolV2 for agent ${a} to ${i} (quoted fee ${p}, expected debt ${B}, maxFee ${A}, debt ceiling ${L}).`})],v=await e.preview(R,d),P=e.formatAmount(l.toString(),$),x=e.formatAmount(p.toString(),$),E=e.formatAmount(B.toString(),$),X=e.formatAmount(A.toString(),$),J=e.formatAmount(L.toString(),$),V=O[1]+O[3],q=O[2],Y=p-V-q,Z=`Borrow ${P} USDG for ERC-8004 agent ${a} to recipient ${i} on Priors CreditPoolV2 (${o.pool}) for ${I}s: expected fixed origination fee ${x} USDG (${p} base units), expected total repayment due ${E} USDG (${B} base units); fee ceiling ${X} USDG (${A} base units), debt ceiling ${J} USDG (${L} base units). Fee recipient on repayment: CreditPoolV2 (${o.pool}), allocating the quoted fee to sponsor ${h.sponsor} (${V} base units including premium), reserve (${q} base units), and lenders (${Y} base units).`;return{txs:R,summary:W(e,Z,v.changes)}}},m={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay (defaults to exact fixed principal + fee)."}}},async execute(n,w){U(w);let d=C(w),i=await be(e,n,d);await we(e,i,d);let a=e.clientFor(S),u;if(n.loanId!==void 0&&n.loanId!==null&&String(n.loanId).trim()!=="")u=F(n.loanId,"loanId");else{let R=xe(n);if(R.length>0){let v=Oe(R,i);v!==null&&(u=BigInt(v))}}let s;if(u!==void 0){let R=await a.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[u]}),v=H(u,R);if(v.agentId!==i)throw new f(`Loan ${u} belongs to agent ${v.agentId}, not agent ${i}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(v.status!==1)throw new f(`Loan ${u} for agent ${i} is not active (status=${v.status}).`);s=v}else{let R=await a.readContract({address:o.pool,abi:g,functionName:"loansOf",args:[i]});if(R.length===0)throw new f(`ERC-8004 agent ${i} has no recorded loans on Priors CreditPoolV2.`);let P=(await Promise.all(R.map(async x=>{let E=await a.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[x]});return H(x,E)}))).filter(x=>x.agentId===i&&x.status===1);if(P.length===0)throw new f(`ERC-8004 agent ${i} has no active loans to repay.`);s=P[P.length-1]}let h=s.principal+s.fee,y=n.maxDue!==void 0?_(n.maxDue):h;if(y<h)throw new f(`Provided maxDue ${y} is below the exact fixed loan debt ${h} USDG base units (principal ${s.principal} + fixed fee ${s.fee}).`);let l=e.approval(o.usdg,o.pool,h.toString(),S),I=e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"repay",args:[s.loanId,i,y]}),value:"0",chainId:S,description:`Repay fixed debt ${h} USDG base units (principal ${s.principal} + fee ${s.fee}) for loan ${s.loanId} (agent ${i}).`}),O=[l,I],p=await e.preview(O,d),A=e.formatAmount(h.toString(),$),B=e.formatAmount(s.principal.toString(),$),L=e.formatAmount(s.fee.toString(),$),N=`Approve and repay ${A} USDG (${h} base units: ${B} USDG principal + ${L} USDG fixed fee) for Priors loan ${s.loanId} (agent ${i}).`;return{txs:O,summary:W(e,N,p.changes)}}},D={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(n,w){U(w);let d=C(w),i=e.clientFor(S),[a,u,s,h]=await Promise.all([i.readContract({address:o.pool,abi:g,functionName:"shares",args:[d]}),i.readContract({address:o.pool,abi:g,functionName:"lastDepositAt",args:[d]}),i.getBlock(),i.readContract({address:o.stockVault,abi:ge,functionName:"assetList"})]),y=a>0n?await i.readContract({address:o.pool,abi:g,functionName:"convertToAssets",args:[a]}):0n,l=a>0n&&u>0n&&s.timestamp<u+Q,I=l?y*de/le:0n,O=y-I,p=null;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")p=F(n.agentId,"agentId");else{let P=await ne(e,d);P.length>0&&(p=P[0])}let A=null,B=!1,L=[],N=null,R=null;if(p!==null){let[P,x,E,X,J,V]=await Promise.all([i.readContract({address:o.pool,abi:g,functionName:"getAgent",args:[p]}),i.readContract({address:o.pool,abi:g,functionName:"loansOf",args:[p]}),i.readContract({address:o.lens,abi:Re,functionName:"available",args:[p]}),i.readContract({address:o.stockVault,abi:ge,functionName:"borrowRoom",args:[p]}),i.readContract({address:o.pool,abi:g,functionName:"delegateOf",args:[p]}),i.readContract({address:o.pool,abi:g,functionName:"isController",args:[p,d]})]),q=await oe(e,p),Y=C(J),Z=V,b=me(P),Ie=b.delegatedIn>b.principalOut?b.delegatedIn-b.principalOut:0n;B=b.enrolled&&!b.isRoot&&!b.defaulted&&!b.frozen&&b.sponsor>0n&&b.delegatedIn>0n,N=E.toString(),R=X.toString();let Ae=await Promise.all(x.map(async k=>{let K=await i.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[k]});return H(k,K)}));for(let k of Ae)if(k.agentId===p&&k.status===1){let K=k.principal+k.fee;L.push({loanId:k.loanId.toString(),agentId:k.agentId.toString(),sponsorId:k.sponsorId.toString(),principal:k.principal.toString(),fee:k.fee.toString(),due:K.toString(),dueAt:k.dueAt.toString(),issuedAt:k.issuedAt.toString(),owner:k.owner,token:z})}A={agentId:p.toString(),owner:q,delegate:Y,isAuthorizedController:Z,enrolled:b.enrolled,isRoot:b.isRoot,defaulted:b.defaulted,frozen:b.frozen,sponsorId:b.sponsor.toString(),delegatedIn:b.delegatedIn.toString(),delegatedOut:b.delegatedOut.toString(),principalOut:b.principalOut.toString(),availableCapacity:Ie.toString(),activeLoansCount:b.activeLoans.toString(),loansRepaid:b.loansRepaid.toString(),volumeRepaid:b.volumeRepaid.toString(),feesPaid:b.feesPaid.toString(),scorePoints:b.scorePoints.toString()}}let v=null;if(n.includeApiCheck){let P=p!==null?`agent=${p.toString()}`:`address=${d}`;v={...await re(e.http,`${Pe}?${P}`,{method:"GET"},te),grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:S,blockNumber:s.number?.toString()??null,blockTimestamp:s.timestamp.toString(),wallet:d,token:z,contracts:o,lender:{shares:a.toString(),grossAssets:y.toString(),earlyExitFeeAssets:I.toString(),netWithdrawAssets:O.toString(),lastDepositAt:u.toString(),withinMinHoldWindow:l,minHoldSeconds:Q.toString()},hasFundedLine:B,agentId:p!==null?p.toString():null,agent:A,activeLoans:L,lens:{address:o.lens,available:N,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:o.stockVault,borrowRoom:R,onchainAssetCount:h.length,hostedMcpStockCount:35,extraNonStockAsset:C($e),zeroCapAssets:De.map(P=>C(P)),caveat:"StockVault metadata is read-only status for already-funded lines (36 on-chain assets including PT-USDG-25MAR2027; CLSK and RGTI have lineCap=0), not an enrollment workflow."},apiCheck:v,limitations:["Borrowing and repayment require an already-funded ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet); Oak does not perform root staking, sponsorship, or credit-line enrollment.","Loan debt is fixed principal + quoteFee origination fee; variable interest is never invented.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}};async function T(n){U(n);let w=C(n),d=e.clientFor(S),[i,a]=await Promise.all([d.readContract({address:o.pool,abi:g,functionName:"shares",args:[w]}),ne(e,w)]),u=[];if(i>0n){let s=await d.readContract({address:o.pool,abi:g,functionName:"convertToAssets",args:[i]});u.push({module:"priors",id:`priors:lender:${w.toLowerCase()}`,chainId:S,assets:[{token:z,amount:s.toString()}],description:`Priors CreditPoolV2 lender position (${i} shares = ${e.formatAmount(s.toString(),$)} USDG gross).`})}for(let s of a){let h=await d.readContract({address:o.pool,abi:g,functionName:"loansOf",args:[s]}),y=await Promise.all(h.map(async l=>{let I=await d.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[l]});return H(l,I)}));for(let l of y)if(l.agentId===s&&l.status===1){let I=l.principal+l.fee;u.push({module:"priors",id:`priors:loan:${l.loanId.toString()}`,chainId:S,assets:[{token:z,amount:I.toString()}],description:`Priors CreditPoolV2 active loan ${l.loanId} for agent ${s} (fixed due ${e.formatAmount(I.toString(),$)} USDG = ${l.principal} principal + ${l.fee} fee).`})}}return u}return{tools:[t,r,c,m,D],positions:T}},qe=Se,Te=e=>ie("priors",[Se(e)]),ze=Te;export{Pe as PRIORS_API_CHECK_URL,le as PRIORS_BPS_DENOMINATOR,o as PRIORS_CONTRACTS,de as PRIORS_EARLY_EXIT_FEE_BPS,ue as PRIORS_MAX_LOAN_USDG,pe as PRIORS_MAX_TERM_SECONDS,Q as PRIORS_MIN_HOLD_SECONDS,ce as PRIORS_MIN_LOAN_USDG,ee as PRIORS_MIN_TERM_SECONDS,z as PRIORS_USDG_TOKEN,Te as createModule,Se as createModulePart,ze as createPriorsModule,qe as createPriorsPart,Oe as recoverBorrowedLoanId};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../../../chunks/
|
|
1
|
+
import{a,b}from"../../../chunks/ZZLHDHOT.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/74X7PXPR.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{b as createModulePart,a as relayOriginDepository};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{b as r}from"../../../chunks/ZZLHDHOT.js";import{a as t}from"../../../chunks/SUQ6PIAV.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import{b as o}from"../../../chunks/UB5U6SI2.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";var d=e=>o("relay",[t(e),r(e)]);export{d as createModule};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../../../chunks/
|
|
1
|
+
import{a}from"../../../chunks/SUQ6PIAV.js";import"../../../chunks/XEN45QST.js";import"../../../chunks/Z53DADZ4.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MEZH7RPA.js";import"../../../chunks/TU3KHOZK.js";import"../../../chunks/74X7PXPR.js";import"../../../chunks/VBWJOG3N.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/R5CBH2CR.js";import"../../../chunks/5BP72XOA.js";import"../../../chunks/XAB4OIE3.js";import"../../../chunks/7I6TXFXR.js";import"../../../chunks/Z3FZWNAJ.js";import"../../../chunks/XN4WDN3O.js";export{a as createOutboundStatus};
|