@oakagentkit/core 0.1.9 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/dist/api/deployments.d.ts +26 -0
- package/build/dist/api/deployments.js +1 -0
- package/build/dist/api/history.js +1 -1
- package/build/dist/api/modules/beefy/clm.js +1 -1
- package/build/dist/api/modules/beefy/guard.js +1 -1
- package/build/dist/api/modules/beefy/index.js +1 -1
- package/build/dist/api/modules/beefy/liquidity.js +1 -1
- package/build/dist/api/modules/clanker/index.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
- package/build/dist/api/modules/hoodlock/fee.js +1 -1
- package/build/dist/api/modules/hoodlock/guard.js +1 -1
- package/build/dist/api/modules/hoodlock/index.js +1 -1
- package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
- package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
- package/build/dist/api/modules/hoodlock/public.js +1 -1
- package/build/dist/api/modules/hookr/actions.js +1 -1
- package/build/dist/api/modules/hookr/addons.js +1 -1
- package/build/dist/api/modules/hookr/contracts.js +1 -1
- package/build/dist/api/modules/hookr/create-cancel.js +1 -1
- package/build/dist/api/modules/hookr/discovery.js +1 -1
- package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
- package/build/dist/api/modules/hookr/index.js +1 -1
- package/build/dist/api/modules/hookr/public-reads.js +1 -1
- package/build/dist/api/modules/hookr/relay.js +1 -1
- package/build/dist/api/modules/kyberswap/index.js +1 -1
- package/build/dist/api/modules/kyberswap/source-pools.d.ts +22 -3
- package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
- package/build/dist/api/modules/longbow/administration.js +1 -1
- package/build/dist/api/modules/longbow/fixed.js +1 -1
- package/build/dist/api/modules/longbow/index.js +1 -1
- package/build/dist/api/modules/meridian/index.js +1 -1
- package/build/dist/api/modules/meridian/rfq.js +1 -1
- package/build/dist/api/modules/morpho/bundles.js +1 -1
- package/build/dist/api/modules/morpho/in-kind.js +1 -1
- package/build/dist/api/modules/morpho/index.js +1 -1
- package/build/dist/api/modules/morpho/local-guard.js +1 -1
- package/build/dist/api/modules/morpho/midnight.js +1 -1
- package/build/dist/api/modules/morpho/protocol.js +1 -1
- package/build/dist/api/modules/morpho/vault-tools.js +1 -1
- package/build/dist/api/modules/netnet/card-plan.js +1 -1
- package/build/dist/api/modules/netnet/card-read.js +1 -1
- package/build/dist/api/modules/netnet/card-recovery.js +1 -1
- package/build/dist/api/modules/netnet/desk-action.js +1 -1
- package/build/dist/api/modules/netnet/financial.js +1 -1
- package/build/dist/api/modules/netnet/index.js +1 -1
- package/build/dist/api/modules/orbio/index.js +1 -1
- package/build/dist/api/modules/pons/claim.js +1 -1
- package/build/dist/api/modules/pons/index.js +1 -1
- package/build/dist/api/modules/pons/launch-status.js +1 -1
- package/build/dist/api/modules/pons/reads.js +1 -1
- package/build/dist/api/modules/pons/trade.js +1 -1
- package/build/dist/api/modules/poolstrade/index.js +1 -1
- package/build/dist/api/modules/priors/index.js +1 -1
- package/build/dist/api/modules/relay/discovery.js +1 -1
- package/build/dist/api/modules/relay/inbound.js +1 -1
- package/build/dist/api/modules/relay/index.js +1 -1
- package/build/dist/api/modules/relay/outbound-status.js +1 -1
- package/build/dist/api/modules/steakhouse/index.js +1 -1
- package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
- package/build/dist/api/modules/steakhouse/management.js +1 -1
- package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
- package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
- package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
- package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
- package/build/dist/api/modules/tickerspring/guards.js +1 -1
- package/build/dist/api/modules/tickerspring/index.js +1 -1
- package/build/dist/api/modules/tickerspring/journeys.js +1 -1
- package/build/dist/api/modules/tickerspring/ladder.js +1 -1
- package/build/dist/api/modules/tickerspring/maker.js +1 -1
- package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
- package/build/dist/api/modules/tickerspring/research.js +1 -1
- package/build/dist/api/modules/tickerspring/strategies.js +1 -1
- package/build/dist/api/modules/uniswap/auction-create.js +1 -1
- package/build/dist/api/modules/uniswap/auction.js +1 -1
- package/build/dist/api/modules/uniswap/batch.js +1 -1
- package/build/dist/api/modules/uniswap/common.js +1 -1
- package/build/dist/api/modules/uniswap/fees.js +1 -1
- package/build/dist/api/modules/uniswap/index.js +1 -1
- package/build/dist/api/modules/uniswap/local-guard.js +1 -1
- package/build/dist/api/modules/uniswap/oracle.js +1 -1
- package/build/dist/api/modules/uniswap/pool-math.js +1 -1
- package/build/dist/api/modules/uniswap/pools.js +1 -1
- package/build/dist/api/modules/uniswap/position.js +1 -1
- package/build/dist/api/modules/uniswap/protocol.js +1 -1
- package/build/dist/api/modules/uniswap/token-jar.js +1 -1
- package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
- package/build/dist/api/modules/uniswap/trade.js +1 -1
- package/build/dist/api/modules/uniswap/v2.js +1 -1
- package/build/dist/api/modules/uniswap/v3.js +1 -1
- package/build/dist/api/modules/uniswap/v4.js +1 -1
- package/build/dist/api/modules/uniswap/wrap.js +1 -1
- package/build/dist/api/modules/velora/claims.js +1 -1
- package/build/dist/api/modules/velora/index.js +1 -1
- package/build/dist/api/prices.js +1 -1
- package/build/dist/api/routes.d.ts +2 -0
- package/build/dist/api/routes.js +1 -1
- package/build/dist/api/send.js +1 -1
- package/build/dist/api/signing-registry.js +1 -1
- package/build/dist/api/simulate.js +1 -1
- package/build/dist/api/swap.js +1 -1
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/chunks/{QOY4AANB.js → 2SNQWKHA.js} +1 -1
- package/build/dist/chunks/{FYTF2QMS.js → 3ACEWCKZ.js} +1 -1
- package/build/dist/chunks/{HZUWK5B2.js → 46ZA2R5L.js} +1 -1
- package/build/dist/chunks/{W6G2QGYF.js → 4IPW5WZ4.js} +1 -1
- package/build/dist/chunks/{JRZLKIYB.js → 55NX776C.js} +1 -1
- package/build/dist/chunks/{2EGFALNH.js → 5FTSKYQH.js} +1 -1
- package/build/dist/chunks/{OJP7Y4AM.js → 5HW6JKME.js} +1 -1
- package/build/dist/chunks/{ZL3KVABO.js → 5VXNQFYJ.js} +1 -1
- package/build/dist/chunks/{ITIIHCZK.js → 64AF7ECA.js} +1 -1
- package/build/dist/chunks/{FLXID6I3.js → 6LLOTPH2.js} +1 -1
- package/build/dist/chunks/{CXMC3T6B.js → 6PU2CMQZ.js} +1 -1
- package/build/dist/chunks/{E2IVNGLC.js → 7BTELNNI.js} +1 -1
- package/build/dist/chunks/{C5LR6F4B.js → 7T4BYFD4.js} +1 -1
- package/build/dist/chunks/{6SB3FB3P.js → 7Z5IM2QZ.js} +1 -1
- package/build/dist/chunks/{JOMK32QW.js → A25P24G2.js} +1 -1
- package/build/dist/chunks/{FL3EF72E.js → ANQ43XJA.js} +1 -1
- package/build/dist/chunks/{B72Q2EQ2.js → BFVLBENV.js} +1 -1
- package/build/dist/chunks/{QH3AL3UN.js → BV3AHLH5.js} +1 -1
- package/build/dist/chunks/{EKGHKEKV.js → BXN3MDS4.js} +1 -1
- package/build/dist/chunks/CAU44UWP.js +1 -0
- package/build/dist/chunks/{HACP2Q6D.js → D6VP3N27.js} +2 -2
- package/build/dist/chunks/{37QNUNED.js → DLIOZCEG.js} +1 -1
- package/build/dist/chunks/EA6IYKIB.js +1 -0
- package/build/dist/chunks/{SYZ55RCX.js → EYYUWFUR.js} +1 -1
- package/build/dist/chunks/{HF2AGJZC.js → FSPNOVKB.js} +1 -1
- package/build/dist/chunks/G4PDM3MX.js +1 -0
- package/build/dist/chunks/{ZPNGV34U.js → GHDDVBPK.js} +1 -1
- package/build/dist/chunks/{OK3TQFXZ.js → GSI5COTD.js} +1 -1
- package/build/dist/chunks/{CAYBSVA6.js → HRG2VVPY.js} +1 -1
- package/build/dist/chunks/{MWWYIFXJ.js → ITV52TIE.js} +1 -1
- package/build/dist/chunks/{4CDR7F4I.js → IUXOUKQN.js} +1 -1
- package/build/dist/chunks/{5H3MQWH7.js → JC4SYMBV.js} +1 -1
- package/build/dist/chunks/{KEPQXFHU.js → JREVERSC.js} +1 -1
- package/build/dist/chunks/{NUWL6TJM.js → K463HFGC.js} +1 -1
- package/build/dist/chunks/{VCWDJQDE.js → KQFDLDHL.js} +1 -1
- package/build/dist/chunks/{LFKSXD3S.js → LI7FYINH.js} +1 -1
- package/build/dist/chunks/{4X6JEMSF.js → N6RL3SUZ.js} +1 -1
- package/build/dist/chunks/{E7ASOYQI.js → NBRMUFJP.js} +1 -1
- package/build/dist/chunks/{UEYFMXV3.js → NIOBE2LK.js} +1 -1
- package/build/dist/chunks/NMFVXBTL.js +1 -0
- package/build/dist/chunks/{REGJY5RC.js → NO57NGRV.js} +1 -1
- package/build/dist/chunks/{SEW7UP5U.js → O5SU2I3G.js} +1 -1
- package/build/dist/chunks/{P6ELT4ZV.js → PJ65ZOQ7.js} +1 -1
- package/build/dist/chunks/{B7V7AA5A.js → QCD33HMD.js} +1 -1
- package/build/dist/chunks/{SS7U3CMZ.js → QQWF6A4P.js} +1 -1
- package/build/dist/chunks/{NNZ4SZZ4.js → QZM7CWZW.js} +1 -1
- package/build/dist/chunks/{HYIEQG4X.js → QZTUMSQY.js} +1 -1
- package/build/dist/chunks/{JVTVOK6P.js → R7D256HG.js} +1 -1
- package/build/dist/chunks/{Z4LJ2GTX.js → RTBOMWCB.js} +1 -1
- package/build/dist/chunks/{EHVPRQHS.js → SDICP7BT.js} +1 -1
- package/build/dist/chunks/{L2MTPRU7.js → T3NPRRTY.js} +1 -1
- package/build/dist/chunks/{BQLLTY4L.js → TNRDCBGO.js} +1 -1
- package/build/dist/chunks/{IKP3Z3RX.js → U3FMCX3L.js} +1 -1
- package/build/dist/chunks/{WHT45EFX.js → UIIJWIR6.js} +1 -1
- package/build/dist/chunks/{K2LWX3PZ.js → UMK564HS.js} +1 -1
- package/build/dist/chunks/{AIWZGIZ6.js → UPPYXY74.js} +1 -1
- package/build/dist/chunks/{XCFA73P2.js → VJ3W2V3B.js} +1 -1
- package/build/dist/chunks/{RNEMTLQG.js → VY3P34PY.js} +1 -1
- package/build/dist/chunks/{2LM5C7FQ.js → WDGPCPQJ.js} +1 -1
- package/build/dist/chunks/{PHXWBC4O.js → XKRWJCYE.js} +1 -1
- package/build/dist/chunks/{E2Q5IA67.js → Y2IWPNEW.js} +1 -1
- package/build/dist/chunks/{YONRUWN7.js → ZCGVBK5K.js} +1 -1
- package/build/dist/chunks/{BBQVTEYB.js → ZGXNTWYG.js} +1 -1
- package/build/dist/chunks/{CS55ERS3.js → ZYR5LSVB.js} +1 -1
- package/package.json +1 -1
- package/build/dist/chunks/2O6A6WEX.js +0 -1
- package/build/dist/chunks/3Z3U4YPA.js +0 -1
- package/build/dist/chunks/EAEQOS7Y.js +0 -1
- package/build/dist/chunks/ZQI7B2Z7.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as v,d as N,e as h}from"./
|
|
1
|
+
import{c as v,d as N,e as h}from"./HRG2VVPY.js";import{a as m}from"./UWOFA6GV.js";import{c as d,f as B,g as p,i as E}from"./73N3TOJL.js";import{a as H}from"./XPFVT2EA.js";import{a as o}from"./5YS5V2LK.js";import{decodeEventLog as W,encodeFunctionData as G,getAddress as V,hashStruct as Y,isHex as J,parseAbi as Q,zeroAddress as k}from"viem";var Z="struct HookrSwapIntent { PoolKey key; bool zeroForOne; int128 amountSpecified; uint128 amountBound; uint160 sqrtPriceLimitX96; address recipient; address relayer; uint256 relayerFee; address engagement; uint256[] campaigns; uint256 nonce; uint256 deadline; }",I=Q(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }",Z,"function execute(HookrSwapIntent intent, address owner, bytes signature) returns (uint256 amountIn, uint256 amountOut)","function hashIntent(HookrSwapIntent intent) pure returns (bytes32)","function pullOf(HookrSwapIntent intent) view returns (address token, uint256 amount, bool feeFromInput)","function isNonceUsed(address owner, uint256 intentNonce) view returns (bool)","function router() view returns (address)","function registry() view returns (address)","function permit2() view returns (address)","event IntentExecuted(bytes32 indexed intentHash,address indexed owner,address indexed relayer,bytes32 poolId,uint256 amountIn,uint256 amountOut,uint256 relayerFee,bool feeFromInput)"]),ee={PoolKey:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],HookrSwapIntent:[{name:"key",type:"PoolKey"},{name:"zeroForOne",type:"bool"},{name:"amountSpecified",type:"int128"},{name:"amountBound",type:"uint128"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"recipient",type:"address"},{name:"relayer",type:"address"},{name:"relayerFee",type:"uint256"},{name:"engagement",type:"address"},{name:"campaigns",type:"uint256[]"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},ne=V("0x000000000022D473030F116dDEE9F6B43aC78BA3"),F={key:{type:"object",properties:{currency0:d,currency1:d,fee:{type:"integer"},tickSpacing:{type:"integer"},hooks:d},required:["currency0","currency1","fee","tickSpacing","hooks"],additionalProperties:!1},zeroForOne:{type:"boolean"},amountSpecified:{type:"string",pattern:"^-?[0-9]+$"},amountBound:m(),sqrtPriceLimitX96:m(),recipient:d,relayer:d,relayerFee:m(),engagement:d,campaigns:{type:"array",items:m(),maxItems:8},nonce:m(),deadline:m()},x={owner:d,signature:{type:"string",pattern:"^0x[0-9a-fA-F]+$"},intent:{type:"object",properties:F,required:Object.keys(F),additionalProperties:!1}};function D(t){return B(t,"Provide a complete trader-signed Hookr intent.")}function y(t,i=256,e=!1){if(typeof t!="string"||!/^-?\d+$/.test(t)||t.length>79)throw new o("Hookr intent amounts, nonce and deadline must be decimal base-unit strings.");let n=BigInt(t);if(e?n<=-(1n<<BigInt(i-1))||n>=1n<<BigInt(i-1):n<0n||n>=1n<<BigInt(i))throw new o("Hookr intent integer is outside its ABI range.");return n}function l(t){return E(t,"Provide valid Hookr intent addresses.")}function j(t,i){if(Object.keys(t).some(s=>!Object.hasOwn(x,s)))throw new o("Provide only owner, intent and the trader signature for Hookr relay.");let e=D(t.intent);if(Object.keys(e).some(s=>!Object.hasOwn(F,s)))throw new o("Hookr intent contains an undocumented field.");let n=D(e.key);if(Object.keys(n).some(s=>!["currency0","currency1","fee","tickSpacing","hooks"].includes(s))||typeof n.fee!="number"||!Number.isInteger(n.fee)||n.fee<0||n.fee>16777215||typeof n.tickSpacing!="number"||!Number.isInteger(n.tickSpacing)||n.tickSpacing<=0||n.tickSpacing>8388607||typeof e.zeroForOne!="boolean")throw new o("Provide a valid canonical v4 pool key and direction.");let a={currency0:l(n.currency0),currency1:l(n.currency1),fee:n.fee,tickSpacing:n.tickSpacing,hooks:l(n.hooks)};if(BigInt(a.currency0)>=BigInt(a.currency1))throw new o("Hookr pool currencies must sort strictly by address.");let r=l(t.owner);if(r===k||p(r,i))throw new o("Hookr relay requires another trader as owner; the relayer funds gas only.");if(!Array.isArray(e.campaigns)||e.campaigns.length>8)throw new o("Provide at most eight Hookr campaign IDs.");let c={key:a,zeroForOne:e.zeroForOne,amountSpecified:y(e.amountSpecified,128,!0),amountBound:y(e.amountBound,128),sqrtPriceLimitX96:y(e.sqrtPriceLimitX96,160),recipient:l(e.recipient),relayer:l(e.relayer),relayerFee:y(e.relayerFee),engagement:l(e.engagement),campaigns:e.campaigns.map(s=>y(s)),nonce:y(e.nonce),deadline:y(e.deadline)};if(c.amountSpecified===0n||c.amountBound===0n)throw new o("Hookr intent input/output amounts and bound must be nonzero.");if([k,h,v].some(s=>p(s,c.recipient)))throw new o("Hookr intent recipient is reserved.");if(c.relayer!==k&&!p(c.relayer,i)||c.relayer===k&&c.relayerFee!==0n)throw new o("Hookr intent names a different relayer or an open relay with a fee.");if(c.engagement===k!=(c.campaigns.length===0))throw new o("Hookr engagement and campaigns must be supplied together.");let f=c.zeroForOne?a.currency0:a.currency1;if(f===k)throw new o("Hookr Permit2 relay cannot pull native ETH input.");if(typeof t.signature!="string"||!J(t.signature,{strict:!0})||t.signature.length<4||t.signature.length%2!==0||t.signature.length>16386)throw new o("Provide the trader-signed Permit2 witness signature, never a private key.");let S=t.signature,w=Y({data:c,primaryType:"HookrSwapIntent",types:ee});return{owner:r,intent:c,signature:S,input:f,intentHash:w}}function q(t,i){let{owner:e,intent:n,signature:a}=j(t,i);return{chainId:H,to:h,value:"0",data:G({abi:I,functionName:"execute",args:[n,e,a]}),description:`Relay Hookr trader ${e} to recipient ${n.recipient}; relayer fee ${n.relayerFee} in pool quote currency. Relayer pays gas; owner supplies Permit2 funds.`}}function ce(t,i,e){let n=q(i,e);if(t.length!==1||t[0].chainId!==n.chainId||!p(t[0].to,n.to)||t[0].value!=="0"||!p(t[0].data,n.data))throw new o("Hookr relay calldata differs from the locally requested signed intent.")}function ue(t){return[{name:"hookr_relay",inputSchema:{type:"object",description:"Preview a trader-signed Permit2 swap for local human-confirmed submission. Relayer pays gas; the trader supplies input. No signature is created by this tool.",properties:x,required:Object.keys(x),additionalProperties:!1},execute:async(i,e)=>{let n=j(i,e),{owner:a,intent:r,signature:c,input:f,intentHash:S}=n,w=t.clientFor(H),s=await w.getBlock();if(typeof s.number!="bigint"||typeof s.timestamp!="bigint"||s.timestamp<=0n||s.timestamp>r.deadline)throw new o("Hookr signed intent expired or the chain timestamp is unavailable.");let g=(X,M=[])=>w.readContract({address:h,abi:I,functionName:X,args:M,blockNumber:s.number}),[_,u,z,K,$,U]=await Promise.all([g("hashIntent",[r]),g("pullOf",[r]),g("isNonceUsed",[a,r.nonce]),g("router"),g("registry"),g("permit2")]);if(_!==S||z!==!1||K!==v||$!==N||U!==ne)throw new o("Hookr intent hash, nonce or forwarder deployment is invalid. Ask the trader for a fresh signed intent.");if(!Array.isArray(u)||u.length!==3||typeof u[0]!="string"||!p(u[0],f)||typeof u[1]!="bigint"||typeof u[2]!="boolean")throw new o("Hookr Permit2 pull could not be verified.");let b=u[2],P=r.amountSpecified<0n?-r.amountSpecified:r.amountBound;if(u[1]!==P+(b?r.relayerFee:0n)||r.amountSpecified>0n&&!b&&r.relayerFee>r.amountSpecified)throw new o("Hookr Permit2 pull or output-side fee differs from the signed terms.");let C=await w.simulateContract({address:h,abi:I,functionName:"execute",args:[r,a,c],account:e,blockNumber:s.number}),[A,R]=C.result,T=r.amountSpecified<0n?r.amountBound:r.amountSpecified-(b?0n:r.relayerFee);if(A>P||R<T)throw new o("Hookr relay simulation did not satisfy the signed input/output bounds.");let O=[t.unsignedTx(q(i,e))],L=await t.preview(O,e);return{txs:O,preview:L,summary:O[0].description,intentHash:S,owner:a,recipient:r.recipient,relayer:e,inputToken:f,maximumPull:u[1].toString(),feeToken:b?f:r.zeroForOne?r.key.currency1:r.key.currency0,relayerFee:r.relayerFee.toString(),feeFromInput:b,minimumOutput:T.toString(),simulatedAmountIn:A.toString(),simulatedAmountOut:R.toString(),note:"Verify IntentExecuted in the receipt and your fee balance after submission."}}},{name:"hookr_relay_receipt",inputSchema:{type:"object",description:"Read the executed intent and fee from a mined Hookr relay receipt.",properties:{transactionHash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}},required:["transactionHash"],additionalProperties:!1},execute:async i=>{if(Object.keys(i).some(a=>a!=="transactionHash")||typeof i.transactionHash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(i.transactionHash))throw new o("Provide a Hookr relay transactionHash.");let e=await t.clientFor(H).getTransactionReceipt({hash:i.transactionHash});if(e.status!=="success")throw new o("Hookr relay reverted. No fee is proven paid.");let n=e.logs.filter(a=>p(a.address,h)).flatMap(a=>{try{let r=W({abi:I,eventName:"IntentExecuted",topics:a.topics,data:a.data});return[{...r.args,amountIn:r.args.amountIn.toString(),amountOut:r.args.amountOut.toString(),relayerFee:r.args.relayerFee.toString()}]}catch{return[]}});if(!n.length)throw new o("Receipt contains no verified Hookr IntentExecuted event.");return{chainId:H,transactionHash:e.transactionHash,blockNumber:e.blockNumber.toString(),intents:n,note:"Event evidence at this mined block; check balances and finality."}}}]}export{I as a,j as b,q as c,ce as d,ue as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as P,g as A,m as S}from"./
|
|
1
|
+
import{d as P,g as A,m as S}from"./R7D256HG.js";import{N as y,b as h}from"./ANQ43XJA.js";import{a as I,b as k,f as N,g as v}from"./64AF7ECA.js";import{a as b}from"./UWOFA6GV.js";import{c as w,g}from"./73N3TOJL.js";import{a as m}from"./XPFVT2EA.js";import{a as r}from"./5YS5V2LK.js";import{encodeFunctionData as f,parseAbi as T,zeroAddress as _}from"viem";var i=T(["function ownerOf(uint256) view returns (address)","function getApproved(uint256) view returns (address)","function getPositionLiquidity(uint256) view returns (uint128)","function safeTransferFrom(address from,address to,uint256 tokenId)","function approve(address spender,uint256 tokenId)","function burn(uint256 tokenId)"]),q={version:{type:"string",enum:["v3","v4"]},tokenId:b(),operation:{type:"string",enum:["transfer","approve","revoke","burn"]},target:w};function D(s){return{tools:[!1,!0].map(c=>({name:c?"uniswap_position_manage":"uniswap_position_status",inputSchema:{type:"object",additionalProperties:!1,required:c?["version","tokenId","operation"]:["version","tokenId"],properties:q},async execute(e,p){if(e.version!=="v3"&&e.version!=="v4")throw new r("Specify position version v3 or v4.");let o=I(e.tokenId,"tokenId"),a=e.version==="v3"?P.positionManager:h,d=s.clientFor(m),l=await d.readContract({address:a,abi:i,functionName:"ownerOf",args:[o]});if(!c){v(e,["version","tokenId"]);let n=await d.readContract({address:a,abi:i,functionName:"getApproved",args:[o]});return{version:e.version,tokenId:o.toString(),manager:a,owner:l,approved:n}}if(!g(l,p))throw new r("Only manage a Uniswap NFT owned by the signing wallet.");let t=e.operation;v(e,["version","tokenId","operation",...["transfer","approve"].includes(String(t))?["target"]:[]]);let u;if(t==="transfer"||t==="approve"){let n=k(e.target);if(n===_)throw new r("Choose a nonzero target, or operation revoke to clear approval.");u=t==="transfer"?f({abi:i,functionName:"safeTransferFrom",args:[p,n,o]}):f({abi:i,functionName:"approve",args:[n,o]})}else if(t==="revoke")u=f({abi:i,functionName:"approve",args:[_,o]});else if(t==="burn"){if(e.version==="v4"){if(await d.readContract({address:a,abi:i,functionName:"getPositionLiquidity",args:[o]})!==0n)throw new r("Remove all liquidity before burning an empty position.");return y(s).tools.find(O=>O.name==="uniswap_remove").execute({version:"v4",tokenId:o.toString(),liquidity:"all",amount0Min:"0",amount1Min:"0"},p)}let n=S(await d.readContract({address:a,abi:A,functionName:"positions",args:[o]}));if(n.liquidity!==0n||n.tokensOwed0!==0n||n.tokensOwed1!==0n)throw new r("Remove liquidity and collect all owed tokens before burning a v3 NFT.");u=f({abi:i,functionName:"burn",args:[o]})}else throw new r("Choose transfer, approve, revoke or burn. Operator-wide approvals are not exact approvals.");return N(s,[s.unsignedTx({to:a,data:u,value:"0",chainId:m,description:`${t} Uniswap ${e.version} NFT #${o}${e.target?` with target ${e.target}`:""}.`})],p,"Position ownership or exact per-NFT approval changes. A transferred position includes its liquidity and accrued rights; burn requires an empty NFT.")}}))}}export{i as a,D as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as _,e as oe,f as M,h as te,i as N}from"./JVTVOK6P.js";import{E as P,a as Z,b as J,c as v,f as C,h as b,m as A,q as x,s as Q,u as ee}from"./FL3EF72E.js";import{f as D,g as Y}from"./FYTF2QMS.js";import{a as $}from"./XCFA73P2.js";import{a as G}from"./6IM6A5VA.js";import{g as S}from"./73N3TOJL.js";import{a as w}from"./XPFVT2EA.js";import{a as k,b as X,d as j}from"./5YS5V2LK.js";import{decodeAbiParameters as fe,getAddress as y,pad as se,parseAbi as ae,parseAbiParameters as me,toEventSelector as he,toHex as ne,zeroAddress as de}from"viem";var ge=he("Initialize(bytes32,address,address,uint24,int24,address,uint160,int24)"),ke=me("uint24 fee, int24 tickSpacing, address hooks, uint160 sqrtPriceX96, int24 tick"),V=10000000n,ce=25,H=200,L=16,we=3e3,Pe=500,ye=500n,E=100,B=ae(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),be=ae(["function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)"]);function Ae(o){let e=o.trim().toLowerCase();return e==="eth"||e==="native"||e===de||e===$.toLowerCase()}function ie(o,e){if(o!=null){if(typeof o!="string")throw new k(`${e} must be a token address, or "eth" for native ETH.`);return Ae(o)?{eth:!0}:(G(o),{eth:!1,address:y(o)})}}var le=(o,e)=>BigInt(o)<BigInt(e)?-1:BigInt(o)>BigInt(e)?1:0;function T(o){return{address:o.address,symbol:o.symbol,decimals:o.decimals}}async function ue(o,e,r,i,d){let[t,n,u]=await Promise.all([o.readContract({address:e,abi:N,functionName:"slot0"}),o.readContract({address:e,abi:N,functionName:"liquidity"}),o.readContract({address:e,abi:N,functionName:"tickSpacing"})]),s=BigInt(t[0]);return{version:"v3",id:e,token0:T(r),token1:T(i),fee:d,tickSpacing:Number(u),initialized:s>0n,liquidity:BigInt(n).toString(),sqrtPriceX96:s.toString(),tick:Number(t[1]),price:s>0n?D(s,r.decimals,i.decimals):"0",addSupported:!0}}async function q(o,e,r){let i=r??Q(e),[d,t]=await Promise.all([P(o,e.currency0,w),P(o,e.currency1,w)]),[n,u]=await Promise.all([o.readContract({address:v,abi:B,functionName:"getSlot0",args:[i]}),o.readContract({address:v,abi:B,functionName:"getLiquidity",args:[i]})]),s=BigInt(n[0]),m=ee(e,Number(n[3]));return{version:"v4",id:i,token0:T(d),token1:T(t),fee:e.fee,tickSpacing:e.tickSpacing,hooks:y(e.hooks),initialized:s>0n,liquidity:BigInt(u).toString(),sqrtPriceX96:s.toString(),tick:Number(n[1]),price:s>0n?D(s,d.decimals,t.decimals):"0",addSupported:x.has(e.hooks.toLowerCase()),feeNote:m.feeNote,...x.has(e.hooks.toLowerCase())?{}:{note:`Hook ${y(e.hooks)} is not one Oak has measured, so uniswap_add will refuse this pool.`}}}async function Ie(o,e,r){let i=await o.getBlockNumber(),d=new Map;for(let t=0n;t<=i;t+=V){let n=t+V-1n<i?t+V-1n:i,u=await o.request({method:"eth_getLogs",params:[{address:Z.toLowerCase(),topics:[ge,null,e?se(e):null,r?se(r):null],fromBlock:ne(t),toBlock:ne(n)}]});if(!Array.isArray(u))throw new k("Invalid v4 Initialize log response.");for(let s of u){if(!Array.isArray(s.topics)||s.topics.length!==4||typeof s.data!="string")throw new k("Invalid v4 Initialize log.");let[m,a,p]=fe(ke,s.data),h={currency0:y(`0x${s.topics[2].slice(-40)}`),currency1:y(`0x${s.topics[3].slice(-40)}`),fee:Number(m),tickSpacing:Number(a),hooks:y(p)};d.set(s.topics[1].toLowerCase(),{key:h,id:s.topics[1]})}}return[...d.values()]}async function ve(o,e,r){let i=e.eth?_.weth:e.address,d=r.eth?_.weth:r.address;if(i===d)return[];let[t,n]=le(i,d)<0?[i,d]:[d,i],[u,s]=await Promise.all([P(o,t,w),P(o,n,w)]),m=[];for(let a of Object.keys(oe).map(Number)){let p=y(String(await o.readContract({address:_.factory,abi:te,functionName:"getPool",args:[t,n,a]})));p!==de&&m.push(await ue(o,p,u,s,a))}return m}function re(o){return o?o.eth?[b,C]:o.address===C?[C,b]:[o.address]:null}async function Ce(o,e){let r=new Map;if(e.length===0)return r;if(typeof o.multicall=="function"&&o.chain?.contracts?.multicall3)try{return(await o.multicall({allowFailure:!0,contracts:e.map(d=>({address:v,abi:B,functionName:"getLiquidity",args:[d]}))})).forEach((d,t)=>r.set(e[t].toLowerCase(),d.status==="success"?BigInt(d.result):0n)),r}catch{}for(let i=0;i<e.length;i+=L)(await Promise.allSettled(e.slice(i,i+L).map(async t=>BigInt(await o.readContract({address:v,abi:B,functionName:"getLiquidity",args:[t]}))))).forEach((t,n)=>r.set(e[i+n].toLowerCase(),t.status==="fulfilled"?t.value:0n));return r}async function Se(o,e,r,i){let d=re(e),t=re(r),n=new Map,u=(c,f)=>{if(c&&f){if(c===f)return;let[l,g]=le(c,f)<0?[c,f]:[f,c];n.set(`${l}/${g}`,[l,g])}else if(c||f){let l=c??f;n.set(`${l}/*0`,[l,null]),n.set(`${l}/*1`,[null,l])}};for(let c of d??[null])for(let f of t??[null])u(c,f);let s=new Map;for(let c of A)[...n.values()].some(([l,g])=>(!l||S(c.key.currency0,l))&&(!g||S(c.key.currency1,g)))&&s.set(c.poolId.toLowerCase(),{key:c.key,id:c.poolId});for(let[c,f]of n.values())for(let l of await Ie(o,c,f))s.set(l.id.toLowerCase(),l);let m=new Set(A.map(c=>c.poolId.toLowerCase())),a=[...s.values()],p=a.filter(c=>m.has(c.id.toLowerCase())),h=a.filter(c=>!m.has(c.id.toLowerCase())).reverse(),I=typeof o.multicall=="function"&&!!o.chain?.contracts?.multicall3?we:Pe;h.length>I&&i.push(`${h.length} v4 pools match; only the newest ${I} non-measured ones were considered. Pass both tokens, or a poolId, to narrow.`);let U=h.slice(0,I),z=await Ce(o,U.map(c=>c.id)),pe=U.sort((c,f)=>{let l=z.get(c.id.toLowerCase())??0n,g=z.get(f.id.toLowerCase())??0n;return l===g?0:l<g?1:-1}),R=[...p,...pe];R.length>H&&i.push(`${R.length} v4 pools match; full state was read for Oak's measured pools plus the deepest of the rest (${H} total). Pass both tokens, or a poolId, to narrow.`);let K=[],O=0,W=R.slice(0,H);for(let c=0;c<W.length;c+=L){let f=await Promise.allSettled(W.slice(c,c+L).map(({key:l,id:g})=>q(o,l,g)));for(let l of f)l.status==="fulfilled"?K.push(l.value):O++}return O>0&&i.push(`${O} pool(s) were skipped because a token or pool state could not be read.`),K}async function _e(o,e){let r=A.find(s=>S(s.poolId,e));if(r)return q(o,r.key,r.poolId);let[i,d,t,n,u]=await o.readContract({address:J,abi:be,functionName:"poolKeys",args:[e.slice(0,52)]});if(i===b&&d===b&&Number(n)===0)throw new k(`No Uniswap v4 pool ${e} is known to the PositionManager (no position was ever minted in it, or it is not initialized). Search by token pair instead.`);return q(o,{currency0:i,currency1:d,fee:Number(t),tickSpacing:Number(n),hooks:u},e)}function Ne(o){let e=new Set([...A.map(t=>t.poolId.toLowerCase()),...M.map(t=>t.address.toLowerCase())]),r=new Set([b,$.toLowerCase(),C.toLowerCase()]),i=t=>r.has(t.address.toLowerCase())?"ETH":t.address.toLowerCase(),d=new Map;for(let t of o.filter(n=>n.initialized&&BigInt(n.liquidity)>0n)){let n=`${i(t.token0)}/${i(t.token1)}`;d.set(n,[...d.get(n)??[],t])}for(let t of d.values()){let n=t.filter(a=>e.has(a.id.toLowerCase()));if(n.length===0&&t.length<3)continue;let s=(n.length>0?n:t).map(a=>BigInt(a.sqrtPriceX96)).sort((a,p)=>a<p?-1:a>p?1:0),m=s[Math.floor(s.length/2)];for(let a of t){if(e.has(a.id.toLowerCase()))continue;let p=Y(BigInt(a.sqrtPriceX96),m);p>ye&&(a.priceOutlierBps=Number(p),a.note=`${a.note?`${a.note} `:""}Price differs ${p} bps from the ${n.length>0?"Oak-measured":"median"} price for this pair; do not treat this pool as the market price.`)}}}async function Ee(o,e){let r=e.version;if(r!==void 0&&r!=="v3"&&r!=="v4")throw new k('version must be "v3" or "v4"; omit it to search both.');let i=e.limit===void 0?ce:Number(e.limit);if(!Number.isInteger(i)||i<1||i>E)throw new k(`limit must be an integer from 1 to ${E}.`);let d=ie(e.tokenA,"tokenA"),t=ie(e.tokenB,"tokenB");if(!d&&t)throw new k("Provide tokenA when searching by token; tokenB narrows the search to a pair.");let n=o.clientFor(w),u=[],s=[];if(e.poolId!==void 0){if(typeof e.poolId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.poolId))throw new k("poolId must be a 32-byte hex v4 poolId. For v3 search by tokenA/tokenB.");s=[await _e(n,e.poolId)]}else if(d){if(r!=="v4"&&(t?s.push(...await ve(n,d,t)):u.push("v3 pools are looked up per pair; pass tokenB to include them.")),r!=="v3")try{s.push(...await Se(n,d,t,u))}catch(a){throw X(a,-32601)?a:new k(`Could not search v4 pools. ${j(a)}`)}}else{u.push("No token filter given: showing the pools Oak has measured. Pass tokenA (and tokenB) to search the chain for every pool of a pair.");let a=await Promise.all(M.map(async h=>{let[F,I]=await Promise.all([P(n,h.token0,w),P(n,h.token1,w)]);return ue(n,h.address,F,I,h.fee)})),p=await Promise.all(A.map(h=>q(n,h.key,h.poolId)));s=[...r==="v4"?[]:a,...r==="v3"?[]:p]}Ne(s),s.sort((a,p)=>BigInt(p.liquidity)>BigInt(a.liquidity)?1:BigInt(p.liquidity)<BigInt(a.liquidity)?-1:0),s.length>i&&u.push(`Showing the ${i} deepest of ${s.length} pools found; raise limit (max ${E}) to see more.`),s=s.slice(0,i);let m=s.filter(a=>a.initialized&&BigInt(a.liquidity)>0n).length;return s.length===0&&u.push("No pool exists for this pair. Create one with uniswap_create_pool, or create it and add the first liquidity together with uniswap_add plus initialPrice."),{pools:s,notes:u,summary:`Found ${s.length} Uniswap pool(s), ${m} with active liquidity. price is token1 per 1 token0.`}}function Me(o){return{tools:[{name:"uniswap_pools",inputSchema:{type:"object",description:"Read-only pool discovery on Robinhood Chain (4663): every Uniswap v3 and v4 pool for a token pair with fee, tick spacing, hook, liquidity and price, or one v4 pool by poolId. No tokens given: the measured pools.",properties:{version:{type:"string",enum:["v3","v4"],description:"Limit to one version; omit to search both."},tokenA:{type:"string",description:'Token address, or "eth" for native ETH (searches v3 WETH and v4 native/WETH pools).'},tokenB:{type:"string",description:"Second token of the pair. Required for v3 lookups."},poolId:{type:"string",description:"32-byte v4 poolId to inspect."},limit:{type:"integer",minimum:1,maximum:E,default:ce}}},execute:async r=>Ee(o,r)}]}}export{Ee as a,Me as b};
|
|
1
|
+
import{d as _,e as oe,f as M,h as te,i as N}from"./R7D256HG.js";import{E as P,a as Z,b as J,c as v,f as C,h as b,m as A,q as x,s as Q,u as ee}from"./ANQ43XJA.js";import{f as D,g as Y}from"./3ACEWCKZ.js";import{a as $}from"./VJ3W2V3B.js";import{a as G}from"./6IM6A5VA.js";import{g as S}from"./73N3TOJL.js";import{a as w}from"./XPFVT2EA.js";import{a as k,b as X,d as j}from"./5YS5V2LK.js";import{decodeAbiParameters as fe,getAddress as y,pad as se,parseAbi as ae,parseAbiParameters as me,toEventSelector as he,toHex as ne,zeroAddress as de}from"viem";var ge=he("Initialize(bytes32,address,address,uint24,int24,address,uint160,int24)"),ke=me("uint24 fee, int24 tickSpacing, address hooks, uint160 sqrtPriceX96, int24 tick"),V=10000000n,ce=25,H=200,L=16,we=3e3,Pe=500,ye=500n,E=100,B=ae(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),be=ae(["function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)"]);function Ae(o){let e=o.trim().toLowerCase();return e==="eth"||e==="native"||e===de||e===$.toLowerCase()}function ie(o,e){if(o!=null){if(typeof o!="string")throw new k(`${e} must be a token address, or "eth" for native ETH.`);return Ae(o)?{eth:!0}:(G(o),{eth:!1,address:y(o)})}}var le=(o,e)=>BigInt(o)<BigInt(e)?-1:BigInt(o)>BigInt(e)?1:0;function T(o){return{address:o.address,symbol:o.symbol,decimals:o.decimals}}async function ue(o,e,r,i,d){let[t,n,u]=await Promise.all([o.readContract({address:e,abi:N,functionName:"slot0"}),o.readContract({address:e,abi:N,functionName:"liquidity"}),o.readContract({address:e,abi:N,functionName:"tickSpacing"})]),s=BigInt(t[0]);return{version:"v3",id:e,token0:T(r),token1:T(i),fee:d,tickSpacing:Number(u),initialized:s>0n,liquidity:BigInt(n).toString(),sqrtPriceX96:s.toString(),tick:Number(t[1]),price:s>0n?D(s,r.decimals,i.decimals):"0",addSupported:!0}}async function q(o,e,r){let i=r??Q(e),[d,t]=await Promise.all([P(o,e.currency0,w),P(o,e.currency1,w)]),[n,u]=await Promise.all([o.readContract({address:v,abi:B,functionName:"getSlot0",args:[i]}),o.readContract({address:v,abi:B,functionName:"getLiquidity",args:[i]})]),s=BigInt(n[0]),m=ee(e,Number(n[3]));return{version:"v4",id:i,token0:T(d),token1:T(t),fee:e.fee,tickSpacing:e.tickSpacing,hooks:y(e.hooks),initialized:s>0n,liquidity:BigInt(u).toString(),sqrtPriceX96:s.toString(),tick:Number(n[1]),price:s>0n?D(s,d.decimals,t.decimals):"0",addSupported:x.has(e.hooks.toLowerCase()),feeNote:m.feeNote,...x.has(e.hooks.toLowerCase())?{}:{note:`Hook ${y(e.hooks)} is not one Oak has measured, so uniswap_add will refuse this pool.`}}}async function Ie(o,e,r){let i=await o.getBlockNumber(),d=new Map;for(let t=0n;t<=i;t+=V){let n=t+V-1n<i?t+V-1n:i,u=await o.request({method:"eth_getLogs",params:[{address:Z.toLowerCase(),topics:[ge,null,e?se(e):null,r?se(r):null],fromBlock:ne(t),toBlock:ne(n)}]});if(!Array.isArray(u))throw new k("Invalid v4 Initialize log response.");for(let s of u){if(!Array.isArray(s.topics)||s.topics.length!==4||typeof s.data!="string")throw new k("Invalid v4 Initialize log.");let[m,a,p]=fe(ke,s.data),h={currency0:y(`0x${s.topics[2].slice(-40)}`),currency1:y(`0x${s.topics[3].slice(-40)}`),fee:Number(m),tickSpacing:Number(a),hooks:y(p)};d.set(s.topics[1].toLowerCase(),{key:h,id:s.topics[1]})}}return[...d.values()]}async function ve(o,e,r){let i=e.eth?_.weth:e.address,d=r.eth?_.weth:r.address;if(i===d)return[];let[t,n]=le(i,d)<0?[i,d]:[d,i],[u,s]=await Promise.all([P(o,t,w),P(o,n,w)]),m=[];for(let a of Object.keys(oe).map(Number)){let p=y(String(await o.readContract({address:_.factory,abi:te,functionName:"getPool",args:[t,n,a]})));p!==de&&m.push(await ue(o,p,u,s,a))}return m}function re(o){return o?o.eth?[b,C]:o.address===C?[C,b]:[o.address]:null}async function Ce(o,e){let r=new Map;if(e.length===0)return r;if(typeof o.multicall=="function"&&o.chain?.contracts?.multicall3)try{return(await o.multicall({allowFailure:!0,contracts:e.map(d=>({address:v,abi:B,functionName:"getLiquidity",args:[d]}))})).forEach((d,t)=>r.set(e[t].toLowerCase(),d.status==="success"?BigInt(d.result):0n)),r}catch{}for(let i=0;i<e.length;i+=L)(await Promise.allSettled(e.slice(i,i+L).map(async t=>BigInt(await o.readContract({address:v,abi:B,functionName:"getLiquidity",args:[t]}))))).forEach((t,n)=>r.set(e[i+n].toLowerCase(),t.status==="fulfilled"?t.value:0n));return r}async function Se(o,e,r,i){let d=re(e),t=re(r),n=new Map,u=(c,f)=>{if(c&&f){if(c===f)return;let[l,g]=le(c,f)<0?[c,f]:[f,c];n.set(`${l}/${g}`,[l,g])}else if(c||f){let l=c??f;n.set(`${l}/*0`,[l,null]),n.set(`${l}/*1`,[null,l])}};for(let c of d??[null])for(let f of t??[null])u(c,f);let s=new Map;for(let c of A)[...n.values()].some(([l,g])=>(!l||S(c.key.currency0,l))&&(!g||S(c.key.currency1,g)))&&s.set(c.poolId.toLowerCase(),{key:c.key,id:c.poolId});for(let[c,f]of n.values())for(let l of await Ie(o,c,f))s.set(l.id.toLowerCase(),l);let m=new Set(A.map(c=>c.poolId.toLowerCase())),a=[...s.values()],p=a.filter(c=>m.has(c.id.toLowerCase())),h=a.filter(c=>!m.has(c.id.toLowerCase())).reverse(),I=typeof o.multicall=="function"&&!!o.chain?.contracts?.multicall3?we:Pe;h.length>I&&i.push(`${h.length} v4 pools match; only the newest ${I} non-measured ones were considered. Pass both tokens, or a poolId, to narrow.`);let U=h.slice(0,I),z=await Ce(o,U.map(c=>c.id)),pe=U.sort((c,f)=>{let l=z.get(c.id.toLowerCase())??0n,g=z.get(f.id.toLowerCase())??0n;return l===g?0:l<g?1:-1}),R=[...p,...pe];R.length>H&&i.push(`${R.length} v4 pools match; full state was read for Oak's measured pools plus the deepest of the rest (${H} total). Pass both tokens, or a poolId, to narrow.`);let K=[],O=0,W=R.slice(0,H);for(let c=0;c<W.length;c+=L){let f=await Promise.allSettled(W.slice(c,c+L).map(({key:l,id:g})=>q(o,l,g)));for(let l of f)l.status==="fulfilled"?K.push(l.value):O++}return O>0&&i.push(`${O} pool(s) were skipped because a token or pool state could not be read.`),K}async function _e(o,e){let r=A.find(s=>S(s.poolId,e));if(r)return q(o,r.key,r.poolId);let[i,d,t,n,u]=await o.readContract({address:J,abi:be,functionName:"poolKeys",args:[e.slice(0,52)]});if(i===b&&d===b&&Number(n)===0)throw new k(`No Uniswap v4 pool ${e} is known to the PositionManager (no position was ever minted in it, or it is not initialized). Search by token pair instead.`);return q(o,{currency0:i,currency1:d,fee:Number(t),tickSpacing:Number(n),hooks:u},e)}function Ne(o){let e=new Set([...A.map(t=>t.poolId.toLowerCase()),...M.map(t=>t.address.toLowerCase())]),r=new Set([b,$.toLowerCase(),C.toLowerCase()]),i=t=>r.has(t.address.toLowerCase())?"ETH":t.address.toLowerCase(),d=new Map;for(let t of o.filter(n=>n.initialized&&BigInt(n.liquidity)>0n)){let n=`${i(t.token0)}/${i(t.token1)}`;d.set(n,[...d.get(n)??[],t])}for(let t of d.values()){let n=t.filter(a=>e.has(a.id.toLowerCase()));if(n.length===0&&t.length<3)continue;let s=(n.length>0?n:t).map(a=>BigInt(a.sqrtPriceX96)).sort((a,p)=>a<p?-1:a>p?1:0),m=s[Math.floor(s.length/2)];for(let a of t){if(e.has(a.id.toLowerCase()))continue;let p=Y(BigInt(a.sqrtPriceX96),m);p>ye&&(a.priceOutlierBps=Number(p),a.note=`${a.note?`${a.note} `:""}Price differs ${p} bps from the ${n.length>0?"Oak-measured":"median"} price for this pair; do not treat this pool as the market price.`)}}}async function Ee(o,e){let r=e.version;if(r!==void 0&&r!=="v3"&&r!=="v4")throw new k('version must be "v3" or "v4"; omit it to search both.');let i=e.limit===void 0?ce:Number(e.limit);if(!Number.isInteger(i)||i<1||i>E)throw new k(`limit must be an integer from 1 to ${E}.`);let d=ie(e.tokenA,"tokenA"),t=ie(e.tokenB,"tokenB");if(!d&&t)throw new k("Provide tokenA when searching by token; tokenB narrows the search to a pair.");let n=o.clientFor(w),u=[],s=[];if(e.poolId!==void 0){if(typeof e.poolId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.poolId))throw new k("poolId must be a 32-byte hex v4 poolId. For v3 search by tokenA/tokenB.");s=[await _e(n,e.poolId)]}else if(d){if(r!=="v4"&&(t?s.push(...await ve(n,d,t)):u.push("v3 pools are looked up per pair; pass tokenB to include them.")),r!=="v3")try{s.push(...await Se(n,d,t,u))}catch(a){throw X(a,-32601)?a:new k(`Could not search v4 pools. ${j(a)}`)}}else{u.push("No token filter given: showing the pools Oak has measured. Pass tokenA (and tokenB) to search the chain for every pool of a pair.");let a=await Promise.all(M.map(async h=>{let[F,I]=await Promise.all([P(n,h.token0,w),P(n,h.token1,w)]);return ue(n,h.address,F,I,h.fee)})),p=await Promise.all(A.map(h=>q(n,h.key,h.poolId)));s=[...r==="v4"?[]:a,...r==="v3"?[]:p]}Ne(s),s.sort((a,p)=>BigInt(p.liquidity)>BigInt(a.liquidity)?1:BigInt(p.liquidity)<BigInt(a.liquidity)?-1:0),s.length>i&&u.push(`Showing the ${i} deepest of ${s.length} pools found; raise limit (max ${E}) to see more.`),s=s.slice(0,i);let m=s.filter(a=>a.initialized&&BigInt(a.liquidity)>0n).length;return s.length===0&&u.push("No pool exists for this pair. Create one with uniswap_create_pool, or create it and add the first liquidity together with uniswap_add plus initialPrice."),{pools:s,notes:u,summary:`Found ${s.length} Uniswap pool(s), ${m} with active liquidity. price is token1 per 1 token0.`}}function Me(o){return{tools:[{name:"uniswap_pools",inputSchema:{type:"object",description:"Read-only pool discovery on Robinhood Chain (4663): every Uniswap v3 and v4 pool for a token pair with fee, tick spacing, hook, liquidity and price, or one v4 pool by poolId. No tokens given: the measured pools.",properties:{version:{type:"string",enum:["v3","v4"],description:"Limit to one version; omit to search both."},tokenA:{type:"string",description:'Token address, or "eth" for native ETH (searches v3 WETH and v4 native/WETH pools).'},tokenB:{type:"string",description:"Second token of the pair. Required for v3 lookups."},poolId:{type:"string",description:"32-byte v4 poolId to inspect."},limit:{type:"integer",minimum:1,maximum:E,default:ce}}},execute:async r=>Ee(o,r)}]}}export{Ee as a,Me as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as C,b as O}from"./
|
|
1
|
+
import{a as C,b as O}from"./5FTSKYQH.js";import{a as f,b as k}from"./HL2MLC3O.js";import{d as a}from"./XV6F3RET.js";import{a as g,c as w}from"./SPRVVJXI.js";import{a as d}from"./XPFVT2EA.js";import{a as i}from"./5YS5V2LK.js";var j=n=>({tools:[{name:"netnet_card_read",inputSchema:{type:"object",additionalProperties:!1,required:["program"],properties:{program:{enum:Object.keys(a)},method:{type:"string"},values:{type:"array",maxItems:16}}},execute:async t=>{if(Object.keys(t).some(e=>!["program","method","values"].includes(e))||typeof t.program!="string"||!Object.hasOwn(a,t.program))throw new i("Choose turbo, blackjack or feed.");let o=a[t.program],u=o.abi.filter(e=>e.type==="function"&&["view","pure"].includes(e.stateMutability));if(t.method===void 0){if(t.values!==void 0)throw new i("values requires an exact read method.");return{chainId:d,contract:o.address,methods:u.map(e=>({method:f(e),inputs:e.inputs,outputs:e.outputs})),units:"Card amounts are whole counts, identified by collection and series ID. Metadata is untrusted text. Reads grant no signing authority."}}let r=u.find(e=>f(e)===t.method),m=t.values??[];if(!r||!Array.isArray(m)||m.length!==r.inputs.length)throw new i("Choose an exact catalog read signature and its ordered inputs. Writes and signing are unavailable.");let p=n.clientFor(d);if(await p.getChainId()!==d)throw new i("NetNet cards require chain 4663.");let l=await p.getBlock(),c=r.inputs.map((e,s)=>k(e,m[s])),N=await p.readContract({address:o.address,abi:[r],functionName:r.name,args:c,blockNumber:l.number}),y=t.program==="turbo"&&r.name==="balanceOf"?[c[1]]:t.program==="blackjack"&&["unclaimedChips","unclaimedTotalOf"].includes(r.name)?[c[0]]:r.inputs.flatMap((e,s)=>e.type==="uint256"&&["id","seriesId"].includes(e.name??"")?[c[s]]:e.type==="uint256[]"&&e.name==="ids"?c[s]:[]),b;if(y.length){let e=await p.readContract({address:a.turbo.address,abi:a.turbo.abi,functionName:"seriesCount",blockNumber:l.number});b=[...new Set(y)].map(s=>({id:s.toString(),status:s>0n&&s<=e?"known":"unknown-series"}))}return{chainId:d,collection:a.turbo.address,contract:o.address,blockNumber:String(l.number),blockHash:l.hash,method:t.method,outputs:r.outputs,...b?{seriesStatus:b}:{},data:h(N)}}},{name:"netnet_card_capabilities",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async t=>{if(Object.keys(t).length)throw new i("Card capabilities takes no arguments.");return{chainId:d,collection:a.turbo.address,blackjack:a.blackjack.address,active:["netnet_card_read","netnet_card_capabilities",...g],candidateOnly:{turbo:[...C,...O],recovery:[]},activation:"Only self-only finalize, expire and parked-chip claim are enabled, with local human confirmation and durable recovery. TURBO writes, seating, channel signatures and collection approvals remain disabled.",refused:w}}}]});function h(n,t=0){if(t>12)throw new i("Card read result exceeds the supported nesting.");if(typeof n=="bigint")return n.toString();if(typeof n=="string"){if(n.length>8194)throw new i("Card read result exceeds the supported length.");return/^0x[0-9a-f]*$/i.test(n)?n:`untrusted ${JSON.stringify(n)}`}if(Array.isArray(n)){if(n.length>4096)throw new i("Choose a bounded card read.");return n.map(o=>h(o,t+1))}return n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([o,u])=>[o,h(u,t+1)])):n}export{j as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as g,d as H,m as M}from"./
|
|
1
|
+
import{c as g,d as H,m as M}from"./7Z5IM2QZ.js";import{d,e as s,y as C}from"./ANQ43XJA.js";import{f as _,g as k}from"./64AF7ECA.js";import{g as h}from"./73N3TOJL.js";import{a as w}from"./XPFVT2EA.js";import{a as t}from"./5YS5V2LK.js";import{decodeFunctionData as b,encodeFunctionData as B,erc20Abi as $,getAddress as O}from"viem";function K(u){return{tools:[{name:"uniswap_swap_batch",inputSchema:{type:"object",additionalProperties:!1,required:["routes"],properties:{routes:{type:"array",minItems:1,maxItems:20,items:{type:"object",description:"Complete uniswap_swap arguments, including an absolute minAmountOut or maxAmountIn."}}}},async execute(n,v){if(k(n,["routes"]),!Array.isArray(n.routes)||n.routes.length<1||n.routes.length>20)throw new t("Provide 1 to 20 explicit bounded Uniswap routes.");let c=new Map,i="0x",A=0n,a,m=[],y=new Set;for(let e of n.routes){if(!e||typeof e!="object"||Array.isArray(e))throw new t("Each route must contain uniswap_swap arguments.");let I=await M(u,e,v,!1);if(!("txs"in I))throw new t("Route did not build swap transactions.");let E=I.txs;for(let r of E.slice(0,-1))if(h(r.to,d)){let[o,D,N,S]=b({abi:H,data:r.data}).args;if(D!==s)throw new t("Unexpected route approval spender.");let T=o.toLowerCase(),p=c.get(T),U=(p?.amount??0n)+N;if(U>=1n<<160n)throw new t("Combined input approvals exceed uint160.");c.set(T,{token:o,amount:U,expiration:p&&p.expiration<BigInt(S)?p.expiration:BigInt(S)})}else{let o=b({abi:$,data:r.data});if(o.functionName!=="approve"||!h(o.args[0],d))throw new t("Unexpected route prerequisite.")}let f=E.at(-1);if(f.to!==s)throw new t("Route does not use the pinned Universal Router.");A+=BigInt(f.value);let[j,x,P]=b({abi:g,data:f.data}).args,R=j.slice(2).match(/../g)??[];if(R.length!==x.length)throw new t("Unexpected route command/parameter count.");R.forEach((r,o)=>{r==="04"?y.add(x[o]):(i=`${i}${r}`,m.push(x[o]))}),a=a===void 0||P<a?P:a}for(let e of y)i=`${i}04`,m.push(e);let l=[];for(let e of c.values())l.push(u.approval(O(e.token),d,e.amount.toString(),w),C(e.token,s,e.amount.toString(),e.expiration.toString()));return l.push(u.unsignedTx({to:s,data:B({abi:g,functionName:"execute",args:[i,m,a]}),value:A.toString(),chainId:w,description:`Atomically execute ${n.routes.length} caller-selected v2/v3/v4 routes, preserving each route's trade bound.`})),_(u,l,v,"Explicit mixed-version/split routes; every route must meet its own bound. No automatic best-route search or allow-revert branch. The wallet must fund each independently previewed route.")}}]}}export{K as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as H,o as q}from"./EAEQOS7Y.js";import{a as de,b as ce,c as le}from"./HFQS5344.js";import{a as ae}from"./G7UKNO2I.js";import{a as ue,b as me}from"./BYXBS45D.js";import{a as pe}from"./GZ5TW3WB.js";import{e as U,h as B,m as re}from"./5EHQM6DM.js";import{b as ie}from"./AXYOJBX6.js";import{c as se}from"./MYBDO5SA.js";import{c as M,e as x,g as w,k as ee,l as ne,m as te,n as oe}from"./73N3TOJL.js";import{a as h,i as Y}from"./XPFVT2EA.js";import{a as E}from"./EG6M6SSO.js";import{a as s}from"./5YS5V2LK.js";import{decodeFunctionResult as Ce,encodeAbiParameters as F,encodeFunctionData as N,erc20Abi as V,isAddress as Ie,parseAbi as we,parseAbiParameters as j,toHex as J,zeroAddress as W}from"viem";var k=Y[h].clanker,fe=we(["function deployToken(((address tokenAdmin,string name,string symbol,bytes32 salt,string image,string metadata,string context,uint256 originatingChainId) tokenConfig,(address hook,address pairedToken,int24 tickIfToken0IsClanker,int24 tickSpacing,bytes poolData) poolConfig,(address locker,address[] rewardAdmins,address[] rewardRecipients,uint16[] rewardBps,int24[] tickLower,int24[] tickUpper,uint16[] positionBps,bytes lockerData) lockerConfig,(address mevModule,bytes mevModuleData) mevModuleConfig,(address extension,uint256 msgValue,uint16 extensionBps,bytes extensionData)[] extensionConfigs) config) payable returns (address)","function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),C=we(["function availableFees(address,address) view returns (uint256)","function claim(address,address)","function collectRewards(address)","function mevModuleEnabled(bytes32) view returns (bool)","function mevModuleOperational(bytes32) returns (bool)"]),I={address:k.paired_weth.address,symbol:"WETH",decimals:18,chainId:h},Pe="https://www.clanker.world/api/tokens",ye={type:"string",pattern:"^\\d+$"},he={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"};function P(n){return ne(ee(n,U),U)}function ge(n,t){if(typeof n!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n))throw new s(`Provide an explicit bytes32 ${t}.`);return n}function T(n,t,a=!1){if(n===void 0&&!a)return"";if(typeof n!="string"||a&&!n.trim())throw new s(`Provide ${t} as text.`);return n}function z(n,t=256){return oe(n,`Amount exceeds the uint${t} range.`,{bits:t})}function G(n){return te(n,"The contract returned an invalid amount.").toString()}function O(n,t){let a=Object.keys(n).find(p=>!t.includes(p));if(a)throw new s(`Unsupported Clanker input: ${a}.`)}function be(n,t){return t.changes.map(({token:a,amount:p})=>{let b=p.startsWith("-");return`${b?"-":"+"}${n.formatAmount(b?p.slice(1):p,a.decimals)} ${a.symbol} (${a.address}, chain ${a.chainId})`}).join("; ")}function Te(n){return x(n)&&Array.isArray(n.data)&&Number.isSafeInteger(n.total)&&Number(n.total)>=0&&Number.isSafeInteger(n.tokensDeployed)&&Number(n.tokensDeployed)>=0&&(n.cursor===null||typeof n.cursor=="string"||n.cursor===void 0&&n.data.length===0&&n.total===0&&n.tokensDeployed===0)&&n.data.every(t=>x(t)&&typeof t.name=="string"&&typeof t.symbol=="string"&&Number.isSafeInteger(t.chain_id)&&["contract_address","admin","msg_sender","factory_address"].every(a=>typeof t[a]=="string"&&Ie(t[a],{strict:!1})))}async function ve(n,t={}){O(t,["q","limit","cursor","deployer"]);let a=t.limit??10;if(typeof a!="number"||!Number.isInteger(a)||a<1||a>20)throw new s("Choose an indexer limit from 1 to 20.");let p=new URL(Pe);p.searchParams.set("chainId",String(h)),p.searchParams.set("limit",String(a)),t.q!==void 0&&p.searchParams.set("q",T(t.q,"search")),t.cursor!==void 0&&p.searchParams.set("cursor",T(t.cursor,"cursor",!0)),t.deployer!==void 0&&p.searchParams.set("msgSender",P(t.deployer));let b=await se(n.http,p.toString(),{headers:{"User-Agent":"Oak-Clanker/1.0"}},Te);return{tokens:b.data.filter(v=>v.chain_id===h&&w(v.factory_address,k.factory.address)),total:b.total,cursor:b.cursor||null,tokensDeployed:b.tokensDeployed}}var Se=n=>{let t=()=>n.clientFor(h),a=async e=>{try{return await e()}catch(i){throw new s(n.plainError(i))}},p=(e,i,l,d="0")=>n.unsignedTx({to:e,data:i,value:d,chainId:h,description:l}),b=async(e,i)=>G(await t().readContract({address:k.fee_locker.address,abi:C,functionName:"availableFees",args:[e,i]})),v=async e=>{if(w(e,I.address))return I;let[i,l]=await Promise.all([t().readContract({address:e,abi:V,functionName:"symbol"}),t().readContract({address:e,abi:V,functionName:"decimals"})]);if(typeof i!="string"||!i.trim()||!Number.isInteger(l)||l<0||l>255)throw new s("The contract returned invalid token metadata.");return{address:e,chainId:h,symbol:i,decimals:l}},Z=e=>ve(n,e),ke=async(e,i)=>{if(O(e,["name","symbol","salt","image","metadata","context","vanity","initialBuy","minAmountOut","slippageBps","rewards","vault","airdrop","feeBps","pool"]),e.vanity!==void 0&&e.vanity!==!1)throw new s("Clanker launches use vanity false and an explicit salt.");let l=T(e.name,"token name",!0),d=T(e.symbol,"token symbol",!0),g=ge(e.salt,"salt"),f=z(e.initialBuy??"0"),u=e.slippageBps??H;if(typeof u!="number")throw new s("Slippage must be an integer from 0 to 9999 bps.");q("0",u);let o=e.minAmountOut===void 0?void 0:z(e.minAmountOut,128);if(o!==void 0&&o<=1n)throw new s("Initial-buy minimum must exceed one base unit.");if(!f&&o!==void 0)throw new s("A minimum requires a positive initial buy.");let c=ce(e,i);B(e.feeBps??100,0,1e3);let y=me(e);if(f&&!w(y.poolConfig.pairedToken,I.address))throw new s("An initial ETH buy currently requires a WETH-paired pool. Launch without an initial buy and obtain a protected swap quote separately.");let r=e.rewards??[{admin:i,recipient:i,bps:1e4,feePreference:0}];if(!Array.isArray(r)||!r.length||r.length>7)throw new s("Provide one to seven reward allocations.");let A=r.map(m=>{if(!x(m))throw new s("Provide reward allocations as objects.");return O(m,["admin","recipient","bps","feePreference"]),{admin:P(m.admin),recipient:P(m.recipient),bps:B(m.bps,1,1e4),feePreference:B(m.feePreference??0,0,2)}});if(A.reduce((m,S)=>m+S.bps,0)!==1e4)throw new s("Reward allocations must total 10000 bps.");let $={tokenConfig:{tokenAdmin:i,name:l,symbol:d,salt:g,image:T(e.image,"image"),metadata:T(e.metadata,"metadata"),context:e.context===void 0?JSON.stringify({interface:"Oak",platform:"robinhood"}):T(e.context,"context"),originatingChainId:BigInt(h)},poolConfig:y.poolConfig,lockerConfig:{locker:k.locker.address,rewardAdmins:A.map(m=>m.admin),rewardRecipients:A.map(m=>m.recipient),rewardBps:A.map(m=>m.bps),tickLower:y.tickLower,tickUpper:y.tickUpper,positionBps:y.positionBps,lockerData:F(j("(uint8[])"),[[A.map(m=>m.feePreference)]])},mevModuleConfig:{mevModule:k.mev_module.address,mevModuleData:F(j("(uint24,uint24,uint256)"),[[666777,41673,15n]])},extensionConfigs:c},xe=await t().simulateContract({address:k.factory.address,abi:fe,functionName:"deployToken",args:[$],account:i,value:0n,gas:E}),_=P(xe.result),K=m=>{let S=[...c,...f?[{extension:k.devbuy.address,msgValue:f,extensionBps:0,extensionData:F(j("(address,address,uint24,int24,address),uint128,address"),[[W,W,0,0,W],m,i])}]:[]];return p(k.factory.address,N({abi:fe,functionName:"deployToken",args:[{...$,extensionConfigs:S}]}),`Launch ${l} (${d}); initial buy ${f} native ETH base units.`,f.toString())};if(f&&o===void 0){let S=(await n.preview([K(0n)],i)).changes.filter(D=>D.token.chainId===h&&w(D.token.address,_)&&D.token.decimals===18).reduce((D,X)=>D+(/^-?\d+$/.test(X.amount)?BigInt(X.amount):(()=>{throw new s("Invalid initial-buy simulation amount.")})()),0n);if(S<=0n)throw new s("Initial-buy simulation returned no token output.");if(o=z(q(S.toString(),u),128),o<=1n)throw new s("Initial-buy output is too small for a protected minimum.")}let Q=[K(o??0n)],R=await n.preview(Q,i);return{txs:Q,preview:R,predictedToken:_,token:{address:_,chainId:h,symbol:d,decimals:18},...o!==void 0?{minAmountOut:o.toString()}:{},summary:`Launch ${d} at ${_} (CREATE2 address predicted from simulation); vanity false; salt ${g}. Supply 100000000000000000000000000000 base units (18 decimals). ${y.feeSummary}; protocol adds 20% of LP fees. Pool and LP allocations: ${JSON.stringify(y)}. Reward allocations: ${JSON.stringify(A)}. Extensions: ${JSON.stringify({vault:e.vault,airdrop:e.airdrop})}. Sniper fees 666777 to 41673 over 15 seconds. ${R.summary} ${be(n,R)}`}},Ae=async(e,i)=>{if(O(e,["token","poolId","collect"]),e.collect!==void 0&&typeof e.collect!="boolean")throw new s("collect must be boolean.");if(e.collect===!1&&e.poolId!==void 0)throw new s("poolId requires collection.");if(e.collect===!0&&e.token===void 0)throw new s("Collection requires a Clanker token.");if(e.poolId!==void 0&&e.token===void 0)throw new s("A pool ID requires its Clanker token.");let l=[I],d=[];if(e.token!==void 0){let o=P(e.token);if(w(o,I.address))throw new s("Provide the launched Clanker token, not WETH.");if(e.collect!==!1){let c=await re(n,o),{poolId:y,hook:r,locker:A}=c;if(e.poolId!==void 0&&!w(ge(e.poolId,"pool ID for fee collection"),y))throw new s("The supplied pool ID does not match the onchain Clanker pool.");w(c.pairedToken,I.address)||l.splice(0,1,await v(c.pairedToken));let $=await t().readContract({address:r,abi:C,functionName:"mevModuleEnabled",args:[y]});if(typeof $!="boolean")throw new s("The hook returned an invalid MEV guard state.");$&&d.push(p(r,N({abi:C,functionName:"mevModuleOperational",args:[y]}),"Update the Clanker pool MEV guard before collection.")),d.push(p(A,N({abi:C,functionName:"collectRewards",args:[o]}),"Collect pending LP fees into the fee locker."))}l.push(await v(o))}let g;if(d.length){if(await t().getChainId()!==h)throw new s("Fee simulation endpoint is on the wrong chain.");let o=[...d.map(r=>({from:i,gas:J(E),to:r.to,data:r.data,value:J(BigInt(r.value))})),...l.map(r=>({from:i,gas:J(E),to:k.fee_locker.address,data:N({abi:C,functionName:"availableFees",args:[i,r.address]}),value:"0x0"}))],c=await t().request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:o}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(c)||c.length!==1||!x(c[0])||!Array.isArray(c[0].calls)||c[0].calls.length!==o.length)throw new s("The endpoint returned an unexpected fee simulation response.");let y=c[0].calls;if(!y.every(r=>x(r)&&r.status==="0x1"&&!r.error))throw new s("Clanker fee collection simulation failed.");g=y.slice(d.length).map(r=>{if(!x(r)||typeof r.returnData!="string"||!/^0x[0-9a-fA-F]{64}$/.test(r.returnData))throw new s("The endpoint returned an invalid fee balance.");return G(Ce({abi:C,functionName:"availableFees",data:r.returnData}))})}else g=await Promise.all(l.map(o=>b(i,o.address)));let f=l.flatMap((o,c)=>BigInt(g[c])>0n?[{token:o,amount:g[c]}]:[]);if(!f.length)throw new s("No claimable fees for this wallet; pending LP fees may require the MEV window to end.");for(let{token:o}of f)d.push(p(k.fee_locker.address,N({abi:C,functionName:"claim",args:[i,o.address]}),`Claim ${o.symbol} fees to ${i}.`));let u=await n.preview(d,i);return{txs:d,preview:u,fees:f,summary:`Claim fees to ${i}. WETH fees aggregate across all Clanker launches for this recipient. ${u.summary} ${be(n,u)}`}},L=(e,i,l,d)=>({name:`clanker_${e}`,inputSchema:{type:"object",properties:i,required:l,additionalProperties:!1},execute:(g,f)=>a(async()=>d(g,P(f)))});return{tools:[L("launch",{name:{type:"string"},symbol:{type:"string"},salt:he,image:{type:"string"},metadata:{type:"string"},context:{type:"string"},vanity:{const:!1},initialBuy:{...ye,description:"Native ETH base units, 18 decimals."},minAmountOut:{...ye,description:"Minimum new token base units, 18 decimals; derived from simulation when omitted."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:H},feeBps:{type:"integer",minimum:0,maximum:1e3,default:100},pool:ue,rewards:{type:"array",minItems:1,maxItems:7,items:{type:"object",properties:{admin:M,recipient:M,bps:{type:"integer",minimum:1,maximum:1e4},feePreference:{type:"integer",minimum:0,maximum:2}},required:["admin","recipient","bps"],additionalProperties:!1}},...de},["name","symbol","salt"],ke),L("claim",{token:{...M,description:"Launched token; derives its onchain pool and collects pending LP fees before claiming."},poolId:{...he,description:"Optional assertion against the derived pool ID."},collect:{type:"boolean",default:!0,description:"Set false to claim only already-collected fees."}},[],Ae),L("browse",{q:{type:"string"},limit:{type:"integer",minimum:1,maximum:20},cursor:{type:"string"},deployer:M},[],Z)],positions:e=>a(async()=>{P(e);let i=new Map,l=new Set,d;do{let u=await Z({deployer:e,limit:20,...d?{cursor:d}:{}});for(let o of u.tokens)w(o.msg_sender,e)&&i.set(o.contract_address.toLowerCase(),o);if(u.cursor&&l.has(u.cursor))throw new s("The Clanker indexer repeated a pagination cursor.");u.cursor&&l.add(u.cursor),d=u.cursor??void 0}while(d);let g=[],f=[I];for(let[u,o]of i){let c=await v(o.contract_address),y=G(await t().readContract({address:c.address,abi:V,functionName:"balanceOf",args:[e]}));g.push({module:"clanker",id:`launch:${u}`,chainId:h,assets:[{token:c,amount:y}],description:`Indexed launch ${o.name}; wallet token balance, not locked LP principal.`}),f.some(r=>w(r.address,c.address))||f.push(c)}for(let u of f){let o=await b(e,u.address);BigInt(o)>0n&&g.push({module:"clanker",id:`fees:${u.address.toLowerCase()}`,chainId:h,assets:[{token:u,amount:o}],description:"Collected fees across launches for this recipient. Pending LP fees excluded; token-side discovery covers indexed launches by this wallet."})}return g})}},Fe=n=>ie("clanker",[Se(n),ae(n),le(n),pe(n)]);export{ve as a,Se as b,Fe as c};
|
|
1
|
+
import{b as H,o as q}from"./CAU44UWP.js";import{a as de,b as ce,c as le}from"./HFQS5344.js";import{a as ae}from"./G7UKNO2I.js";import{a as ue,b as me}from"./BYXBS45D.js";import{a as pe}from"./GZ5TW3WB.js";import{e as U,h as B,m as re}from"./5EHQM6DM.js";import{b as ie}from"./AXYOJBX6.js";import{a as E}from"./EG6M6SSO.js";import{c as se}from"./MYBDO5SA.js";import{c as M,e as x,g as w,k as ee,l as ne,m as te,n as oe}from"./73N3TOJL.js";import{a as h,i as Y}from"./XPFVT2EA.js";import{a as s}from"./5YS5V2LK.js";import{decodeFunctionResult as Ce,encodeAbiParameters as F,encodeFunctionData as N,erc20Abi as V,isAddress as Ie,parseAbi as we,parseAbiParameters as j,toHex as J,zeroAddress as W}from"viem";var k=Y[h].clanker,fe=we(["function deployToken(((address tokenAdmin,string name,string symbol,bytes32 salt,string image,string metadata,string context,uint256 originatingChainId) tokenConfig,(address hook,address pairedToken,int24 tickIfToken0IsClanker,int24 tickSpacing,bytes poolData) poolConfig,(address locker,address[] rewardAdmins,address[] rewardRecipients,uint16[] rewardBps,int24[] tickLower,int24[] tickUpper,uint16[] positionBps,bytes lockerData) lockerConfig,(address mevModule,bytes mevModuleData) mevModuleConfig,(address extension,uint256 msgValue,uint16 extensionBps,bytes extensionData)[] extensionConfigs) config) payable returns (address)","function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),C=we(["function availableFees(address,address) view returns (uint256)","function claim(address,address)","function collectRewards(address)","function mevModuleEnabled(bytes32) view returns (bool)","function mevModuleOperational(bytes32) returns (bool)"]),I={address:k.paired_weth.address,symbol:"WETH",decimals:18,chainId:h},Pe="https://www.clanker.world/api/tokens",ye={type:"string",pattern:"^\\d+$"},he={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"};function P(n){return ne(ee(n,U),U)}function ge(n,t){if(typeof n!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n))throw new s(`Provide an explicit bytes32 ${t}.`);return n}function T(n,t,a=!1){if(n===void 0&&!a)return"";if(typeof n!="string"||a&&!n.trim())throw new s(`Provide ${t} as text.`);return n}function z(n,t=256){return oe(n,`Amount exceeds the uint${t} range.`,{bits:t})}function G(n){return te(n,"The contract returned an invalid amount.").toString()}function O(n,t){let a=Object.keys(n).find(p=>!t.includes(p));if(a)throw new s(`Unsupported Clanker input: ${a}.`)}function be(n,t){return t.changes.map(({token:a,amount:p})=>{let b=p.startsWith("-");return`${b?"-":"+"}${n.formatAmount(b?p.slice(1):p,a.decimals)} ${a.symbol} (${a.address}, chain ${a.chainId})`}).join("; ")}function Te(n){return x(n)&&Array.isArray(n.data)&&Number.isSafeInteger(n.total)&&Number(n.total)>=0&&Number.isSafeInteger(n.tokensDeployed)&&Number(n.tokensDeployed)>=0&&(n.cursor===null||typeof n.cursor=="string"||n.cursor===void 0&&n.data.length===0&&n.total===0&&n.tokensDeployed===0)&&n.data.every(t=>x(t)&&typeof t.name=="string"&&typeof t.symbol=="string"&&Number.isSafeInteger(t.chain_id)&&["contract_address","admin","msg_sender","factory_address"].every(a=>typeof t[a]=="string"&&Ie(t[a],{strict:!1})))}async function ve(n,t={}){O(t,["q","limit","cursor","deployer"]);let a=t.limit??10;if(typeof a!="number"||!Number.isInteger(a)||a<1||a>20)throw new s("Choose an indexer limit from 1 to 20.");let p=new URL(Pe);p.searchParams.set("chainId",String(h)),p.searchParams.set("limit",String(a)),t.q!==void 0&&p.searchParams.set("q",T(t.q,"search")),t.cursor!==void 0&&p.searchParams.set("cursor",T(t.cursor,"cursor",!0)),t.deployer!==void 0&&p.searchParams.set("msgSender",P(t.deployer));let b=await se(n.http,p.toString(),{headers:{"User-Agent":"Oak-Clanker/1.0"}},Te);return{tokens:b.data.filter(v=>v.chain_id===h&&w(v.factory_address,k.factory.address)),total:b.total,cursor:b.cursor||null,tokensDeployed:b.tokensDeployed}}var Se=n=>{let t=()=>n.clientFor(h),a=async e=>{try{return await e()}catch(i){throw new s(n.plainError(i))}},p=(e,i,l,d="0")=>n.unsignedTx({to:e,data:i,value:d,chainId:h,description:l}),b=async(e,i)=>G(await t().readContract({address:k.fee_locker.address,abi:C,functionName:"availableFees",args:[e,i]})),v=async e=>{if(w(e,I.address))return I;let[i,l]=await Promise.all([t().readContract({address:e,abi:V,functionName:"symbol"}),t().readContract({address:e,abi:V,functionName:"decimals"})]);if(typeof i!="string"||!i.trim()||!Number.isInteger(l)||l<0||l>255)throw new s("The contract returned invalid token metadata.");return{address:e,chainId:h,symbol:i,decimals:l}},Z=e=>ve(n,e),ke=async(e,i)=>{if(O(e,["name","symbol","salt","image","metadata","context","vanity","initialBuy","minAmountOut","slippageBps","rewards","vault","airdrop","feeBps","pool"]),e.vanity!==void 0&&e.vanity!==!1)throw new s("Clanker launches use vanity false and an explicit salt.");let l=T(e.name,"token name",!0),d=T(e.symbol,"token symbol",!0),g=ge(e.salt,"salt"),f=z(e.initialBuy??"0"),u=e.slippageBps??H;if(typeof u!="number")throw new s("Slippage must be an integer from 0 to 9999 bps.");q("0",u);let o=e.minAmountOut===void 0?void 0:z(e.minAmountOut,128);if(o!==void 0&&o<=1n)throw new s("Initial-buy minimum must exceed one base unit.");if(!f&&o!==void 0)throw new s("A minimum requires a positive initial buy.");let c=ce(e,i);B(e.feeBps??100,0,1e3);let y=me(e);if(f&&!w(y.poolConfig.pairedToken,I.address))throw new s("An initial ETH buy currently requires a WETH-paired pool. Launch without an initial buy and obtain a protected swap quote separately.");let r=e.rewards??[{admin:i,recipient:i,bps:1e4,feePreference:0}];if(!Array.isArray(r)||!r.length||r.length>7)throw new s("Provide one to seven reward allocations.");let A=r.map(m=>{if(!x(m))throw new s("Provide reward allocations as objects.");return O(m,["admin","recipient","bps","feePreference"]),{admin:P(m.admin),recipient:P(m.recipient),bps:B(m.bps,1,1e4),feePreference:B(m.feePreference??0,0,2)}});if(A.reduce((m,S)=>m+S.bps,0)!==1e4)throw new s("Reward allocations must total 10000 bps.");let $={tokenConfig:{tokenAdmin:i,name:l,symbol:d,salt:g,image:T(e.image,"image"),metadata:T(e.metadata,"metadata"),context:e.context===void 0?JSON.stringify({interface:"Oak",platform:"robinhood"}):T(e.context,"context"),originatingChainId:BigInt(h)},poolConfig:y.poolConfig,lockerConfig:{locker:k.locker.address,rewardAdmins:A.map(m=>m.admin),rewardRecipients:A.map(m=>m.recipient),rewardBps:A.map(m=>m.bps),tickLower:y.tickLower,tickUpper:y.tickUpper,positionBps:y.positionBps,lockerData:F(j("(uint8[])"),[[A.map(m=>m.feePreference)]])},mevModuleConfig:{mevModule:k.mev_module.address,mevModuleData:F(j("(uint24,uint24,uint256)"),[[666777,41673,15n]])},extensionConfigs:c},xe=await t().simulateContract({address:k.factory.address,abi:fe,functionName:"deployToken",args:[$],account:i,value:0n,gas:E}),_=P(xe.result),K=m=>{let S=[...c,...f?[{extension:k.devbuy.address,msgValue:f,extensionBps:0,extensionData:F(j("(address,address,uint24,int24,address),uint128,address"),[[W,W,0,0,W],m,i])}]:[]];return p(k.factory.address,N({abi:fe,functionName:"deployToken",args:[{...$,extensionConfigs:S}]}),`Launch ${l} (${d}); initial buy ${f} native ETH base units.`,f.toString())};if(f&&o===void 0){let S=(await n.preview([K(0n)],i)).changes.filter(D=>D.token.chainId===h&&w(D.token.address,_)&&D.token.decimals===18).reduce((D,X)=>D+(/^-?\d+$/.test(X.amount)?BigInt(X.amount):(()=>{throw new s("Invalid initial-buy simulation amount.")})()),0n);if(S<=0n)throw new s("Initial-buy simulation returned no token output.");if(o=z(q(S.toString(),u),128),o<=1n)throw new s("Initial-buy output is too small for a protected minimum.")}let Q=[K(o??0n)],R=await n.preview(Q,i);return{txs:Q,preview:R,predictedToken:_,token:{address:_,chainId:h,symbol:d,decimals:18},...o!==void 0?{minAmountOut:o.toString()}:{},summary:`Launch ${d} at ${_} (CREATE2 address predicted from simulation); vanity false; salt ${g}. Supply 100000000000000000000000000000 base units (18 decimals). ${y.feeSummary}; protocol adds 20% of LP fees. Pool and LP allocations: ${JSON.stringify(y)}. Reward allocations: ${JSON.stringify(A)}. Extensions: ${JSON.stringify({vault:e.vault,airdrop:e.airdrop})}. Sniper fees 666777 to 41673 over 15 seconds. ${R.summary} ${be(n,R)}`}},Ae=async(e,i)=>{if(O(e,["token","poolId","collect"]),e.collect!==void 0&&typeof e.collect!="boolean")throw new s("collect must be boolean.");if(e.collect===!1&&e.poolId!==void 0)throw new s("poolId requires collection.");if(e.collect===!0&&e.token===void 0)throw new s("Collection requires a Clanker token.");if(e.poolId!==void 0&&e.token===void 0)throw new s("A pool ID requires its Clanker token.");let l=[I],d=[];if(e.token!==void 0){let o=P(e.token);if(w(o,I.address))throw new s("Provide the launched Clanker token, not WETH.");if(e.collect!==!1){let c=await re(n,o),{poolId:y,hook:r,locker:A}=c;if(e.poolId!==void 0&&!w(ge(e.poolId,"pool ID for fee collection"),y))throw new s("The supplied pool ID does not match the onchain Clanker pool.");w(c.pairedToken,I.address)||l.splice(0,1,await v(c.pairedToken));let $=await t().readContract({address:r,abi:C,functionName:"mevModuleEnabled",args:[y]});if(typeof $!="boolean")throw new s("The hook returned an invalid MEV guard state.");$&&d.push(p(r,N({abi:C,functionName:"mevModuleOperational",args:[y]}),"Update the Clanker pool MEV guard before collection.")),d.push(p(A,N({abi:C,functionName:"collectRewards",args:[o]}),"Collect pending LP fees into the fee locker."))}l.push(await v(o))}let g;if(d.length){if(await t().getChainId()!==h)throw new s("Fee simulation endpoint is on the wrong chain.");let o=[...d.map(r=>({from:i,gas:J(E),to:r.to,data:r.data,value:J(BigInt(r.value))})),...l.map(r=>({from:i,gas:J(E),to:k.fee_locker.address,data:N({abi:C,functionName:"availableFees",args:[i,r.address]}),value:"0x0"}))],c=await t().request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:o}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(c)||c.length!==1||!x(c[0])||!Array.isArray(c[0].calls)||c[0].calls.length!==o.length)throw new s("The endpoint returned an unexpected fee simulation response.");let y=c[0].calls;if(!y.every(r=>x(r)&&r.status==="0x1"&&!r.error))throw new s("Clanker fee collection simulation failed.");g=y.slice(d.length).map(r=>{if(!x(r)||typeof r.returnData!="string"||!/^0x[0-9a-fA-F]{64}$/.test(r.returnData))throw new s("The endpoint returned an invalid fee balance.");return G(Ce({abi:C,functionName:"availableFees",data:r.returnData}))})}else g=await Promise.all(l.map(o=>b(i,o.address)));let f=l.flatMap((o,c)=>BigInt(g[c])>0n?[{token:o,amount:g[c]}]:[]);if(!f.length)throw new s("No claimable fees for this wallet; pending LP fees may require the MEV window to end.");for(let{token:o}of f)d.push(p(k.fee_locker.address,N({abi:C,functionName:"claim",args:[i,o.address]}),`Claim ${o.symbol} fees to ${i}.`));let u=await n.preview(d,i);return{txs:d,preview:u,fees:f,summary:`Claim fees to ${i}. WETH fees aggregate across all Clanker launches for this recipient. ${u.summary} ${be(n,u)}`}},L=(e,i,l,d)=>({name:`clanker_${e}`,inputSchema:{type:"object",properties:i,required:l,additionalProperties:!1},execute:(g,f)=>a(async()=>d(g,P(f)))});return{tools:[L("launch",{name:{type:"string"},symbol:{type:"string"},salt:he,image:{type:"string"},metadata:{type:"string"},context:{type:"string"},vanity:{const:!1},initialBuy:{...ye,description:"Native ETH base units, 18 decimals."},minAmountOut:{...ye,description:"Minimum new token base units, 18 decimals; derived from simulation when omitted."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:H},feeBps:{type:"integer",minimum:0,maximum:1e3,default:100},pool:ue,rewards:{type:"array",minItems:1,maxItems:7,items:{type:"object",properties:{admin:M,recipient:M,bps:{type:"integer",minimum:1,maximum:1e4},feePreference:{type:"integer",minimum:0,maximum:2}},required:["admin","recipient","bps"],additionalProperties:!1}},...de},["name","symbol","salt"],ke),L("claim",{token:{...M,description:"Launched token; derives its onchain pool and collects pending LP fees before claiming."},poolId:{...he,description:"Optional assertion against the derived pool ID."},collect:{type:"boolean",default:!0,description:"Set false to claim only already-collected fees."}},[],Ae),L("browse",{q:{type:"string"},limit:{type:"integer",minimum:1,maximum:20},cursor:{type:"string"},deployer:M},[],Z)],positions:e=>a(async()=>{P(e);let i=new Map,l=new Set,d;do{let u=await Z({deployer:e,limit:20,...d?{cursor:d}:{}});for(let o of u.tokens)w(o.msg_sender,e)&&i.set(o.contract_address.toLowerCase(),o);if(u.cursor&&l.has(u.cursor))throw new s("The Clanker indexer repeated a pagination cursor.");u.cursor&&l.add(u.cursor),d=u.cursor??void 0}while(d);let g=[],f=[I];for(let[u,o]of i){let c=await v(o.contract_address),y=G(await t().readContract({address:c.address,abi:V,functionName:"balanceOf",args:[e]}));g.push({module:"clanker",id:`launch:${u}`,chainId:h,assets:[{token:c,amount:y}],description:`Indexed launch ${o.name}; wallet token balance, not locked LP principal.`}),f.some(r=>w(r.address,c.address))||f.push(c)}for(let u of f){let o=await b(e,u.address);BigInt(o)>0n&&g.push({module:"clanker",id:`fees:${u.address.toLowerCase()}`,chainId:h,assets:[{token:u,amount:o}],description:"Collected fees across launches for this recipient. Pending LP fees excluded; token-side discovery covers indexed launches by this wallet."})}return g})}},Fe=n=>ie("clanker",[Se(n),ae(n),le(n),pe(n)]);export{ve as a,Se as b,Fe as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as b,g as W,h as j,m as z}from"./
|
|
1
|
+
import{d as b,g as W,h as j,m as z}from"./R7D256HG.js";import{b as C,c as F,s as B,z as R}from"./ANQ43XJA.js";import{a as X,e as q,g as D}from"./64AF7ECA.js";import{a as U}from"./UWOFA6GV.js";import{g as T}from"./73N3TOJL.js";import{a as O}from"./XPFVT2EA.js";import{a as c}from"./5YS5V2LK.js";import{decodeEventLog as J,parseAbi as V,toEventSelector as Z,toHex as x}from"viem";var K=V(["function getPositionInfo(bytes32 poolId,address owner,int24 tickLower,int24 tickUpper,bytes32 salt) view returns (uint128 liquidity,uint256 feeGrowthInside0LastX128,uint256 feeGrowthInside1LastX128)","function getFeeGrowthInside(bytes32 poolId,int24 tickLower,int24 tickUpper) view returns (uint256,uint256)"]),Q=V(["function ownerOf(uint256) view returns (address)","function getPoolAndPositionInfo(uint256) view returns ((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks),uint256)"]),A=V(["function slot0() view returns (uint160,int24,uint16,uint16,uint16,uint8,bool)","function feeGrowthGlobal0X128() view returns (uint256)","function feeGrowthGlobal1X128() view returns (uint256)","function ticks(int24) view returns (uint128,int128,uint256,uint256,int56,uint160,uint32,bool)"]),$=(1n<<256n)-1n,ee=1n<<128n,P=(s,t)=>s-t&$;function G(s,t,r,n=0n){return P(s,t)*r/ee+n}function ue(s){return{tools:[{name:"uniswap_fees",inputSchema:{type:"object",additionalProperties:!1,required:["version","tokenId"],properties:{includeHistory:{type:"boolean",description:"V3 only: read the complete NFT collect/decrease event history for lifetime fees. This can require multiple RPC log windows."},version:{type:"string",enum:["v3","v4"]},tokenId:U()}},async execute(t){if(D(t,["version","tokenId","includeHistory"]),t.includeHistory!==void 0&&typeof t.includeHistory!="boolean")throw new c("includeHistory must be a boolean.");if(t.includeHistory===!0&&t.version!=="v3")throw new c("V4 position lifetime fees need historical liquidity/fee-growth checkpoints; no verified history source is configured.");let r=X(t.tokenId,"tokenId"),n=s.clientFor(O),i=await n.getBlockNumber();if(t.version!=="v3"&&t.version!=="v4")throw new c("Provide version v3 or v4 for fee reads.");let _=await n.readContract({address:t.version==="v4"?C:b.positionManager,abi:Q,functionName:"ownerOf",args:[r],blockNumber:i}),v,m,a,d,u,w=0n,p=0n;if(t.version==="v4"){let[e,f]=await n.readContract({address:C,abi:Q,functionName:"getPoolAndPositionInfo",args:[r],blockNumber:i}),{tickLower:h,tickUpper:N}=R(f),S=B(e),[k,I]=await Promise.all([n.readContract({address:F,abi:K,functionName:"getPositionInfo",args:[S,C,h,N,x(r,{size:32})],blockNumber:i}),n.readContract({address:F,abi:K,functionName:"getFeeGrowthInside",args:[S,h,N],blockNumber:i})]);[v,m,a]=[e.currency0,e.currency1,k[0]],[d,u]=[G(I[0],k[1],a),G(I[1],k[2],a)]}else if(t.version==="v3"){let e=z(await n.readContract({address:b.positionManager,abi:W,functionName:"positions",args:[r],blockNumber:i})),f=await n.readContract({address:b.factory,abi:j,functionName:"getPool",args:[e.token0,e.token1,e.fee],blockNumber:i}),[h,N,S,k,I]=await Promise.all([n.readContract({address:f,abi:A,functionName:"slot0",blockNumber:i}),n.readContract({address:f,abi:A,functionName:"feeGrowthGlobal0X128",blockNumber:i}),n.readContract({address:f,abi:A,functionName:"feeGrowthGlobal1X128",blockNumber:i}),n.readContract({address:f,abi:A,functionName:"ticks",args:[e.tickLower],blockNumber:i}),n.readContract({address:f,abi:A,functionName:"ticks",args:[e.tickUpper],blockNumber:i})]),M=(L,E,H)=>P(P(L,h[1]>=e.tickLower?E:P(L,E)),h[1]<e.tickUpper?H:P(L,H));[v,m,a]=[e.token0,e.token1,e.liquidity],[w,p]=[e.tokensOwed0,e.tokensOwed1],[d,u]=[G(M(N,k[2],I[2]),e.feeGrowthInside0LastX128,a,e.tokensOwed0),G(M(S,k[3],I[3]),e.feeGrowthInside1LastX128,a,e.tokensOwed1)]}else throw new c('Provide version "v3" or "v4" for fee reads.');let[o,g]=await Promise.all([q(s,v,i),q(s,m,i)]),y=[{token:o,amount:d.toString()},{token:g,amount:u.toString()}],l=t.includeHistory===!0?await te(s,r,i,d,u):void 0;return{version:t.version,tokenId:r.toString(),owner:_,blockNumber:i.toString(),liquidity:a.toString(),...t.version==="v4"?{uncollected:y}:{},collectable:y,feeGrowthAccrual:[{token:o,amount:(d-w).toString()},{token:g,amount:(u-p).toString()}],tokensOwed:[{token:o,amount:w.toString()},{token:g,amount:p.toString()}],...l?{lifetimeFees:[{token:o,amount:l[0].toString()},{token:g,amount:l[1].toString()}]}:{},summary:"One-block collectable estimate, excluding gas. V3 tokensOwed may include withdrawn principal; feeGrowthAccrual excludes those stored amounts. V4 hook accounting can change actual collections. V4 current liquidity times lifetime range growth is not lifetime position earnings."}}}]}}var Y=V(["event IncreaseLiquidity(uint256 indexed tokenId,uint128 liquidity,uint256 amount0,uint256 amount1)","event DecreaseLiquidity(uint256 indexed tokenId,uint128 liquidity,uint256 amount0,uint256 amount1)","event Collect(uint256 indexed tokenId,address recipient,uint256 amount0,uint256 amount1)"]);async function te(s,t,r,n,i){let _=s.clientFor(O),v=Y.map(o=>Z(o)),m=0n,a=0n,d=0n,u=0n,w=0;for(let o=0n;o<=r;o+=10000000n){let g=o+9999999n<r?o+9999999n:r,y=await _.request({method:"eth_getLogs",params:[{address:b.positionManager,topics:[v,x(t,{size:32})],fromBlock:x(o),toBlock:x(g)}]});if(!Array.isArray(y))throw new c("V3 lifetime fee history is unavailable; do not treat missing history as zero earnings.");for(let l of y){if(!T(l.address,b.positionManager))throw new c("Unexpected contract in v3 lifetime fee history.");let e=J({abi:Y,data:l.data,topics:l.topics});if(e.args.tokenId!==t)throw new c("Unexpected NFT in v3 fee history.");e.eventName==="Collect"?(m+=e.args.amount0,a+=e.args.amount1):e.eventName==="DecreaseLiquidity"?(d+=e.args.amount0,u+=e.args.amount1):w++}}if(w===0)throw new c("V3 mint/increase history is missing for this existing NFT; lifetime earnings are unknown.");let p=[m+n-d,a+i-u];if(p.some(o=>o<0n))throw new c("V3 fee history is incomplete or inconsistent; lifetime earnings are unknown.");return p}export{K as a,P as b,G as c,ue as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as Ce,d as Me,e as we,f as ie,i as be,j as Ne}from"./FYTF2QMS.js";import{b as ne,o as ge}from"./EAEQOS7Y.js";import{a as O,b as pe}from"./6IM6A5VA.js";import{a as F,c as Ue}from"./RETS2ZEK.js";import{a as k,i as _}from"./XPFVT2EA.js";import{a as Te}from"./EG6M6SSO.js";import{a as c,b as te,d as U}from"./5YS5V2LK.js";import{decodeFunctionResult as he,encodeFunctionData as R,getAddress as l,parseAbi as Z,zeroAddress as C}from"viem";var re=-887272,se=887272,z=(1n<<128n)-1n,Fe="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",ze="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",Ge="0x3067048beee31b25b2f1681f88dac838c8bba36af25bfb2b7cf7473a5847e35f",oe=2000n,je=5,Ke=1800n,f=Object.freeze({factory:l(_[4663].uniswap.v3_factory.address),positionManager:l(_[4663].uniswap.v3_position_manager.address),swapRouter02:l(_[4663].uniswap.swap_router02.address),permit2:l(_[4663].uniswap.permit2.address),weth:l(_[4663].uniswap.WETH.address),usdg:l(_[4663].uniswap.USDG.address),ethUsdgPool:l(_[4663].oracle.ethUsdgPool.address)}),xe=Object.freeze({100:1,500:10,3e3:60,1e4:200}),yt=Object.freeze([{fee:100,tickSpacing:1,address:l("0x52e65B17fB6E5BA00Ed806f37Afcd2DaA50271Ca"),token0:f.weth,token1:f.usdg,recordedLiquidity:"1957537485734736219",recordedSqrtPriceX96:"3839219776288481168641554",recordedTick:-198707,feeProtocol:68},{fee:500,tickSpacing:10,address:l("0x69bfaf19c9f377bb306a89aed9f6b07e2c1a8d9a"),token0:f.weth,token1:f.usdg,recordedLiquidity:"714542894544667104",recordedSqrtPriceX96:"3839644024453020182443671",recordedTick:-198705,feeProtocol:68},{fee:3e3,tickSpacing:60,address:l("0xa9188730fe85be88ad499d7d52b099e800fb0334"),token0:f.weth,token1:f.usdg,recordedLiquidity:"310559629687003603",recordedSqrtPriceX96:"3843235825752878635548672",recordedTick:-198686,feeProtocol:102},{fee:1e4,tickSpacing:200,address:l("0x5f009e071f07e92b6c624e83f52f17bbda34680d"),token0:f.weth,token1:f.usdg,recordedLiquidity:"5822966536584155",recordedSqrtPriceX96:"3853297838190389678059735",recordedTick:-198634,feeProtocol:102}]),x=Z(["function positions(uint256 tokenId) view returns (uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1)","function ownerOf(uint256 tokenId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)","function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline) params) payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)","function increaseLiquidity((uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint128 liquidity, uint256 amount0, uint256 amount1)","function decreaseLiquidity((uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint256 amount0, uint256 amount1)","function collect((uint256 tokenId, address recipient, uint128 amount0Max, uint128 amount1Max) params) payable returns (uint256 amount0, uint256 amount1)","function burn(uint256 tokenId) payable","function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96) payable returns (address pool)"]),Q=Z(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)","function feeAmountTickSpacing(uint24 fee) view returns (int24)"]),ke=Z(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickSpacing() view returns (int24)","function fee() view returns (uint24)","function token0() view returns (address)","function token1() view returns (address)"]),Qe=Z(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),ye=Z(["function decimals() view returns (uint8)","function symbol() view returns (string)","function allowance(address owner, address spender) view returns (uint256)"]),Ye="0xd0e30db0";function Ze(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e===C||e===Fe||e==="eth"||e==="native"}function E(t,e){if(Ze(t))throw new c(`Uniswap v3 requires wrapped ERC-20 WETH (${f.weth}) rather than native ETH in ${e}.`);if(typeof t!="string")throw new c(`${e} must be a valid 20-byte hex address.`);return O(t),l(t)}function Je(t,e,n){let a=Number(t),o=Number(e),i=Number(n);if(!Number.isInteger(i)||i<=0)throw new c("Uniswap v3 tickSpacing must be a positive integer.");if(!Number.isInteger(a)||!Number.isInteger(o))throw new c("Uniswap v3 tickLower and tickUpper must be integers.");if(a<re||o>se||a>se||o<re)throw new c(`Uniswap v3 ticks are out of bounds [${re}, ${se}].`);if(a>=o)throw new c("Uniswap v3 tickLower must be strictly less than tickUpper.");if(a%i!==0||o%i!==0)throw new c(`Uniswap v3 tickLower (${a}) and tickUpper (${o}) must be divisible by tickSpacing (${i}).`);return{tickLower:a,tickUpper:o,tickSpacing:i}}function et(t,e){let n=t.trim(),a=n.startsWith("-"),o=a||n.startsWith("+")?n.slice(1):n,i=Ue(F(o).toString(),e);return a&&i!=="0"?`-${i}`:i}function tt(t){let e=typeof t=="string"?he({abi:x,functionName:"positions",data:t}):t;return{nonce:BigInt(e[0]),operator:l(String(e[1])),token0:l(String(e[2])),token1:l(String(e[3])),fee:Number(e[4]),tickLower:Number(e[5]),tickUpper:Number(e[6]),liquidity:BigInt(e[7]),feeGrowthInside0LastX128:BigInt(e[8]),feeGrowthInside1LastX128:BigInt(e[9]),tokensOwed0:BigInt(e[10]),tokensOwed1:BigInt(e[11])}}function $e(t,e){if(!t||!Array.isArray(t.logs))return[];let n=e?l(e).toLowerCase():void 0,a=f.positionManager.toLowerCase(),o=new Set;for(let i of t.logs){if(!i||typeof i.address!="string"||i.address.toLowerCase()!==a)continue;let r=Array.isArray(i.topics)?i.topics.map(u=>String(u).toLowerCase()):[],s=r[0];if(s===ze&&r.length>=4){let d=`0x${r[2].slice(-40)}`;if(!n||d===n){let m=BigInt(r[3]).toString();m!=="0"&&o.add(m)}}else if(s===Ge&&r.length>=2&&!n){let u=BigInt(r[1]).toString();u!=="0"&&o.add(u)}}return[...o]}function ht(t){let e=n=>typeof n=="bigint"?n:F(n);return R({abi:Qe,functionName:"exactInputSingle",args:[{tokenIn:l(t.tokenIn),tokenOut:l(t.tokenOut),fee:t.fee,recipient:l(t.recipient),amountIn:e(t.amountIn),amountOutMinimum:e(t.amountOutMinimum),sqrtPriceLimitX96:t.sqrtPriceLimitX96!==void 0?e(t.sqrtPriceLimitX96):0n}]})}var Le=1n<<96n;function Re(t){let e=Math.abs(t),n=(e&1)!==0?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&2)!==0&&(n=n*0xfff97272373d413259a46990580e213an>>128n),(e&4)!==0&&(n=n*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&8)!==0&&(n=n*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&16)!==0&&(n=n*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&32)!==0&&(n=n*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&64)!==0&&(n=n*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&128)!==0&&(n=n*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&256)!==0&&(n=n*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&512)!==0&&(n=n*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&1024)!==0&&(n=n*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&2048)!==0&&(n=n*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&4096)!==0&&(n=n*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&8192)!==0&&(n=n*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&16384)!==0&&(n=n*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&32768)!==0&&(n=n*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&65536)!==0&&(n=n*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&131072)!==0&&(n=n*0x5d6af8dedb81196699c329225ee604n>>128n),(e&262144)!==0&&(n=n*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&524288)!==0&&(n=n*0x48a170391f7dc42444e8fa2n>>128n),t>0&&(n=((1n<<256n)-1n)/n),(n>>32n)+(n%(1n<<32n)===0n?0n:1n)}function nt(t,e,n,a){if(a<=0n)return{amount0:0n,amount1:0n};let[o,i]=e<n?[e,n]:[n,e];if(t<=o)return{amount0:(a<<96n)*(i-o)/i/o,amount1:0n};if(t<i){let s=(a<<96n)*(i-t)/i/t,u=a*(t-o)/Le;return{amount0:s,amount1:u}}return{amount0:0n,amount1:a*(i-o)/Le}}async function M(t,e,n,a){let o=l(e),i,r;if(n===k&&o===f.weth?(i=18,r="WETH"):n===k&&o===f.usdg&&(i=6,r="USDG"),i===void 0){let s=await t.readContract({address:o,abi:ye,functionName:"decimals"});i=Number(s)}if(r===void 0)try{let s=await t.readContract({address:o,abi:ye,functionName:"symbol"});if(typeof s!="string"||!s.trim())throw new c("Token symbol is unavailable.");r=Ne(s.trim(),o)}catch(s){throw new c(`Could not read token metadata. ${U(s)}`)}if(!Number.isInteger(i)||i<0||i>255)throw new c("Token decimals are invalid.");if(a!=null){let s=Number(a);if(!Number.isInteger(s)||s!==i)throw new c(`Token ${o} on chain ${n} has ${i} decimals, not ${String(a)}.`)}return{address:o,symbol:r,decimals:i,chainId:n}}async function it(t){try{if(!t.getBlock)throw new c("Block timestamps are unavailable.");let e=await t.getBlock();if(typeof e.timestamp!="bigint")throw new c("Invalid block timestamp.");return e.timestamp}catch(e){throw new c(`Could not read the current block timestamp. ${U(e)}`)}}function J(t,e){if(typeof t=="bigint"){if(t<0n)throw new c(`${e} must be a non-negative integer.`);return t}if(typeof t=="number"){if(!Number.isSafeInteger(t)||t<0)throw new c(`${e} must be a non-negative integer.`);return BigInt(t)}if(typeof t=="string")return F(t);throw new c(`${e} must be a non-negative integer.`)}async function _e(t,e){let n=await it(t);if(e==null)return n+Ke;let a=J(e,"deadline");if(a<=n)throw new c(`Uniswap v3 deadline (${a.toString()}) has expired at timestamp ${n.toString()}.`);return a}function V(t,e){if(typeof t!="string"||!/^\d+$/.test(t))throw new c(`${e} must be a non-negative integer string in base units.`);return F(t)}function Ee(t){let e=t.slippageBps??ne;if(typeof e!="number")throw new c("Slippage must be an integer from 0 to 9999 bps.");return ge("0",e),e}function ae(t,e,n,a){let o=t===void 0?F(ge(e.toString(),n)):V(t,a);if(o<=1n)throw new c(`${a} must exceed 1 base unit; the simulated amount may be too small.`);return o}function X(t,e){return pe({to:f.positionManager,data:t,value:"0",chainId:k,description:e})}async function Y(t,e,n){try{if(!t.request)throw new c("Sequential transaction simulation is unavailable.");let o=await t.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:n,gas:`0x${Te.toString(16)}`,to:i.to,data:i.data,value:`0x${BigInt(i.value).toString(16)}`}))}],validation:!1,traceTransfers:!0},"latest"]},{retryCount:0});if(!Array.isArray(o)||o.length!==1||!Array.isArray(o[0]?.calls)||o[0].calls.length!==e.length)throw new c("Unexpected batch simulation response.");return o[0].calls.map((i,r)=>{if(i.status!=="0x1"||i.error||typeof i.returnData!="string"||!/^0x([a-fA-F0-9]{2})*$/.test(i.returnData))throw new c(`Simulation call ${r+1} failed. ${U(i.error)}`);return i.returnData})}catch(a){throw new c(`Uniswap v3 simulation failed. ${U(a)}`)}}function ce(t,e){try{return he({abi:x,functionName:t,data:e})}catch{throw new c(`Uniswap v3 ${t} simulation returned invalid amounts.`)}}function Be(t,e,n){if(t.initialPrice!==void 0&&t.sqrtPriceX96!==void 0)throw new c("Provide initialPrice or sqrtPriceX96, not both.");if(t.sqrtPriceX96!==void 0){if(typeof t.sqrtPriceX96!="string"||!/^\d+$/.test(t.sqrtPriceX96))throw new c("sqrtPriceX96 must be a non-negative integer string.");return Me(BigInt(t.sqrtPriceX96))}if(t.initialPrice===void 0)throw new c("A new pool needs initialPrice (token1 per 1 token0, human units) or sqrtPriceX96.");return Ce(t.initialPrice,e,n)}async function De(t,e,n,a){let o=[];for(let i of Object.keys(xe).map(Number)){if(i===a)continue;let r=l(String(await t.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[e,n,i]})));if(r===C||BigInt(await t.readContract({address:r,abi:ke,functionName:"liquidity"}))===0n)continue;let u=await t.readContract({address:r,abi:ke,functionName:"slot0"});o.push({label:`v3 fee ${i} pool ${r}`,sqrtPriceX96:BigInt(u[0])})}return o}function G(t,e={}){if(e.chainId!==void 0&&Number(e.chainId)!==k)throw new c(`Uniswap v3 is only supported on Robinhood Chain (${k}).`);if(e.version!==void 0&&e.version!=="v3")throw new c(`Uniswap v3 handler received unsupported version "${String(e.version)}".`);let n=t.clientFor(k);return{...n,readContract:async a=>{try{return await n.readContract(a)}catch(o){throw new c(`Could not read Uniswap v3 ${a.functionName}. ${U(o)}`,{cause:o})}}}}async function ve(t,e,n){let a;try{a=await t.readContract({address:f.positionManager,abi:x,functionName:"ownerOf",args:[e]})}catch(r){throw new c(`Could not verify owner of Uniswap v3 position #${e}. ${U(r)}`)}let o=l(String(a)),i=l(n);if(o!==i)throw new c(`Wallet ${i} is not the owner of Uniswap v3 position #${e.toString()} (owned by ${o}).`);return o}async function de(t,e){let n=await t.readContract({address:f.positionManager,abi:x,functionName:"positions",args:[e]});return tt(n)}function Ie(t,e){if(!Array.isArray(e.changes)||!e.changes.length)return t;let n=e.changes.map(a=>`${et(a.amount,a.token.decimals)} ${a.token.symbol}`);return`${t} (${n.join(", ")})`}async function ot(t,e,n){O(n);let a=l(n),o=G(t,e),i=await _e(o,e.deadline),r=Ee(e),s=e.tokenId===void 0?void 0:J(e.tokenId,"tokenId"),u;if(s!==void 0){if(s<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await ve(o,s,a),u=await de(o,s)}let d=u?.token0??E(e.token0,"token0"),m=u?.token1??E(e.token1,"token1");if(BigInt(d)>=BigInt(m))throw new c("Uniswap v3 requires distinct sorted token addresses.");let p=u?.fee??Number(e.fee??100),g=xe[p];if(!g)throw new c("Unsupported Uniswap v3 fee tier.");let y=l(String(await o.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[d,m,p]}))),h=e.initialPrice!==void 0||e.sqrtPriceX96!==void 0;if(y===C&&!h)throw new c("No Uniswap v3 pool exists for these tokens and fee tier. To create it and add the first liquidity in one tool call with separately confirmed transactions, add initialPrice (token1 per 1 token0, human units) to this call; to create it without liquidity use uniswap_create_pool.");if(y!==C&&h)throw new c(`The Uniswap v3 pool already exists at ${y}; remove initialPrice/sqrtPriceX96 to add liquidity at its current price.`);if(s!==void 0&&h)throw new c("initialPrice cannot be combined with tokenId.");if(e.fullRange!==void 0&&typeof e.fullRange!="boolean")throw new c("fullRange must be a boolean.");if(e.fullRange===!0&&(e.tickLower!==void 0||e.tickUpper!==void 0||u))throw new c("Use fullRange only for a new position, without explicit ticks. Existing position ticks cannot change.");let{tickLower:S,tickUpper:N,tickSpacing:T}=Je(u?.tickLower??(e.fullRange===!0?Math.ceil(re/g)*g:e.tickLower),u?.tickUpper??(e.fullRange===!0?Math.floor(se/g)*g:e.tickUpper),g),w=await M(o,d,k,e.token0Decimals),b=await M(o,m,k,e.token1Decimals),P;if(y===C){let q=Be(e,w.decimals,b.decimals),L=be(q,await De(o,d,m,p),e.acceptPriceDeviation===!0,w.decimals,b.decimals);P={sqrtPriceX96:q,note:L}}let v=V(e.amount0Desired,"amount0Desired"),I=V(e.amount1Desired,"amount1Desired");if(v===0n&&I===0n)throw new c("Liquidity addition requires a positive desired amount.");let $=e.recipient===void 0?a:E(e.recipient,"recipient");if($!==a)throw new c("Uniswap recipient must be the signing wallet.");if(e.wrapNative===!0&&d!==f.weth&&m!==f.weth)throw new c("Wrapping requires a positive WETH desired amount.");let H=await Promise.all([d,m].map(async q=>BigInt(await o.readContract({address:q,abi:ye,functionName:"allowance",args:[a,f.positionManager]})))),j=(q,L)=>{let fe=[];if(e.wrapNative===!0){let K=d===f.weth?q:L;K>0n&&fe.push(pe({to:f.weth,data:Ye,value:K.toString(),chainId:k,description:"Wrap ETH into WETH."}))}for(let[K,We]of[d,m].entries()){let me=K===0?q:L;me>0n&&H[K]<me&&fe.push(t.approval(We,f.positionManager,me.toString(),k))}return fe},W=s===void 0?"mint":"increaseLiquidity",B=(q,L)=>X(s===void 0?R({abi:x,functionName:"mint",args:[{token0:d,token1:m,fee:p,tickLower:S,tickUpper:N,amount0Desired:v,amount1Desired:I,amount0Min:q,amount1Min:L,recipient:$,deadline:i}]}):R({abi:x,functionName:"increaseLiquidity",args:[{tokenId:s,amount0Desired:v,amount1Desired:I,amount0Min:q,amount1Min:L,deadline:i}]}),`${W==="mint"?"Mint":"Increase"} Uniswap v3 ${w.symbol}/${b.symbol} liquidity.`),D=P&&X(R({abi:x,functionName:"createAndInitializePoolIfNecessary",args:[d,m,p,P.sqrtPriceX96]}),`Create and initialize the Uniswap v3 ${w.symbol}/${b.symbol} fee ${p} pool at ${ie(P.sqrtPriceX96,w.decimals,b.decimals)} ${b.symbol} per ${w.symbol}.`),Pe=D?[D]:[],Se=await Y(o,[...Pe,...j(v,I),B(0n,0n)],a),A=ce(W,Se[Se.length-1]),Ve=A[A.length-2],He=A[A.length-1];if(Ve>v||He>I)throw new c("Simulated liquidity spend exceeds the desired amounts.");let ee=[...Pe,...j(v,I)],ue=ae(e.amount0Min,A[A.length-2],r,"amount0Min"),le=ae(e.amount1Min,A[A.length-1],r,"amount1Min");if(ue>v||le>I)throw new c("Uniswap v3 minimum amount cannot exceed desired amount.");let Ae=B(ue,le);ee.push(Ae);for(let[q,L]of[d,m].entries())(q===0?v:I)>0n&&ee.push(t.approval(L,f.positionManager,"0",k));let qe=await t.preview(ee,a);return{txs:ee,preview:qe,summary:Ie(Ae.description,qe),details:{version:"v3",action:W,...s===void 0?{}:{tokenId:s.toString()},pool:y===C?null:y,fee:p,tickSpacing:T,tickLower:S,tickUpper:N,token0:w,token1:b,amount0Desired:v.toString(),amount1Desired:I.toString(),amount0Min:ue.toString(),amount1Min:le.toString(),deadline:i.toString(),recipient:$,expectedAmount0:A[A.length-2].toString(),expectedAmount1:A[A.length-1].toString(),...P?{poolCreated:!0,sqrtPriceX96:P.sqrtPriceX96.toString(),initialPrice:ie(P.sqrtPriceX96,w.decimals,b.decimals),initialTick:we(P.sqrtPriceX96),priceCheck:P.note}:{}}}}async function rt(t,e,n){O(n);let a=l(n),o=G(t,e),i=E(e.token0,"token0"),r=E(e.token1,"token1");if(BigInt(i)>=BigInt(r))throw new c(`Uniswap v3 requires sorted token addresses (token0 < token1). Use token0=${BigInt(i)<BigInt(r)?i:r}, token1=${BigInt(i)<BigInt(r)?r:i}; initialPrice is token1 per 1 token0 in that order.`);let s=Number(e.fee),u=xe[s];if(!u){let b=Number(await o.readContract({address:f.factory,abi:Q,functionName:"feeAmountTickSpacing",args:[s]}));if(!Number.isInteger(s)||b<=0)throw new c("Unsupported Uniswap v3 fee tier. Enabled tiers: 100, 500, 3000, 10000.");u=b}let d=l(String(await o.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[i,r,s]})));if(d!==C)throw new c(`The Uniswap v3 pool already exists at ${d}. Use uniswap_add to provide liquidity.`);let m=await M(o,i,k,e.token0Decimals),p=await M(o,r,k,e.token1Decimals),g=Be(e,m.decimals,p.decimals),y=be(g,await De(o,i,r,s),e.acceptPriceDeviation===!0,m.decimals,p.decimals),h=ie(g,m.decimals,p.decimals),S=[X(R({abi:x,functionName:"createAndInitializePoolIfNecessary",args:[i,r,s,g]}),`Create and initialize the Uniswap v3 ${m.symbol}/${p.symbol} fee ${s} pool at ${h} ${p.symbol} per ${m.symbol}.`)],N=await Y(o,S,a),T;try{T=l(String(he({abi:x,functionName:"createAndInitializePoolIfNecessary",data:N[0]})))}catch{throw new c("Uniswap v3 pool creation simulation returned an invalid pool address.")}if(T===C)throw new c("Uniswap v3 pool creation simulation returned no pool.");let w=await t.preview(S,a);return{txs:S,preview:w,summary:`${S[0].description} The pool starts empty: nothing trades until liquidity is added with uniswap_add.`,details:{version:"v3",action:"createPool",pool:T,fee:s,tickSpacing:u,token0:m,token1:p,sqrtPriceX96:g.toString(),initialPrice:h,initialTick:we(g),priceCheck:y}}}async function st(t,e,n){O(n);let a=l(n),o=G(t,e),i=J(e.tokenId,"tokenId");if(i<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await ve(o,i,a);let r=await de(o,i),s=await M(o,r.token0,k),u=await M(o,r.token1,k),d=e.recipient===void 0?a:E(e.recipient,"recipient");if(d!==a)throw new c("Uniswap recipient must be the signing wallet.");let m=e.amount0Max===void 0?z:V(e.amount0Max,"amount0Max"),p=e.amount1Max===void 0?z:V(e.amount1Max,"amount1Max");if(m===0n&&p===0n||m>z||p>z)throw new c("Collect requires a positive amountMax within uint128.");let g=[X(R({abi:x,functionName:"collect",args:[{tokenId:i,recipient:d,amount0Max:m,amount1Max:p}]}),`Collect Uniswap v3 fees from position #${i}.`)],y=ce("collect",(await Y(o,g,a))[0]),h=await t.preview(g,a);return{txs:g,preview:h,summary:Ie(g[0].description,h),details:{version:"v3",action:"collect",tokenId:i.toString(),recipient:d,token0:s,token1:u,amount0Max:m.toString(),amount1Max:p.toString(),expectedAmount0:y[0].toString(),expectedAmount1:y[1].toString()}}}async function at(t,e,n){O(n);let a=l(n),o=G(t,e),i=J(e.tokenId,"tokenId");if(i<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await ve(o,i,a);let r=await de(o,i),s=r.liquidity===0n&&e.burn===!0;if(r.liquidity<=0n&&!s)throw new c("Position has zero active liquidity to remove.");if(e.liquidity===void 0&&!s)throw new c('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let u=e.liquidity==="all"||e.liquidity===void 0?r.liquidity:V(e.liquidity,"liquidity");if(u<=0n&&!s)throw new c("Liquidity to remove must be positive.");if(u>r.liquidity)throw new c("Requested liquidity exceeds position liquidity.");let d=await _e(o,e.deadline),m=Ee(e),p=await M(o,r.token0,k),g=await M(o,r.token1,k),y=e.recipient===void 0?a:E(e.recipient,"recipient");if(y!==a)throw new c("Uniswap recipient must be the signing wallet.");let h=(B,D)=>X(R({abi:x,functionName:"decreaseLiquidity",args:[{tokenId:i,liquidity:u,amount0Min:B,amount1Min:D,deadline:d}]}),`Decrease ${u} liquidity on Uniswap v3 position #${i}.`),S=s?[0n,0n]:ce("decreaseLiquidity",(await Y(o,[h(0n,0n)],a))[0]),N=(B,D)=>{if(B!==void 0&&V(B,D)!==0n)throw new c(`${D} must be zero for an empty position burn.`);return 0n},T=s?N(e.amount0Min,"amount0Min"):ae(e.amount0Min,S[0],m,"amount0Min"),w=s?N(e.amount1Min,"amount1Min"):ae(e.amount1Min,S[1],m,"amount1Min"),b=s?[]:[h(T,w)],P=b.length,v=!s||r.tokensOwed0>0n||r.tokensOwed1>0n;v&&b.push(X(R({abi:x,functionName:"collect",args:[{tokenId:i,recipient:y,amount0Max:z,amount1Max:z}]}),`Collect principal and fees from Uniswap v3 position #${i}.`));let I=u===r.liquidity,$=I&&e.burn===!0;$&&b.push(X(R({abi:x,functionName:"burn",args:[i]}),`Burn empty Uniswap v3 position #${i}.`));let H=await Y(o,b,a),j=v?ce("collect",H[P]):[0n,0n],W=await t.preview(b,a);return{txs:b,preview:W,summary:Ie(`Remove Uniswap v3 liquidity from position #${i}${$?`; burns position #${i} at ${f.positionManager}`:""}`,W),details:{version:"v3",action:"remove",tokenId:i.toString(),recipient:y,token0:p,token1:g,liquidityRemoved:u.toString(),amount0Min:T.toString(),amount1Min:w.toString(),deadline:d.toString(),expectedAmount0:j[0].toString(),expectedAmount1:j[1].toString(),fullExit:I,burned:$}}}async function ct(t,e,n={}){let a=l(e),o=new Set;if(Array.isArray(n.tokenIds))for(let r of n.tokenIds){let s=J(r,"tokenId");s>0n&&o.add(s.toString())}if(Array.isArray(n.receipts))for(let r of n.receipts)for(let s of $e(r,a))o.add(s);let i=!1;try{let r=BigInt(await t.readContract({address:f.positionManager,abi:x,functionName:"balanceOf",args:[a]})),s=r>64n?64n:r;for(let u=0n;u<s;u++){try{let d=BigInt(await t.readContract({address:f.positionManager,abi:x,functionName:"tokenOfOwnerByIndex",args:[a,u]}));d>0n&&o.add(d.toString())}catch(d){if(!te(d,3,-32601,-32004))throw d;break}u+1n===r&&(i=!0)}r===0n&&(i=!0)}catch(r){if(!te(r,3,-32601,-32004))throw r}if(typeof t.getLogs=="function"&&typeof t.getBlockNumber=="function")try{let r=n.toBlock??await t.getBlockNumber(),s=n.maxChunks??je,u=n.fromBlock??(r>oe*BigInt(s)?r-oe*BigInt(s)+1n:0n),d=r,m=0;for(;d>=u&&m<s;){let p=d>=oe-1n?d-(oe-1n):0n,g=p<u?u:p,y=await t.getLogs({address:f.positionManager,fromBlock:g,toBlock:d});for(let h of $e({logs:y},a))o.add(h);if(m+=1,g===0n||g<=u)break;d=g-1n}}catch(r){throw new c(`Could not discover Uniswap v3 positions from logs. ${U(r)}`)}else if(!i&&n.tokenIds===void 0&&n.receipts===void 0)throw new c("Uniswap v3 position discovery is unavailable; supply candidate token IDs or receipts.");return[...o].map(r=>BigInt(r)).sort((r,s)=>r<s?-1:r>s?1:0)}async function Oe(t,e,n={}){O(e);let a=l(e),o=G(t),i=await ct(o,a,n),r=[];for(let s of i){let u;try{let w=await o.readContract({address:f.positionManager,abi:x,functionName:"ownerOf",args:[s]});u=l(String(w))}catch(w){if(te(w,3))continue;throw new c(`Could not verify owner of position #${s}. ${U(w)}`)}if(u!==a)continue;let d;try{d=await de(o,s)}catch(w){throw new c(`Could not read position #${s}. ${U(w)}`)}if(d.liquidity===0n&&d.tokensOwed0===0n&&d.tokensOwed1===0n&&!n.includeEmpty)continue;let p=await M(o,d.token0,k),g=await M(o,d.token1,k),y=0n,h=0n;if(d.liquidity>0n)try{let w=await o.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[d.token0,d.token1,d.fee]}),b=l(String(w));if(b===C)throw new c("Position pool was not found.");if(b!==C){let P=await o.readContract({address:b,abi:ke,functionName:"slot0"}),v=BigInt(P[0]);if(v<=0n)throw new c("Position pool has no initialized price.");let I=Re(d.tickLower),$=Re(d.tickUpper),H=nt(v,I,$,d.liquidity);y=H.amount0,h=H.amount1}}catch(w){throw new c(`Could not value Uniswap v3 position #${s}. ${U(w)}`)}let S=y+d.tokensOwed0,N=h+d.tokensOwed1,T=[{token:p,amount:S.toString()},{token:g,amount:N.toString()}];r.push({module:"uniswap",id:`uniswap:v3:${s.toString()}`,chainId:k,assets:T,description:`Uniswap v3 LP position #${s.toString()} (${p.symbol}/${g.symbol} fee ${d.fee} ticks [${d.tickLower}, ${d.tickUpper}] liquidity ${d.liquidity.toString()})`})}return r}async function dt(t,e,n){G(t,e);let a=e.wallet!==void 0?E(e.wallet,"wallet"):l(n),o=Array.isArray(e.tokenIds)?e.tokenIds:void 0,i=Array.isArray(e.receipts)?e.receipts:void 0,r=e.includeZero===!0||e.includeEmpty===!0,s=await Oe(t,a,{tokenIds:o,receipts:i,includeEmpty:r});return{positions:s,details:{version:"v3",wallet:a,count:s.length,positionManager:f.positionManager}}}function ut(t){return[{name:"uniswap_add",inputSchema:{type:"object",description:"Mint a new Uniswap v3 concentrated liquidity position or increase liquidity on an existing v3 NFT position on Robinhood Chain (4663).",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Optional existing v3 NFT tokenId for increaseLiquidity."},token0:{type:"string",description:"Sorted ERC-20 token0 address (e.g. WETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address (e.g. USDG)."},fee:{type:"integer",enum:[100,500,3e3,1e4],default:100},fullRange:{type:"boolean",description:"For a new v3 position, use the widest ticks aligned to the pool fee tier; omit explicit ticks."},tickLower:{type:"integer",description:"Lower tick boundary divisible by tickSpacing."},tickUpper:{type:"integer",description:"Upper tick boundary divisible by tickSpacing."},amount0Desired:{type:"string",description:"Desired token0 amount in decimal base units."},amount1Desired:{type:"string",description:"Desired token1 amount in decimal base units."},amount0Min:{type:"string",description:"Minimum token0 amount in decimal base units."},amount1Min:{type:"string",description:"Minimum token1 amount in decimal base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},wrapNative:{type:"boolean",description:"Optional: wrap native ETH into WETH before minting."},initialPrice:{type:"string",description:"Only when the pool does not exist: starting price as token1 per 1 token0 in human units. The pool is created then liquidity is minted in separately confirmed transactions."},sqrtPriceX96:{type:"string",description:"Alternative to initialPrice: exact starting sqrtPriceX96."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 bps from other live pools of the pair."}}},execute:(r,s)=>ot(t,r,s)},{name:"uniswap_collect",inputSchema:{type:"object",description:"Collect accrued Uniswap v3 LP fees for an owned NonfungiblePositionManager NFT.",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Uniswap v3 NFT tokenId."},recipient:{type:"string",description:"Optional fee recipient; must be the signing wallet."},amount0Max:{type:"string",description:"Max token0 to collect (defaults to uint128 max)."},amount1Max:{type:"string",description:"Max token1 to collect (defaults to uint128 max)."}},required:["tokenId"]},execute:(r,s)=>st(t,r,s)},{name:"uniswap_remove",inputSchema:{type:"object",description:"Decrease liquidity on an owned Uniswap v3 NFT position, collect principal and fees, and optionally burn the empty NFT.",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Uniswap v3 NFT tokenId."},liquidity:{type:"string",description:"Positive base-unit liquidity amount, or all for a full exit."},amount0Min:{type:"string",description:"Minimum token0 principal in decimal base units."},amount1Min:{type:"string",description:"Minimum token1 principal in decimal base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},burn:{type:"boolean",description:"Whether to burn the NFT after removing 100% of liquidity, or burn an already-empty position."}},required:["tokenId"]},execute:(r,s)=>at(t,r,s)},{name:"uniswap_list_positions",inputSchema:{type:"object",description:"List active Uniswap v3 LP positions owned by the wallet from NFT receipts and Transfer logs.",properties:{version:{type:"string",enum:["v3"],default:"v3"},wallet:{type:"string",description:"Optional wallet address override."},tokenIds:{type:"array",items:{type:"string"},description:"Optional candidate v3 NFT tokenIds to inspect."}}},execute:(r,s)=>dt(t,r,s)},{name:"uniswap_create_pool",inputSchema:{type:"object",description:"Create and initialize an empty Uniswap v3 pool on Robinhood Chain (4663). Add liquidity afterwards with uniswap_add.",properties:{version:{type:"string",enum:["v3"],default:"v3"},token0:{type:"string",description:"Sorted ERC-20 token0 address (WETH, not native ETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address."},fee:{type:"integer",enum:[100,500,3e3,1e4]},initialPrice:{type:"string",description:'Starting price as token1 per 1 token0 in human units, e.g. "3000" for 1 WETH = 3000 USDG.'},sqrtPriceX96:{type:"string",description:"Alternative to initialPrice: exact starting sqrtPriceX96."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 bps from other live pools of the pair."}},required:["token0","token1","fee"]},execute:(r,s)=>rt(t,r,s)}]}var Xe=t=>({tools:ut(t),positions:e=>Oe(t,e)}),xt=Xe,vt=Xe;export{re as a,se as b,z as c,f as d,xe as e,yt as f,x as g,Q as h,ke as i,Qe as j,Je as k,et as l,tt as m,$e as n,ht as o,Be as p,ot as q,rt as r,st as s,at as t,Oe as u,dt as v,ut as w,Xe as x,xt as y,vt as z};
|
|
1
|
+
import{c as Ce,d as Me,e as we,f as ie,i as be,j as Ne}from"./3ACEWCKZ.js";import{b as ne,o as ge}from"./CAU44UWP.js";import{a as O,b as pe}from"./6IM6A5VA.js";import{a as Te}from"./EG6M6SSO.js";import{a as F,c as Ue}from"./RETS2ZEK.js";import{a as k,i as _}from"./XPFVT2EA.js";import{a as c,b as te,d as U}from"./5YS5V2LK.js";import{decodeFunctionResult as he,encodeFunctionData as R,getAddress as l,parseAbi as Z,zeroAddress as C}from"viem";var re=-887272,se=887272,z=(1n<<128n)-1n,Fe="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",ze="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",Ge="0x3067048beee31b25b2f1681f88dac838c8bba36af25bfb2b7cf7473a5847e35f",oe=2000n,je=5,Ke=1800n,f=Object.freeze({factory:l(_[4663].uniswap.v3_factory.address),positionManager:l(_[4663].uniswap.v3_position_manager.address),swapRouter02:l(_[4663].uniswap.swap_router02.address),permit2:l(_[4663].uniswap.permit2.address),weth:l(_[4663].uniswap.WETH.address),usdg:l(_[4663].uniswap.USDG.address),ethUsdgPool:l(_[4663].oracle.ethUsdgPool.address)}),xe=Object.freeze({100:1,500:10,3e3:60,1e4:200}),yt=Object.freeze([{fee:100,tickSpacing:1,address:l("0x52e65B17fB6E5BA00Ed806f37Afcd2DaA50271Ca"),token0:f.weth,token1:f.usdg,recordedLiquidity:"1957537485734736219",recordedSqrtPriceX96:"3839219776288481168641554",recordedTick:-198707,feeProtocol:68},{fee:500,tickSpacing:10,address:l("0x69bfaf19c9f377bb306a89aed9f6b07e2c1a8d9a"),token0:f.weth,token1:f.usdg,recordedLiquidity:"714542894544667104",recordedSqrtPriceX96:"3839644024453020182443671",recordedTick:-198705,feeProtocol:68},{fee:3e3,tickSpacing:60,address:l("0xa9188730fe85be88ad499d7d52b099e800fb0334"),token0:f.weth,token1:f.usdg,recordedLiquidity:"310559629687003603",recordedSqrtPriceX96:"3843235825752878635548672",recordedTick:-198686,feeProtocol:102},{fee:1e4,tickSpacing:200,address:l("0x5f009e071f07e92b6c624e83f52f17bbda34680d"),token0:f.weth,token1:f.usdg,recordedLiquidity:"5822966536584155",recordedSqrtPriceX96:"3853297838190389678059735",recordedTick:-198634,feeProtocol:102}]),x=Z(["function positions(uint256 tokenId) view returns (uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1)","function ownerOf(uint256 tokenId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)","function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline) params) payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)","function increaseLiquidity((uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint128 liquidity, uint256 amount0, uint256 amount1)","function decreaseLiquidity((uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint256 amount0, uint256 amount1)","function collect((uint256 tokenId, address recipient, uint128 amount0Max, uint128 amount1Max) params) payable returns (uint256 amount0, uint256 amount1)","function burn(uint256 tokenId) payable","function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96) payable returns (address pool)"]),Q=Z(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)","function feeAmountTickSpacing(uint24 fee) view returns (int24)"]),ke=Z(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickSpacing() view returns (int24)","function fee() view returns (uint24)","function token0() view returns (address)","function token1() view returns (address)"]),Qe=Z(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),ye=Z(["function decimals() view returns (uint8)","function symbol() view returns (string)","function allowance(address owner, address spender) view returns (uint256)"]),Ye="0xd0e30db0";function Ze(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e===C||e===Fe||e==="eth"||e==="native"}function E(t,e){if(Ze(t))throw new c(`Uniswap v3 requires wrapped ERC-20 WETH (${f.weth}) rather than native ETH in ${e}.`);if(typeof t!="string")throw new c(`${e} must be a valid 20-byte hex address.`);return O(t),l(t)}function Je(t,e,n){let a=Number(t),o=Number(e),i=Number(n);if(!Number.isInteger(i)||i<=0)throw new c("Uniswap v3 tickSpacing must be a positive integer.");if(!Number.isInteger(a)||!Number.isInteger(o))throw new c("Uniswap v3 tickLower and tickUpper must be integers.");if(a<re||o>se||a>se||o<re)throw new c(`Uniswap v3 ticks are out of bounds [${re}, ${se}].`);if(a>=o)throw new c("Uniswap v3 tickLower must be strictly less than tickUpper.");if(a%i!==0||o%i!==0)throw new c(`Uniswap v3 tickLower (${a}) and tickUpper (${o}) must be divisible by tickSpacing (${i}).`);return{tickLower:a,tickUpper:o,tickSpacing:i}}function et(t,e){let n=t.trim(),a=n.startsWith("-"),o=a||n.startsWith("+")?n.slice(1):n,i=Ue(F(o).toString(),e);return a&&i!=="0"?`-${i}`:i}function tt(t){let e=typeof t=="string"?he({abi:x,functionName:"positions",data:t}):t;return{nonce:BigInt(e[0]),operator:l(String(e[1])),token0:l(String(e[2])),token1:l(String(e[3])),fee:Number(e[4]),tickLower:Number(e[5]),tickUpper:Number(e[6]),liquidity:BigInt(e[7]),feeGrowthInside0LastX128:BigInt(e[8]),feeGrowthInside1LastX128:BigInt(e[9]),tokensOwed0:BigInt(e[10]),tokensOwed1:BigInt(e[11])}}function $e(t,e){if(!t||!Array.isArray(t.logs))return[];let n=e?l(e).toLowerCase():void 0,a=f.positionManager.toLowerCase(),o=new Set;for(let i of t.logs){if(!i||typeof i.address!="string"||i.address.toLowerCase()!==a)continue;let r=Array.isArray(i.topics)?i.topics.map(u=>String(u).toLowerCase()):[],s=r[0];if(s===ze&&r.length>=4){let d=`0x${r[2].slice(-40)}`;if(!n||d===n){let m=BigInt(r[3]).toString();m!=="0"&&o.add(m)}}else if(s===Ge&&r.length>=2&&!n){let u=BigInt(r[1]).toString();u!=="0"&&o.add(u)}}return[...o]}function ht(t){let e=n=>typeof n=="bigint"?n:F(n);return R({abi:Qe,functionName:"exactInputSingle",args:[{tokenIn:l(t.tokenIn),tokenOut:l(t.tokenOut),fee:t.fee,recipient:l(t.recipient),amountIn:e(t.amountIn),amountOutMinimum:e(t.amountOutMinimum),sqrtPriceLimitX96:t.sqrtPriceLimitX96!==void 0?e(t.sqrtPriceLimitX96):0n}]})}var Le=1n<<96n;function Re(t){let e=Math.abs(t),n=(e&1)!==0?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&2)!==0&&(n=n*0xfff97272373d413259a46990580e213an>>128n),(e&4)!==0&&(n=n*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&8)!==0&&(n=n*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&16)!==0&&(n=n*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&32)!==0&&(n=n*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&64)!==0&&(n=n*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&128)!==0&&(n=n*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&256)!==0&&(n=n*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&512)!==0&&(n=n*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&1024)!==0&&(n=n*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&2048)!==0&&(n=n*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&4096)!==0&&(n=n*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&8192)!==0&&(n=n*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&16384)!==0&&(n=n*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&32768)!==0&&(n=n*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&65536)!==0&&(n=n*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&131072)!==0&&(n=n*0x5d6af8dedb81196699c329225ee604n>>128n),(e&262144)!==0&&(n=n*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&524288)!==0&&(n=n*0x48a170391f7dc42444e8fa2n>>128n),t>0&&(n=((1n<<256n)-1n)/n),(n>>32n)+(n%(1n<<32n)===0n?0n:1n)}function nt(t,e,n,a){if(a<=0n)return{amount0:0n,amount1:0n};let[o,i]=e<n?[e,n]:[n,e];if(t<=o)return{amount0:(a<<96n)*(i-o)/i/o,amount1:0n};if(t<i){let s=(a<<96n)*(i-t)/i/t,u=a*(t-o)/Le;return{amount0:s,amount1:u}}return{amount0:0n,amount1:a*(i-o)/Le}}async function M(t,e,n,a){let o=l(e),i,r;if(n===k&&o===f.weth?(i=18,r="WETH"):n===k&&o===f.usdg&&(i=6,r="USDG"),i===void 0){let s=await t.readContract({address:o,abi:ye,functionName:"decimals"});i=Number(s)}if(r===void 0)try{let s=await t.readContract({address:o,abi:ye,functionName:"symbol"});if(typeof s!="string"||!s.trim())throw new c("Token symbol is unavailable.");r=Ne(s.trim(),o)}catch(s){throw new c(`Could not read token metadata. ${U(s)}`)}if(!Number.isInteger(i)||i<0||i>255)throw new c("Token decimals are invalid.");if(a!=null){let s=Number(a);if(!Number.isInteger(s)||s!==i)throw new c(`Token ${o} on chain ${n} has ${i} decimals, not ${String(a)}.`)}return{address:o,symbol:r,decimals:i,chainId:n}}async function it(t){try{if(!t.getBlock)throw new c("Block timestamps are unavailable.");let e=await t.getBlock();if(typeof e.timestamp!="bigint")throw new c("Invalid block timestamp.");return e.timestamp}catch(e){throw new c(`Could not read the current block timestamp. ${U(e)}`)}}function J(t,e){if(typeof t=="bigint"){if(t<0n)throw new c(`${e} must be a non-negative integer.`);return t}if(typeof t=="number"){if(!Number.isSafeInteger(t)||t<0)throw new c(`${e} must be a non-negative integer.`);return BigInt(t)}if(typeof t=="string")return F(t);throw new c(`${e} must be a non-negative integer.`)}async function _e(t,e){let n=await it(t);if(e==null)return n+Ke;let a=J(e,"deadline");if(a<=n)throw new c(`Uniswap v3 deadline (${a.toString()}) has expired at timestamp ${n.toString()}.`);return a}function V(t,e){if(typeof t!="string"||!/^\d+$/.test(t))throw new c(`${e} must be a non-negative integer string in base units.`);return F(t)}function Ee(t){let e=t.slippageBps??ne;if(typeof e!="number")throw new c("Slippage must be an integer from 0 to 9999 bps.");return ge("0",e),e}function ae(t,e,n,a){let o=t===void 0?F(ge(e.toString(),n)):V(t,a);if(o<=1n)throw new c(`${a} must exceed 1 base unit; the simulated amount may be too small.`);return o}function X(t,e){return pe({to:f.positionManager,data:t,value:"0",chainId:k,description:e})}async function Y(t,e,n){try{if(!t.request)throw new c("Sequential transaction simulation is unavailable.");let o=await t.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:n,gas:`0x${Te.toString(16)}`,to:i.to,data:i.data,value:`0x${BigInt(i.value).toString(16)}`}))}],validation:!1,traceTransfers:!0},"latest"]},{retryCount:0});if(!Array.isArray(o)||o.length!==1||!Array.isArray(o[0]?.calls)||o[0].calls.length!==e.length)throw new c("Unexpected batch simulation response.");return o[0].calls.map((i,r)=>{if(i.status!=="0x1"||i.error||typeof i.returnData!="string"||!/^0x([a-fA-F0-9]{2})*$/.test(i.returnData))throw new c(`Simulation call ${r+1} failed. ${U(i.error)}`);return i.returnData})}catch(a){throw new c(`Uniswap v3 simulation failed. ${U(a)}`)}}function ce(t,e){try{return he({abi:x,functionName:t,data:e})}catch{throw new c(`Uniswap v3 ${t} simulation returned invalid amounts.`)}}function Be(t,e,n){if(t.initialPrice!==void 0&&t.sqrtPriceX96!==void 0)throw new c("Provide initialPrice or sqrtPriceX96, not both.");if(t.sqrtPriceX96!==void 0){if(typeof t.sqrtPriceX96!="string"||!/^\d+$/.test(t.sqrtPriceX96))throw new c("sqrtPriceX96 must be a non-negative integer string.");return Me(BigInt(t.sqrtPriceX96))}if(t.initialPrice===void 0)throw new c("A new pool needs initialPrice (token1 per 1 token0, human units) or sqrtPriceX96.");return Ce(t.initialPrice,e,n)}async function De(t,e,n,a){let o=[];for(let i of Object.keys(xe).map(Number)){if(i===a)continue;let r=l(String(await t.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[e,n,i]})));if(r===C||BigInt(await t.readContract({address:r,abi:ke,functionName:"liquidity"}))===0n)continue;let u=await t.readContract({address:r,abi:ke,functionName:"slot0"});o.push({label:`v3 fee ${i} pool ${r}`,sqrtPriceX96:BigInt(u[0])})}return o}function G(t,e={}){if(e.chainId!==void 0&&Number(e.chainId)!==k)throw new c(`Uniswap v3 is only supported on Robinhood Chain (${k}).`);if(e.version!==void 0&&e.version!=="v3")throw new c(`Uniswap v3 handler received unsupported version "${String(e.version)}".`);let n=t.clientFor(k);return{...n,readContract:async a=>{try{return await n.readContract(a)}catch(o){throw new c(`Could not read Uniswap v3 ${a.functionName}. ${U(o)}`,{cause:o})}}}}async function ve(t,e,n){let a;try{a=await t.readContract({address:f.positionManager,abi:x,functionName:"ownerOf",args:[e]})}catch(r){throw new c(`Could not verify owner of Uniswap v3 position #${e}. ${U(r)}`)}let o=l(String(a)),i=l(n);if(o!==i)throw new c(`Wallet ${i} is not the owner of Uniswap v3 position #${e.toString()} (owned by ${o}).`);return o}async function de(t,e){let n=await t.readContract({address:f.positionManager,abi:x,functionName:"positions",args:[e]});return tt(n)}function Ie(t,e){if(!Array.isArray(e.changes)||!e.changes.length)return t;let n=e.changes.map(a=>`${et(a.amount,a.token.decimals)} ${a.token.symbol}`);return`${t} (${n.join(", ")})`}async function ot(t,e,n){O(n);let a=l(n),o=G(t,e),i=await _e(o,e.deadline),r=Ee(e),s=e.tokenId===void 0?void 0:J(e.tokenId,"tokenId"),u;if(s!==void 0){if(s<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await ve(o,s,a),u=await de(o,s)}let d=u?.token0??E(e.token0,"token0"),m=u?.token1??E(e.token1,"token1");if(BigInt(d)>=BigInt(m))throw new c("Uniswap v3 requires distinct sorted token addresses.");let p=u?.fee??Number(e.fee??100),g=xe[p];if(!g)throw new c("Unsupported Uniswap v3 fee tier.");let y=l(String(await o.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[d,m,p]}))),h=e.initialPrice!==void 0||e.sqrtPriceX96!==void 0;if(y===C&&!h)throw new c("No Uniswap v3 pool exists for these tokens and fee tier. To create it and add the first liquidity in one tool call with separately confirmed transactions, add initialPrice (token1 per 1 token0, human units) to this call; to create it without liquidity use uniswap_create_pool.");if(y!==C&&h)throw new c(`The Uniswap v3 pool already exists at ${y}; remove initialPrice/sqrtPriceX96 to add liquidity at its current price.`);if(s!==void 0&&h)throw new c("initialPrice cannot be combined with tokenId.");if(e.fullRange!==void 0&&typeof e.fullRange!="boolean")throw new c("fullRange must be a boolean.");if(e.fullRange===!0&&(e.tickLower!==void 0||e.tickUpper!==void 0||u))throw new c("Use fullRange only for a new position, without explicit ticks. Existing position ticks cannot change.");let{tickLower:S,tickUpper:N,tickSpacing:T}=Je(u?.tickLower??(e.fullRange===!0?Math.ceil(re/g)*g:e.tickLower),u?.tickUpper??(e.fullRange===!0?Math.floor(se/g)*g:e.tickUpper),g),w=await M(o,d,k,e.token0Decimals),b=await M(o,m,k,e.token1Decimals),P;if(y===C){let q=Be(e,w.decimals,b.decimals),L=be(q,await De(o,d,m,p),e.acceptPriceDeviation===!0,w.decimals,b.decimals);P={sqrtPriceX96:q,note:L}}let v=V(e.amount0Desired,"amount0Desired"),I=V(e.amount1Desired,"amount1Desired");if(v===0n&&I===0n)throw new c("Liquidity addition requires a positive desired amount.");let $=e.recipient===void 0?a:E(e.recipient,"recipient");if($!==a)throw new c("Uniswap recipient must be the signing wallet.");if(e.wrapNative===!0&&d!==f.weth&&m!==f.weth)throw new c("Wrapping requires a positive WETH desired amount.");let H=await Promise.all([d,m].map(async q=>BigInt(await o.readContract({address:q,abi:ye,functionName:"allowance",args:[a,f.positionManager]})))),j=(q,L)=>{let fe=[];if(e.wrapNative===!0){let K=d===f.weth?q:L;K>0n&&fe.push(pe({to:f.weth,data:Ye,value:K.toString(),chainId:k,description:"Wrap ETH into WETH."}))}for(let[K,We]of[d,m].entries()){let me=K===0?q:L;me>0n&&H[K]<me&&fe.push(t.approval(We,f.positionManager,me.toString(),k))}return fe},W=s===void 0?"mint":"increaseLiquidity",B=(q,L)=>X(s===void 0?R({abi:x,functionName:"mint",args:[{token0:d,token1:m,fee:p,tickLower:S,tickUpper:N,amount0Desired:v,amount1Desired:I,amount0Min:q,amount1Min:L,recipient:$,deadline:i}]}):R({abi:x,functionName:"increaseLiquidity",args:[{tokenId:s,amount0Desired:v,amount1Desired:I,amount0Min:q,amount1Min:L,deadline:i}]}),`${W==="mint"?"Mint":"Increase"} Uniswap v3 ${w.symbol}/${b.symbol} liquidity.`),D=P&&X(R({abi:x,functionName:"createAndInitializePoolIfNecessary",args:[d,m,p,P.sqrtPriceX96]}),`Create and initialize the Uniswap v3 ${w.symbol}/${b.symbol} fee ${p} pool at ${ie(P.sqrtPriceX96,w.decimals,b.decimals)} ${b.symbol} per ${w.symbol}.`),Pe=D?[D]:[],Se=await Y(o,[...Pe,...j(v,I),B(0n,0n)],a),A=ce(W,Se[Se.length-1]),Ve=A[A.length-2],He=A[A.length-1];if(Ve>v||He>I)throw new c("Simulated liquidity spend exceeds the desired amounts.");let ee=[...Pe,...j(v,I)],ue=ae(e.amount0Min,A[A.length-2],r,"amount0Min"),le=ae(e.amount1Min,A[A.length-1],r,"amount1Min");if(ue>v||le>I)throw new c("Uniswap v3 minimum amount cannot exceed desired amount.");let Ae=B(ue,le);ee.push(Ae);for(let[q,L]of[d,m].entries())(q===0?v:I)>0n&&ee.push(t.approval(L,f.positionManager,"0",k));let qe=await t.preview(ee,a);return{txs:ee,preview:qe,summary:Ie(Ae.description,qe),details:{version:"v3",action:W,...s===void 0?{}:{tokenId:s.toString()},pool:y===C?null:y,fee:p,tickSpacing:T,tickLower:S,tickUpper:N,token0:w,token1:b,amount0Desired:v.toString(),amount1Desired:I.toString(),amount0Min:ue.toString(),amount1Min:le.toString(),deadline:i.toString(),recipient:$,expectedAmount0:A[A.length-2].toString(),expectedAmount1:A[A.length-1].toString(),...P?{poolCreated:!0,sqrtPriceX96:P.sqrtPriceX96.toString(),initialPrice:ie(P.sqrtPriceX96,w.decimals,b.decimals),initialTick:we(P.sqrtPriceX96),priceCheck:P.note}:{}}}}async function rt(t,e,n){O(n);let a=l(n),o=G(t,e),i=E(e.token0,"token0"),r=E(e.token1,"token1");if(BigInt(i)>=BigInt(r))throw new c(`Uniswap v3 requires sorted token addresses (token0 < token1). Use token0=${BigInt(i)<BigInt(r)?i:r}, token1=${BigInt(i)<BigInt(r)?r:i}; initialPrice is token1 per 1 token0 in that order.`);let s=Number(e.fee),u=xe[s];if(!u){let b=Number(await o.readContract({address:f.factory,abi:Q,functionName:"feeAmountTickSpacing",args:[s]}));if(!Number.isInteger(s)||b<=0)throw new c("Unsupported Uniswap v3 fee tier. Enabled tiers: 100, 500, 3000, 10000.");u=b}let d=l(String(await o.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[i,r,s]})));if(d!==C)throw new c(`The Uniswap v3 pool already exists at ${d}. Use uniswap_add to provide liquidity.`);let m=await M(o,i,k,e.token0Decimals),p=await M(o,r,k,e.token1Decimals),g=Be(e,m.decimals,p.decimals),y=be(g,await De(o,i,r,s),e.acceptPriceDeviation===!0,m.decimals,p.decimals),h=ie(g,m.decimals,p.decimals),S=[X(R({abi:x,functionName:"createAndInitializePoolIfNecessary",args:[i,r,s,g]}),`Create and initialize the Uniswap v3 ${m.symbol}/${p.symbol} fee ${s} pool at ${h} ${p.symbol} per ${m.symbol}.`)],N=await Y(o,S,a),T;try{T=l(String(he({abi:x,functionName:"createAndInitializePoolIfNecessary",data:N[0]})))}catch{throw new c("Uniswap v3 pool creation simulation returned an invalid pool address.")}if(T===C)throw new c("Uniswap v3 pool creation simulation returned no pool.");let w=await t.preview(S,a);return{txs:S,preview:w,summary:`${S[0].description} The pool starts empty: nothing trades until liquidity is added with uniswap_add.`,details:{version:"v3",action:"createPool",pool:T,fee:s,tickSpacing:u,token0:m,token1:p,sqrtPriceX96:g.toString(),initialPrice:h,initialTick:we(g),priceCheck:y}}}async function st(t,e,n){O(n);let a=l(n),o=G(t,e),i=J(e.tokenId,"tokenId");if(i<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await ve(o,i,a);let r=await de(o,i),s=await M(o,r.token0,k),u=await M(o,r.token1,k),d=e.recipient===void 0?a:E(e.recipient,"recipient");if(d!==a)throw new c("Uniswap recipient must be the signing wallet.");let m=e.amount0Max===void 0?z:V(e.amount0Max,"amount0Max"),p=e.amount1Max===void 0?z:V(e.amount1Max,"amount1Max");if(m===0n&&p===0n||m>z||p>z)throw new c("Collect requires a positive amountMax within uint128.");let g=[X(R({abi:x,functionName:"collect",args:[{tokenId:i,recipient:d,amount0Max:m,amount1Max:p}]}),`Collect Uniswap v3 fees from position #${i}.`)],y=ce("collect",(await Y(o,g,a))[0]),h=await t.preview(g,a);return{txs:g,preview:h,summary:Ie(g[0].description,h),details:{version:"v3",action:"collect",tokenId:i.toString(),recipient:d,token0:s,token1:u,amount0Max:m.toString(),amount1Max:p.toString(),expectedAmount0:y[0].toString(),expectedAmount1:y[1].toString()}}}async function at(t,e,n){O(n);let a=l(n),o=G(t,e),i=J(e.tokenId,"tokenId");if(i<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await ve(o,i,a);let r=await de(o,i),s=r.liquidity===0n&&e.burn===!0;if(r.liquidity<=0n&&!s)throw new c("Position has zero active liquidity to remove.");if(e.liquidity===void 0&&!s)throw new c('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let u=e.liquidity==="all"||e.liquidity===void 0?r.liquidity:V(e.liquidity,"liquidity");if(u<=0n&&!s)throw new c("Liquidity to remove must be positive.");if(u>r.liquidity)throw new c("Requested liquidity exceeds position liquidity.");let d=await _e(o,e.deadline),m=Ee(e),p=await M(o,r.token0,k),g=await M(o,r.token1,k),y=e.recipient===void 0?a:E(e.recipient,"recipient");if(y!==a)throw new c("Uniswap recipient must be the signing wallet.");let h=(B,D)=>X(R({abi:x,functionName:"decreaseLiquidity",args:[{tokenId:i,liquidity:u,amount0Min:B,amount1Min:D,deadline:d}]}),`Decrease ${u} liquidity on Uniswap v3 position #${i}.`),S=s?[0n,0n]:ce("decreaseLiquidity",(await Y(o,[h(0n,0n)],a))[0]),N=(B,D)=>{if(B!==void 0&&V(B,D)!==0n)throw new c(`${D} must be zero for an empty position burn.`);return 0n},T=s?N(e.amount0Min,"amount0Min"):ae(e.amount0Min,S[0],m,"amount0Min"),w=s?N(e.amount1Min,"amount1Min"):ae(e.amount1Min,S[1],m,"amount1Min"),b=s?[]:[h(T,w)],P=b.length,v=!s||r.tokensOwed0>0n||r.tokensOwed1>0n;v&&b.push(X(R({abi:x,functionName:"collect",args:[{tokenId:i,recipient:y,amount0Max:z,amount1Max:z}]}),`Collect principal and fees from Uniswap v3 position #${i}.`));let I=u===r.liquidity,$=I&&e.burn===!0;$&&b.push(X(R({abi:x,functionName:"burn",args:[i]}),`Burn empty Uniswap v3 position #${i}.`));let H=await Y(o,b,a),j=v?ce("collect",H[P]):[0n,0n],W=await t.preview(b,a);return{txs:b,preview:W,summary:Ie(`Remove Uniswap v3 liquidity from position #${i}${$?`; burns position #${i} at ${f.positionManager}`:""}`,W),details:{version:"v3",action:"remove",tokenId:i.toString(),recipient:y,token0:p,token1:g,liquidityRemoved:u.toString(),amount0Min:T.toString(),amount1Min:w.toString(),deadline:d.toString(),expectedAmount0:j[0].toString(),expectedAmount1:j[1].toString(),fullExit:I,burned:$}}}async function ct(t,e,n={}){let a=l(e),o=new Set;if(Array.isArray(n.tokenIds))for(let r of n.tokenIds){let s=J(r,"tokenId");s>0n&&o.add(s.toString())}if(Array.isArray(n.receipts))for(let r of n.receipts)for(let s of $e(r,a))o.add(s);let i=!1;try{let r=BigInt(await t.readContract({address:f.positionManager,abi:x,functionName:"balanceOf",args:[a]})),s=r>64n?64n:r;for(let u=0n;u<s;u++){try{let d=BigInt(await t.readContract({address:f.positionManager,abi:x,functionName:"tokenOfOwnerByIndex",args:[a,u]}));d>0n&&o.add(d.toString())}catch(d){if(!te(d,3,-32601,-32004))throw d;break}u+1n===r&&(i=!0)}r===0n&&(i=!0)}catch(r){if(!te(r,3,-32601,-32004))throw r}if(typeof t.getLogs=="function"&&typeof t.getBlockNumber=="function")try{let r=n.toBlock??await t.getBlockNumber(),s=n.maxChunks??je,u=n.fromBlock??(r>oe*BigInt(s)?r-oe*BigInt(s)+1n:0n),d=r,m=0;for(;d>=u&&m<s;){let p=d>=oe-1n?d-(oe-1n):0n,g=p<u?u:p,y=await t.getLogs({address:f.positionManager,fromBlock:g,toBlock:d});for(let h of $e({logs:y},a))o.add(h);if(m+=1,g===0n||g<=u)break;d=g-1n}}catch(r){throw new c(`Could not discover Uniswap v3 positions from logs. ${U(r)}`)}else if(!i&&n.tokenIds===void 0&&n.receipts===void 0)throw new c("Uniswap v3 position discovery is unavailable; supply candidate token IDs or receipts.");return[...o].map(r=>BigInt(r)).sort((r,s)=>r<s?-1:r>s?1:0)}async function Oe(t,e,n={}){O(e);let a=l(e),o=G(t),i=await ct(o,a,n),r=[];for(let s of i){let u;try{let w=await o.readContract({address:f.positionManager,abi:x,functionName:"ownerOf",args:[s]});u=l(String(w))}catch(w){if(te(w,3))continue;throw new c(`Could not verify owner of position #${s}. ${U(w)}`)}if(u!==a)continue;let d;try{d=await de(o,s)}catch(w){throw new c(`Could not read position #${s}. ${U(w)}`)}if(d.liquidity===0n&&d.tokensOwed0===0n&&d.tokensOwed1===0n&&!n.includeEmpty)continue;let p=await M(o,d.token0,k),g=await M(o,d.token1,k),y=0n,h=0n;if(d.liquidity>0n)try{let w=await o.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[d.token0,d.token1,d.fee]}),b=l(String(w));if(b===C)throw new c("Position pool was not found.");if(b!==C){let P=await o.readContract({address:b,abi:ke,functionName:"slot0"}),v=BigInt(P[0]);if(v<=0n)throw new c("Position pool has no initialized price.");let I=Re(d.tickLower),$=Re(d.tickUpper),H=nt(v,I,$,d.liquidity);y=H.amount0,h=H.amount1}}catch(w){throw new c(`Could not value Uniswap v3 position #${s}. ${U(w)}`)}let S=y+d.tokensOwed0,N=h+d.tokensOwed1,T=[{token:p,amount:S.toString()},{token:g,amount:N.toString()}];r.push({module:"uniswap",id:`uniswap:v3:${s.toString()}`,chainId:k,assets:T,description:`Uniswap v3 LP position #${s.toString()} (${p.symbol}/${g.symbol} fee ${d.fee} ticks [${d.tickLower}, ${d.tickUpper}] liquidity ${d.liquidity.toString()})`})}return r}async function dt(t,e,n){G(t,e);let a=e.wallet!==void 0?E(e.wallet,"wallet"):l(n),o=Array.isArray(e.tokenIds)?e.tokenIds:void 0,i=Array.isArray(e.receipts)?e.receipts:void 0,r=e.includeZero===!0||e.includeEmpty===!0,s=await Oe(t,a,{tokenIds:o,receipts:i,includeEmpty:r});return{positions:s,details:{version:"v3",wallet:a,count:s.length,positionManager:f.positionManager}}}function ut(t){return[{name:"uniswap_add",inputSchema:{type:"object",description:"Mint a new Uniswap v3 concentrated liquidity position or increase liquidity on an existing v3 NFT position on Robinhood Chain (4663).",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Optional existing v3 NFT tokenId for increaseLiquidity."},token0:{type:"string",description:"Sorted ERC-20 token0 address (e.g. WETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address (e.g. USDG)."},fee:{type:"integer",enum:[100,500,3e3,1e4],default:100},fullRange:{type:"boolean",description:"For a new v3 position, use the widest ticks aligned to the pool fee tier; omit explicit ticks."},tickLower:{type:"integer",description:"Lower tick boundary divisible by tickSpacing."},tickUpper:{type:"integer",description:"Upper tick boundary divisible by tickSpacing."},amount0Desired:{type:"string",description:"Desired token0 amount in decimal base units."},amount1Desired:{type:"string",description:"Desired token1 amount in decimal base units."},amount0Min:{type:"string",description:"Minimum token0 amount in decimal base units."},amount1Min:{type:"string",description:"Minimum token1 amount in decimal base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},wrapNative:{type:"boolean",description:"Optional: wrap native ETH into WETH before minting."},initialPrice:{type:"string",description:"Only when the pool does not exist: starting price as token1 per 1 token0 in human units. The pool is created then liquidity is minted in separately confirmed transactions."},sqrtPriceX96:{type:"string",description:"Alternative to initialPrice: exact starting sqrtPriceX96."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 bps from other live pools of the pair."}}},execute:(r,s)=>ot(t,r,s)},{name:"uniswap_collect",inputSchema:{type:"object",description:"Collect accrued Uniswap v3 LP fees for an owned NonfungiblePositionManager NFT.",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Uniswap v3 NFT tokenId."},recipient:{type:"string",description:"Optional fee recipient; must be the signing wallet."},amount0Max:{type:"string",description:"Max token0 to collect (defaults to uint128 max)."},amount1Max:{type:"string",description:"Max token1 to collect (defaults to uint128 max)."}},required:["tokenId"]},execute:(r,s)=>st(t,r,s)},{name:"uniswap_remove",inputSchema:{type:"object",description:"Decrease liquidity on an owned Uniswap v3 NFT position, collect principal and fees, and optionally burn the empty NFT.",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Uniswap v3 NFT tokenId."},liquidity:{type:"string",description:"Positive base-unit liquidity amount, or all for a full exit."},amount0Min:{type:"string",description:"Minimum token0 principal in decimal base units."},amount1Min:{type:"string",description:"Minimum token1 principal in decimal base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},burn:{type:"boolean",description:"Whether to burn the NFT after removing 100% of liquidity, or burn an already-empty position."}},required:["tokenId"]},execute:(r,s)=>at(t,r,s)},{name:"uniswap_list_positions",inputSchema:{type:"object",description:"List active Uniswap v3 LP positions owned by the wallet from NFT receipts and Transfer logs.",properties:{version:{type:"string",enum:["v3"],default:"v3"},wallet:{type:"string",description:"Optional wallet address override."},tokenIds:{type:"array",items:{type:"string"},description:"Optional candidate v3 NFT tokenIds to inspect."}}},execute:(r,s)=>dt(t,r,s)},{name:"uniswap_create_pool",inputSchema:{type:"object",description:"Create and initialize an empty Uniswap v3 pool on Robinhood Chain (4663). Add liquidity afterwards with uniswap_add.",properties:{version:{type:"string",enum:["v3"],default:"v3"},token0:{type:"string",description:"Sorted ERC-20 token0 address (WETH, not native ETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address."},fee:{type:"integer",enum:[100,500,3e3,1e4]},initialPrice:{type:"string",description:'Starting price as token1 per 1 token0 in human units, e.g. "3000" for 1 WETH = 3000 USDG.'},sqrtPriceX96:{type:"string",description:"Alternative to initialPrice: exact starting sqrtPriceX96."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 bps from other live pools of the pair."}},required:["token0","token1","fee"]},execute:(r,s)=>rt(t,r,s)}]}var Xe=t=>({tools:ut(t),positions:e=>Oe(t,e)}),xt=Xe,vt=Xe;export{re as a,se as b,z as c,f as d,xe as e,yt as f,x as g,Q as h,ke as i,Qe as j,Je as k,et as l,tt as m,$e as n,ht as o,Be as p,ot as q,rt as r,st as s,at as t,Oe as u,dt as v,ut as w,Xe as x,xt as y,vt as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Ee}from"./H4S2ZCWK.js";import{a as xe}from"./L2MTPRU7.js";import{a as $e,b as me,c as Te}from"./SQ5BNSXR.js";import{c as Re,d as t,e as R,f as d,g as Ae,h as W,i as v,j as de,k as L,m as O,n as c,o as ue,p as ce,q as le,r as Ce,s as qe}from"./53N7PNJH.js";import{a as ke,o as re}from"./EAEQOS7Y.js";import{a as ve}from"./UWOFA6GV.js";import{c as be,e as Q,g as M}from"./73N3TOJL.js";import{a as l,i as we}from"./XPFVT2EA.js";import{a as h}from"./5YS5V2LK.js";import{decodeFunctionData as Fe,erc20Abi as Me}from"viem";var z="0x0000000000000000000000000000000000000000",N=we[l].relay.depository.address.toLowerCase(),Se=30,ze=w=>{let U=qe(w);async function pe(n){let e;try{e=await U(`/intents/status/v3?requestId=${encodeURIComponent(n)}`)}catch(C){if(w.plainError(C)!=="The request timed out. Please try again.")throw C;return{requestId:n,status:"unknown",timedOut:!0,fulfilled:!1,settled:!1,pollAgain:!0,needsAttention:!1,inTxHashes:[],txHashes:[],originChainId:void 0,destinationChainId:void 0,summary:"The status request timed out. Bridge settlement is unknown; poll again."}}if(typeof e.status!="string")throw new h("Relay returned an invalid bridge status.");let i=ue(e.inTxHashes),p=ue(e.txHashes),u=e.originChainId===void 0?void 0:W(e.originChainId),a=e.destinationChainId===void 0?void 0:W(e.destinationChainId),s=ce(e.failReason),m=ce(e.refundFailReason),r=e.status==="success"&&p.length>0&&a!==void 0,q=e.status==="refund"&&p.length>0&&u!==void 0,g=e.status==="failure"&&m!==void 0,A=["waiting","depositing","pending","submitted","failure","refund","success"].includes(e.status)?e.status==="failure"&&/TIMEOUT|EXPIRED/.test(typeof e.failReason=="string"?e.failReason:"")?"timeout":e.status:"unknown",k=r?"Relay reports destination fulfillment.":q?"Relay reports a refund on the origin chain; the destination was not fulfilled.":g?"The bridge failed and automatic refund is unavailable. Review the request with Relay.":"Bridge settlement is not confirmed. Poll Relay again; an origin receipt alone does not prove destination fulfillment.";return{requestId:n,status:A,relayStatus:e.status,fulfilled:r,settled:r||q,pollAgain:!r&&!q&&!g,needsAttention:g,timedOut:!1,inTxHashes:i,txHashes:p,originChainId:u,destinationChainId:a,failReason:s,refundFailReason:m,...e.updatedAt===void 0?{}:{updatedAt:v(String(e.updatedAt))},summary:k}}async function De(n,e){let i=s=>({destinationVerified:!1,destinationCheck:s}),p;try{if(p=w.clientFor(n),await p.getChainId()!==n)return i(`The configured RPC does not serve chain ${n}; destination receipts were not checked.`)}catch{return i(`No RPC is available for chain ${n}; destination receipts were not checked.`)}let u=[];for(let s of e)try{let m=await p.getTransactionReceipt({hash:s});u.push({hash:s,status:m.status,blockNumber:m.blockNumber.toString()})}catch{return{...i(`Receipt ${s} is not available on chain ${n} yet; poll again.`),destinationReceipts:u}}let a=u.length>0&&u.every(s=>s.status==="success");return{destinationVerified:a,destinationReceipts:u,destinationCheck:a?`Every Relay destination transaction has a successful receipt on chain ${n}. Amounts are not decoded here; compare the recipient balance for the exact delivered amount.`:`A Relay destination transaction did not succeed on chain ${n}; do not treat this bridge as delivered.`}}async function Pe(n){let e=await w.clientFor(l).readContract({address:n,abi:Me,functionName:"decimals"}),i=typeof e=="bigint"?Number(e):e;if(typeof i!="number"||!Number.isInteger(i)||i<0||i>255)throw new h("Could not read valid ERC-20 decimals() on-chain.");return i}async function _e(n,e){let i=d(e),p=d(n.recipient??i),u=W(n.destinationChainId);if(u===l)throw new h("Choose a destination chain other than 4663.");let a=Ae(n.originCurrency??z),s=a!==z,m=d(n.destinationCurrency??z),r=v(n.amount);if(r==="0")throw new h("Provide a positive bridge amount.");let q=n.minAmountOut===void 0?void 0:v(n.minAmountOut),g=n.slippageBps??me;if(typeof g!="number")throw new h("Slippage must be an integer from 0 to 9999 bps.");re("0",g);let I=R((await U("/chains")).chains).map(t),A=I.find(o=>o.id===l),k=I.find(o=>o.id===u);if(!A||!k||A.disabled!==!1||k.disabled!==!1||A.depositEnabled!==!0||A.vmType!=="evm"||k.vmType!=="evm")throw new h("Relay does not currently support this outbound chain route.");if(!xe(u))throw new h(`Relay has no supported Oak return path from chain ${u}. Choose a destination supported by relay_bridge_in before bridge-out.`);let C=await $e(w.clientFor,u,i,"server"),b=s?await Pe(a):18,P=Math.floor(Date.now()/1e3)+ke,$=await U("/quote/v2",{user:i,recipient:p,originChainId:l,destinationChainId:u,originCurrency:a,destinationCurrency:m,amount:r,tradeType:"EXACT_INPUT",...s?{explicitDeposit:!0}:{}}),E=L($.requestId),S=t($.details),B=O(S.currencyIn),f=O(S.currencyOut),T={token:f.token,amount:v(t(S.currencyOut).minimumAmount)};if(c(d(S.sender)===i&&d(S.recipient)===p&&B.token.chainId===l&&B.token.address===a&&B.token.decimals===b&&B.amount===r&&f.token.chainId===u&&f.token.address===m&&BigInt(T.amount)>0n&&BigInt(T.amount)<=BigInt(f.amount)),m===z&&c(f.token.decimals===t(k.currency).decimals),q!==void 0){if(T.amount!==q)throw new h("Relay order minimum must exactly match minAmountOut. Request a new quote.")}else if(BigInt(T.amount)<BigInt(re(f.amount,g)))throw Te(f.amount,T.amount);let J=t(t($.protocol).v2),j=L(J.orderId),Z=t(J.orderData),Y=t(Z.output),ee=de(Y.deadline),K=R(Z.inputs).map(t);c(K.length>0);let te=K.flatMap(o=>{let y=R(o.refunds).map(t);return c(y.length>0),y.map(Ie=>{if(d(Ie.recipient)!==i)throw new h("Relay refund recipient does not match the agent wallet. Request a new quote.");return de(Ie.deadline)})}),Oe=te.reduce((o,y)=>Math.min(o,y),ee),ne=Math.min(P,Oe-Se),he=()=>{if(Date.now()/1e3>=ne)throw new h("The Relay quote expired or its order/refund deadline leaves too little time to sign and send. Request a fresh bridge quote.")};he();let H=R(Y.payments).map(t),ie=t(t(A.protocol).v2),Ne=t(t(k.protocol).v2),V=t(J.paymentDetails);c(Y.chainId===Ne.chainId&&H.length===1&&R(Y.calls).length===0&&d(H[0].recipient)===p&&d(H[0].currency)===m&&v(H[0].minimumAmount)===T.amount&&v(H[0].expectedAmount)===f.amount&&V.chainId===ie.chainId&&d(V.currency)===a&&v(V.amount)===r),c(d(V.depository)===N&&d(ie.depository)===N);let oe=t(K[0].payment);c(K.length===1&&oe.chainId===ie.chainId&&d(oe.currency)===a&&v(oe.amount)===r);let F=R($.steps).map(t),_=s&&F.length===2?F[0]:void 0;c(F.length===(_?2:1));let G=F[F.length-1];c(G.kind==="transaction"&&G.id==="deposit"&&G.requestId===E);let X=R(G.items).map(t);c(X.length===1&&X[0].status==="incomplete");let x=t(X[0].data),fe=t(X[0].check);if(c(fe.method==="GET"&&fe.endpoint===`/intents/status/v3?requestId=${E}`&&x.chainId===l&&d(x.from)===i&&d(x.to)===N&&v(x.value)===(s?"0":r)),typeof x.data!="string"||!(s?/^0x[0-9a-fA-F]{264}$/:/^0x[0-9a-fA-F]{136}$/).test(x.data))throw new h(`Relay returned unexpected ${s?"ERC-20":"native"} deposit calldata.`);let D=Fe({abi:Re,data:x.data});D.functionName==="depositErc20"?c(s&&d(D.args[0])===i&&d(D.args[1])===a&&D.args[2]===BigInt(r)&&M(D.args[3],j)):c(!s&&d(D.args[0])===i&&M(D.args[1],j));let Be=I.filter(o=>o.vmType==="evm"&&Q(o.protocol)&&Q(o.protocol.v2)).map(o=>t(t(o.protocol).v2).chainId).filter(o=>typeof o=="string");if(!M(Ee(Z,Be),j))throw new h("Relay order ID does not match the checked quote terms. Request a new quote.");let ae=s?w.approval(a,N,r,l):void 0;if(_&&ae){c(_.kind==="transaction"&&_.id==="approve"&&_.requestId===E);let o=R(_.items).map(t);c(o.length===1&&o[0].status==="incomplete");let y=t(o[0].data);c(y.chainId===l&&d(y.from)===i&&d(y.to)===a&&v(y.value)==="0"&&typeof y.data=="string"&&M(y.data,ae.data))}let ye=[...ae?await Ce(w,a,N,r,l,i):[],w.unsignedTx({to:N,data:x.data,value:s?"0":r,chainId:l,description:s?`Deposit ${r} base units of ${a} for Relay request ${E}.`:`Deposit native ETH for Relay request ${E}.`})],ge=t($.fees);for(let o of Object.values(ge))O(o);let se=await w.preview(ye,i);he();let He=se.changes.map(o=>{let y=o.amount.startsWith("-");return`${y?"-":""}${w.formatAmount(y?o.amount.slice(1):o.amount,o.token.decimals)} ${o.token.symbol}`}).join(", ");return{txs:ye,requestId:E,orderId:j,recipient:p,originChainId:l,destinationChainId:u,expiresAt:String(ne),orderDeadline:String(ee),refundDeadlines:te.map(String),returnPath:C,amountIn:B,amountOut:f,minAmountOut:T,fees:ge,expandedPriceImpact:S.expandedPriceImpact,timeEstimate:S.timeEstimate,preview:se,summary:`${C} Bridge to ${p} on chain ${u}; asset ${f.token.address} on chain ${f.token.chainId} (${le(f.token.symbol)}); expected ${f.amount}, minimum ${T.amount} base units (${f.token.decimals} decimals). Order deadline ${ee} Unix seconds; refund deadlines ${te.join(", ")} Unix seconds; accept before ${ne} Unix seconds to reserve ${Se}s to sign and send. Origin preview: ${He||se.summary}. Relay route fees are included in the quote; origin gas is separate. Poll relay_status with requestId ${E} after local submission; destination fulfillment is not yet confirmed.`}}return{tools:[{name:"relay_bridge_out",inputSchema:{type:"object",required:["destinationChainId","amount"],additionalProperties:!1,properties:{destinationChainId:{type:"integer",minimum:1},amount:{type:"string",pattern:"^[1-9][0-9]*$"},recipient:{type:"string"},originCurrency:be,slippageBps:{type:"integer",minimum:0,maximum:9999,default:me},destinationCurrency:{type:"string"},minAmountOut:ve()}},execute:async(n,e)=>{try{return await _e(n,e)}catch(i){throw new h(w.plainError(i))}}},{name:"relay_status",inputSchema:{type:"object",required:["requestId"],additionalProperties:!1,properties:{requestId:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},verifyDestination:{type:"boolean"}}},execute:async n=>{let e=await pe(L(n.requestId));return n.verifyDestination!==!0||!e.fulfilled||e.destinationChainId===void 0?e:{...e,...await De(e.destinationChainId,e.txHashes)}}}],positions:async n=>{let e=d(n);if(!process.env.OAK_RELAY_API_KEY?.trim())return[{module:"relay",id:"relay-discovery-unavailable",chainId:l,assets:[],incomplete:!0,description:'Relay pending bridge discovery requires OAK_RELAY_API_KEY on the server. The request-history API requires this key; no pending bridges were checked. Ask the operator to configure it, or check a known request with relay_status {"requestId":"<id>"}. Legacy vault shares on other chains can be checked with relay_vault_status {"chainId":1} or {"chainId":42161}.'}];let i=new Map;for(let p of["outbound","inbound"]){let u=new Set,a;do{let s=new URLSearchParams({user:e,[p==="outbound"?"originChainId":"destinationChainId"]:String(l),limit:"100",includePendingRequests:"true"});a&&s.set("continuation",a);let m=await U(`/requests/v3?${s}`);for(let r of R(m.requests).map(t)){let q=Q(r.depositAddress)?r.depositAddress.depositor:void 0;if(![r.user,r.sender,q].some($=>typeof $=="string"&&$.toLowerCase()===e))throw new h("Relay returned a request for another wallet.");let g=L(r.id);if(i.has(g))continue;let I=await pe(g);if(I.settled)continue;let A=t(r.data),k=t(t(A.route).quoted),C=O(t(k.origin).inputCurrency),b={...C,token:{...C.token,symbol:le(C.token.symbol)??"unknown"}},P=O(t(k.destination).outputCurrency);c(p==="outbound"?b.token.chainId===l&&P.token.chainId!==l:b.token.chainId!==l&&P.token.chainId===l),I.originChainId!==void 0&&c(I.originChainId===b.token.chainId),I.destinationChainId!==void 0&&c(I.destinationChainId===P.token.chainId),i.set(g,{module:"relay",id:g,chainId:b.token.chainId,assets:[b],description:`Relay ${p} ${I.status}: ${b.amount} ${b.token.symbol} base units (${b.token.decimals} decimals) from chain ${b.token.chainId} toward ${d(r.recipient)} on chain ${P.token.chainId}. ${I.summary} Track with relay_status requestId ${g}.`})}if(m.continuation!==void 0&&m.continuation!==null&&typeof m.continuation!="string")throw new h("Relay returned invalid pagination.");if(a=typeof m.continuation=="string"&&m.continuation?m.continuation:void 0,a){if(u.has(a))throw new h("Relay repeated its pagination cursor. Pending positions are incomplete.");u.add(a)}}while(a)}return[...i.values()]}}};export{ze as a};
|
|
1
|
+
import{a as Ee}from"./H4S2ZCWK.js";import{a as xe}from"./T3NPRRTY.js";import{a as $e,b as me,c as Te}from"./SQ5BNSXR.js";import{c as Re,d as t,e as R,f as d,g as Ae,h as W,i as v,j as de,k as L,m as O,n as c,o as ue,p as ce,q as le,r as Ce,s as qe}from"./53N7PNJH.js";import{a as ke,o as re}from"./CAU44UWP.js";import{a as ve}from"./UWOFA6GV.js";import{c as be,e as Q,g as M}from"./73N3TOJL.js";import{a as l,i as we}from"./XPFVT2EA.js";import{a as h}from"./5YS5V2LK.js";import{decodeFunctionData as Fe,erc20Abi as Me}from"viem";var z="0x0000000000000000000000000000000000000000",N=we[l].relay.depository.address.toLowerCase(),Se=30,ze=w=>{let U=qe(w);async function pe(n){let e;try{e=await U(`/intents/status/v3?requestId=${encodeURIComponent(n)}`)}catch(C){if(w.plainError(C)!=="The request timed out. Please try again.")throw C;return{requestId:n,status:"unknown",timedOut:!0,fulfilled:!1,settled:!1,pollAgain:!0,needsAttention:!1,inTxHashes:[],txHashes:[],originChainId:void 0,destinationChainId:void 0,summary:"The status request timed out. Bridge settlement is unknown; poll again."}}if(typeof e.status!="string")throw new h("Relay returned an invalid bridge status.");let i=ue(e.inTxHashes),p=ue(e.txHashes),u=e.originChainId===void 0?void 0:W(e.originChainId),a=e.destinationChainId===void 0?void 0:W(e.destinationChainId),s=ce(e.failReason),m=ce(e.refundFailReason),r=e.status==="success"&&p.length>0&&a!==void 0,q=e.status==="refund"&&p.length>0&&u!==void 0,g=e.status==="failure"&&m!==void 0,A=["waiting","depositing","pending","submitted","failure","refund","success"].includes(e.status)?e.status==="failure"&&/TIMEOUT|EXPIRED/.test(typeof e.failReason=="string"?e.failReason:"")?"timeout":e.status:"unknown",k=r?"Relay reports destination fulfillment.":q?"Relay reports a refund on the origin chain; the destination was not fulfilled.":g?"The bridge failed and automatic refund is unavailable. Review the request with Relay.":"Bridge settlement is not confirmed. Poll Relay again; an origin receipt alone does not prove destination fulfillment.";return{requestId:n,status:A,relayStatus:e.status,fulfilled:r,settled:r||q,pollAgain:!r&&!q&&!g,needsAttention:g,timedOut:!1,inTxHashes:i,txHashes:p,originChainId:u,destinationChainId:a,failReason:s,refundFailReason:m,...e.updatedAt===void 0?{}:{updatedAt:v(String(e.updatedAt))},summary:k}}async function De(n,e){let i=s=>({destinationVerified:!1,destinationCheck:s}),p;try{if(p=w.clientFor(n),await p.getChainId()!==n)return i(`The configured RPC does not serve chain ${n}; destination receipts were not checked.`)}catch{return i(`No RPC is available for chain ${n}; destination receipts were not checked.`)}let u=[];for(let s of e)try{let m=await p.getTransactionReceipt({hash:s});u.push({hash:s,status:m.status,blockNumber:m.blockNumber.toString()})}catch{return{...i(`Receipt ${s} is not available on chain ${n} yet; poll again.`),destinationReceipts:u}}let a=u.length>0&&u.every(s=>s.status==="success");return{destinationVerified:a,destinationReceipts:u,destinationCheck:a?`Every Relay destination transaction has a successful receipt on chain ${n}. Amounts are not decoded here; compare the recipient balance for the exact delivered amount.`:`A Relay destination transaction did not succeed on chain ${n}; do not treat this bridge as delivered.`}}async function Pe(n){let e=await w.clientFor(l).readContract({address:n,abi:Me,functionName:"decimals"}),i=typeof e=="bigint"?Number(e):e;if(typeof i!="number"||!Number.isInteger(i)||i<0||i>255)throw new h("Could not read valid ERC-20 decimals() on-chain.");return i}async function _e(n,e){let i=d(e),p=d(n.recipient??i),u=W(n.destinationChainId);if(u===l)throw new h("Choose a destination chain other than 4663.");let a=Ae(n.originCurrency??z),s=a!==z,m=d(n.destinationCurrency??z),r=v(n.amount);if(r==="0")throw new h("Provide a positive bridge amount.");let q=n.minAmountOut===void 0?void 0:v(n.minAmountOut),g=n.slippageBps??me;if(typeof g!="number")throw new h("Slippage must be an integer from 0 to 9999 bps.");re("0",g);let I=R((await U("/chains")).chains).map(t),A=I.find(o=>o.id===l),k=I.find(o=>o.id===u);if(!A||!k||A.disabled!==!1||k.disabled!==!1||A.depositEnabled!==!0||A.vmType!=="evm"||k.vmType!=="evm")throw new h("Relay does not currently support this outbound chain route.");if(!xe(u))throw new h(`Relay has no supported Oak return path from chain ${u}. Choose a destination supported by relay_bridge_in before bridge-out.`);let C=await $e(w.clientFor,u,i,"server"),b=s?await Pe(a):18,P=Math.floor(Date.now()/1e3)+ke,$=await U("/quote/v2",{user:i,recipient:p,originChainId:l,destinationChainId:u,originCurrency:a,destinationCurrency:m,amount:r,tradeType:"EXACT_INPUT",...s?{explicitDeposit:!0}:{}}),E=L($.requestId),S=t($.details),B=O(S.currencyIn),f=O(S.currencyOut),T={token:f.token,amount:v(t(S.currencyOut).minimumAmount)};if(c(d(S.sender)===i&&d(S.recipient)===p&&B.token.chainId===l&&B.token.address===a&&B.token.decimals===b&&B.amount===r&&f.token.chainId===u&&f.token.address===m&&BigInt(T.amount)>0n&&BigInt(T.amount)<=BigInt(f.amount)),m===z&&c(f.token.decimals===t(k.currency).decimals),q!==void 0){if(T.amount!==q)throw new h("Relay order minimum must exactly match minAmountOut. Request a new quote.")}else if(BigInt(T.amount)<BigInt(re(f.amount,g)))throw Te(f.amount,T.amount);let J=t(t($.protocol).v2),j=L(J.orderId),Z=t(J.orderData),Y=t(Z.output),ee=de(Y.deadline),K=R(Z.inputs).map(t);c(K.length>0);let te=K.flatMap(o=>{let y=R(o.refunds).map(t);return c(y.length>0),y.map(Ie=>{if(d(Ie.recipient)!==i)throw new h("Relay refund recipient does not match the agent wallet. Request a new quote.");return de(Ie.deadline)})}),Oe=te.reduce((o,y)=>Math.min(o,y),ee),ne=Math.min(P,Oe-Se),he=()=>{if(Date.now()/1e3>=ne)throw new h("The Relay quote expired or its order/refund deadline leaves too little time to sign and send. Request a fresh bridge quote.")};he();let H=R(Y.payments).map(t),ie=t(t(A.protocol).v2),Ne=t(t(k.protocol).v2),V=t(J.paymentDetails);c(Y.chainId===Ne.chainId&&H.length===1&&R(Y.calls).length===0&&d(H[0].recipient)===p&&d(H[0].currency)===m&&v(H[0].minimumAmount)===T.amount&&v(H[0].expectedAmount)===f.amount&&V.chainId===ie.chainId&&d(V.currency)===a&&v(V.amount)===r),c(d(V.depository)===N&&d(ie.depository)===N);let oe=t(K[0].payment);c(K.length===1&&oe.chainId===ie.chainId&&d(oe.currency)===a&&v(oe.amount)===r);let F=R($.steps).map(t),_=s&&F.length===2?F[0]:void 0;c(F.length===(_?2:1));let G=F[F.length-1];c(G.kind==="transaction"&&G.id==="deposit"&&G.requestId===E);let X=R(G.items).map(t);c(X.length===1&&X[0].status==="incomplete");let x=t(X[0].data),fe=t(X[0].check);if(c(fe.method==="GET"&&fe.endpoint===`/intents/status/v3?requestId=${E}`&&x.chainId===l&&d(x.from)===i&&d(x.to)===N&&v(x.value)===(s?"0":r)),typeof x.data!="string"||!(s?/^0x[0-9a-fA-F]{264}$/:/^0x[0-9a-fA-F]{136}$/).test(x.data))throw new h(`Relay returned unexpected ${s?"ERC-20":"native"} deposit calldata.`);let D=Fe({abi:Re,data:x.data});D.functionName==="depositErc20"?c(s&&d(D.args[0])===i&&d(D.args[1])===a&&D.args[2]===BigInt(r)&&M(D.args[3],j)):c(!s&&d(D.args[0])===i&&M(D.args[1],j));let Be=I.filter(o=>o.vmType==="evm"&&Q(o.protocol)&&Q(o.protocol.v2)).map(o=>t(t(o.protocol).v2).chainId).filter(o=>typeof o=="string");if(!M(Ee(Z,Be),j))throw new h("Relay order ID does not match the checked quote terms. Request a new quote.");let ae=s?w.approval(a,N,r,l):void 0;if(_&&ae){c(_.kind==="transaction"&&_.id==="approve"&&_.requestId===E);let o=R(_.items).map(t);c(o.length===1&&o[0].status==="incomplete");let y=t(o[0].data);c(y.chainId===l&&d(y.from)===i&&d(y.to)===a&&v(y.value)==="0"&&typeof y.data=="string"&&M(y.data,ae.data))}let ye=[...ae?await Ce(w,a,N,r,l,i):[],w.unsignedTx({to:N,data:x.data,value:s?"0":r,chainId:l,description:s?`Deposit ${r} base units of ${a} for Relay request ${E}.`:`Deposit native ETH for Relay request ${E}.`})],ge=t($.fees);for(let o of Object.values(ge))O(o);let se=await w.preview(ye,i);he();let He=se.changes.map(o=>{let y=o.amount.startsWith("-");return`${y?"-":""}${w.formatAmount(y?o.amount.slice(1):o.amount,o.token.decimals)} ${o.token.symbol}`}).join(", ");return{txs:ye,requestId:E,orderId:j,recipient:p,originChainId:l,destinationChainId:u,expiresAt:String(ne),orderDeadline:String(ee),refundDeadlines:te.map(String),returnPath:C,amountIn:B,amountOut:f,minAmountOut:T,fees:ge,expandedPriceImpact:S.expandedPriceImpact,timeEstimate:S.timeEstimate,preview:se,summary:`${C} Bridge to ${p} on chain ${u}; asset ${f.token.address} on chain ${f.token.chainId} (${le(f.token.symbol)}); expected ${f.amount}, minimum ${T.amount} base units (${f.token.decimals} decimals). Order deadline ${ee} Unix seconds; refund deadlines ${te.join(", ")} Unix seconds; accept before ${ne} Unix seconds to reserve ${Se}s to sign and send. Origin preview: ${He||se.summary}. Relay route fees are included in the quote; origin gas is separate. Poll relay_status with requestId ${E} after local submission; destination fulfillment is not yet confirmed.`}}return{tools:[{name:"relay_bridge_out",inputSchema:{type:"object",required:["destinationChainId","amount"],additionalProperties:!1,properties:{destinationChainId:{type:"integer",minimum:1},amount:{type:"string",pattern:"^[1-9][0-9]*$"},recipient:{type:"string"},originCurrency:be,slippageBps:{type:"integer",minimum:0,maximum:9999,default:me},destinationCurrency:{type:"string"},minAmountOut:ve()}},execute:async(n,e)=>{try{return await _e(n,e)}catch(i){throw new h(w.plainError(i))}}},{name:"relay_status",inputSchema:{type:"object",required:["requestId"],additionalProperties:!1,properties:{requestId:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},verifyDestination:{type:"boolean"}}},execute:async n=>{let e=await pe(L(n.requestId));return n.verifyDestination!==!0||!e.fulfilled||e.destinationChainId===void 0?e:{...e,...await De(e.destinationChainId,e.txHashes)}}}],positions:async n=>{let e=d(n);if(!process.env.OAK_RELAY_API_KEY?.trim())return[{module:"relay",id:"relay-discovery-unavailable",chainId:l,assets:[],incomplete:!0,description:'Relay pending bridge discovery requires OAK_RELAY_API_KEY on the server. The request-history API requires this key; no pending bridges were checked. Ask the operator to configure it, or check a known request with relay_status {"requestId":"<id>"}. Legacy vault shares on other chains can be checked with relay_vault_status {"chainId":1} or {"chainId":42161}.'}];let i=new Map;for(let p of["outbound","inbound"]){let u=new Set,a;do{let s=new URLSearchParams({user:e,[p==="outbound"?"originChainId":"destinationChainId"]:String(l),limit:"100",includePendingRequests:"true"});a&&s.set("continuation",a);let m=await U(`/requests/v3?${s}`);for(let r of R(m.requests).map(t)){let q=Q(r.depositAddress)?r.depositAddress.depositor:void 0;if(![r.user,r.sender,q].some($=>typeof $=="string"&&$.toLowerCase()===e))throw new h("Relay returned a request for another wallet.");let g=L(r.id);if(i.has(g))continue;let I=await pe(g);if(I.settled)continue;let A=t(r.data),k=t(t(A.route).quoted),C=O(t(k.origin).inputCurrency),b={...C,token:{...C.token,symbol:le(C.token.symbol)??"unknown"}},P=O(t(k.destination).outputCurrency);c(p==="outbound"?b.token.chainId===l&&P.token.chainId!==l:b.token.chainId!==l&&P.token.chainId===l),I.originChainId!==void 0&&c(I.originChainId===b.token.chainId),I.destinationChainId!==void 0&&c(I.destinationChainId===P.token.chainId),i.set(g,{module:"relay",id:g,chainId:b.token.chainId,assets:[b],description:`Relay ${p} ${I.status}: ${b.amount} ${b.token.symbol} base units (${b.token.decimals} decimals) from chain ${b.token.chainId} toward ${d(r.recipient)} on chain ${P.token.chainId}. ${I.summary} Track with relay_status requestId ${g}.`})}if(m.continuation!==void 0&&m.continuation!==null&&typeof m.continuation!="string")throw new h("Relay returned invalid pagination.");if(a=typeof m.continuation=="string"&&m.continuation?m.continuation:void 0,a){if(u.has(a))throw new h("Relay repeated its pagination cursor. Pending positions are incomplete.");u.add(a)}}while(a)}return[...i.values()]}}};export{ze as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as s}from"./
|
|
1
|
+
import{j as s}from"./NBRMUFJP.js";import{formatUnits as c}from"viem";function l(e){return`HoodLock creation fee: ${e.eth} ETH (${e.amount} wei; ${e.usd===null?"USD unavailable: no fresh ETH/USD reference":`approximately $${e.usd} USD`}), not refundable after creation. Paid to ${e.contract}; separate from network gas.`}async function p(e,t,d,r){let o=r===0n?"0":null;if(r>0n)try{let a=await s("ETH",{client:e.clientFor(4663),chainId:4663});BigInt(a.usdE18)>0n&&(o=c(r*BigInt(a.usdE18)/10n**18n,18))}catch{}let n={contract:d,amount:r.toString(),eth:c(r,18),usd:o,refundable:!1},i=l(n);return{...t,summary:`${t.summary} ${i}`,preview:{...t.preview,summary:`${t.preview.summary} ${i}`},protocolFee:n}}export{l as a,p as b};
|