@oakagentkit/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/build/dist/api/addresses.d.ts +1 -1
  2. package/build/dist/api/addresses.js +1 -1
  3. package/build/dist/api/amounts.js +1 -1
  4. package/build/dist/api/args.d.ts +19 -0
  5. package/build/dist/api/args.js +1 -0
  6. package/build/dist/api/canonical.js +1 -1
  7. package/build/dist/api/chain.js +1 -1
  8. package/build/dist/api/errors.d.ts +1 -0
  9. package/build/dist/api/errors.js +1 -1
  10. package/build/dist/api/gas.d.ts +5 -0
  11. package/build/dist/api/gas.js +1 -0
  12. package/build/dist/api/grandfather.js +1 -1
  13. package/build/dist/api/history.js +1 -1
  14. package/build/dist/api/http.js +1 -1
  15. package/build/dist/api/identity-link.js +1 -1
  16. package/build/dist/api/merkle.js +1 -1
  17. package/build/dist/api/metadata.js +1 -1
  18. package/build/dist/api/module.js +1 -1
  19. package/build/dist/api/modules/beefy/index.js +1 -1
  20. package/build/dist/api/modules/clanker/index.js +1 -1
  21. package/build/dist/api/modules/erc8004/index.d.ts +11 -0
  22. package/build/dist/api/modules/erc8004/index.js +1 -1
  23. package/build/dist/api/modules/grove/index.js +1 -1
  24. package/build/dist/api/modules/heyresearch/index.js +1 -1
  25. package/build/dist/api/modules/hoodag/index.js +1 -1
  26. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  27. package/build/dist/api/modules/hoodlock/index.js +1 -1
  28. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  29. package/build/dist/api/modules/hookr/create-cancel.d.ts +2 -2
  30. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  31. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  32. package/build/dist/api/modules/hookr/index.js +1 -1
  33. package/build/dist/api/modules/kyberswap/index.js +1 -1
  34. package/build/dist/api/modules/lighter/index.js +1 -1
  35. package/build/dist/api/modules/longbow/index.d.ts +4 -2
  36. package/build/dist/api/modules/longbow/index.js +1 -1
  37. package/build/dist/api/modules/meridian/index.js +1 -1
  38. package/build/dist/api/modules/meridian/markets.js +1 -1
  39. package/build/dist/api/modules/meridian/rfq.js +1 -1
  40. package/build/dist/api/modules/merkl/index.js +1 -1
  41. package/build/dist/api/modules/morpho/index.d.ts +1 -1
  42. package/build/dist/api/modules/morpho/index.js +2 -2
  43. package/build/dist/api/modules/netnet/index.js +1 -1
  44. package/build/dist/api/modules/orbio/index.js +1 -1
  45. package/build/dist/api/modules/pons/claim.js +1 -1
  46. package/build/dist/api/modules/pons/index.js +1 -1
  47. package/build/dist/api/modules/pons/launch-status.js +1 -1
  48. package/build/dist/api/modules/pons/prices.js +1 -1
  49. package/build/dist/api/modules/pons/trade.d.ts +3 -1
  50. package/build/dist/api/modules/pons/trade.js +1 -1
  51. package/build/dist/api/modules/poolstrade/index.js +1 -1
  52. package/build/dist/api/modules/priors/index.js +1 -1
  53. package/build/dist/api/modules/relay/inbound.d.ts +2 -0
  54. package/build/dist/api/modules/relay/inbound.js +1 -1
  55. package/build/dist/api/modules/relay/index.js +1 -1
  56. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  57. package/build/dist/api/modules/spark/index.js +1 -1
  58. package/build/dist/api/modules/steakhouse/index.js +1 -1
  59. package/build/dist/api/modules/tickerspring/index.js +1 -1
  60. package/build/dist/api/modules/uniswap/index.js +1 -1
  61. package/build/dist/api/modules/uniswap/v3.js +1 -1
  62. package/build/dist/api/modules/uniswap/v4.js +1 -1
  63. package/build/dist/api/modules/velora/index.js +1 -1
  64. package/build/dist/api/positions.js +1 -1
  65. package/build/dist/api/pricenote.js +1 -1
  66. package/build/dist/api/prices.js +1 -1
  67. package/build/dist/api/pricing.d.ts +5 -1
  68. package/build/dist/api/pricing.js +1 -1
  69. package/build/dist/api/routes.js +1 -1
  70. package/build/dist/api/secret-fields.js +1 -1
  71. package/build/dist/api/send.d.ts +45 -0
  72. package/build/dist/api/send.js +1 -0
  73. package/build/dist/api/simulate.js +1 -1
  74. package/build/dist/api/swap.d.ts +6 -1
  75. package/build/dist/api/swap.js +1 -1
  76. package/build/dist/api/tokens.js +1 -1
  77. package/build/dist/api/tool-policy.d.ts +1 -0
  78. package/build/dist/api/tool-policy.js +1 -1
  79. package/build/dist/api/tx.js +1 -1
  80. package/build/dist/api/types.d.ts +13 -0
  81. package/build/dist/api/untrusted.js +1 -1
  82. package/build/dist/api/vendor-limits.js +1 -1
  83. package/build/dist/chunks/2IRORNOH.js +1 -0
  84. package/build/dist/chunks/{YTHDLCHL.js → 3PA2XT75.js} +1 -1
  85. package/build/dist/chunks/52TGAWSI.js +1 -0
  86. package/build/dist/chunks/{OOSNTGDJ.js → 66DWJWDA.js} +1 -1
  87. package/build/dist/chunks/{ZKOMJGNH.js → 6SYTB6FB.js} +1 -1
  88. package/build/dist/chunks/73EABRFC.js +1 -0
  89. package/build/dist/chunks/{VZWOWR6G.js → A5ITAEUQ.js} +1 -1
  90. package/build/dist/chunks/A5KSG6LW.js +1 -0
  91. package/build/dist/chunks/{JMPOXXNJ.js → B4FOHEBE.js} +1 -1
  92. package/build/dist/chunks/B4MLWDPM.js +1 -0
  93. package/build/dist/chunks/{D45AODDL.js → BHR46XNW.js} +1 -1
  94. package/build/dist/chunks/{YEE3KKTA.js → BOFA26WU.js} +1 -1
  95. package/build/dist/chunks/CQNZWL7F.js +1 -0
  96. package/build/dist/chunks/GDP4JSAX.js +1 -0
  97. package/build/dist/chunks/{P7Q6MJZH.js → GIBF3YJO.js} +1 -1
  98. package/build/dist/chunks/GN4QZ4JA.js +1 -0
  99. package/build/dist/chunks/{B5RZYFQC.js → I5CQ64EU.js} +1 -1
  100. package/build/dist/chunks/ICCJ3TOO.js +1 -0
  101. package/build/dist/chunks/{XN4WDN3O.js → JXOEJPJ4.js} +1 -1
  102. package/build/dist/chunks/{47PKSOXA.js → KL5YE7JA.js} +1 -1
  103. package/build/dist/chunks/KVVTKM6E.js +1 -0
  104. package/build/dist/chunks/{UL2L7NHO.js → M6JGTQRY.js} +1 -1
  105. package/build/dist/chunks/{ZUAXW2ZD.js → MK6L6TGI.js} +1 -1
  106. package/build/dist/chunks/{KFMNCJXJ.js → MOVRI5IV.js} +1 -1
  107. package/build/dist/chunks/NA7HV7BR.js +1 -0
  108. package/build/dist/chunks/NGAI6GTU.js +1 -0
  109. package/build/dist/chunks/{UZH4FQEL.js → OBX7IZG5.js} +1 -1
  110. package/build/dist/chunks/{KP7VSXIQ.js → OSQ4AAM2.js} +1 -1
  111. package/build/dist/chunks/{75D6Q7L3.js → OWEUVFB6.js} +1 -1
  112. package/build/dist/chunks/{LZK6C5LT.js → P4G3EKF7.js} +1 -1
  113. package/build/dist/chunks/{IABIXUNX.js → QGDHMVPE.js} +1 -1
  114. package/build/dist/chunks/{VZPFBWVH.js → SJ7HDRI4.js} +1 -1
  115. package/build/dist/chunks/SPAKOCR7.js +1 -0
  116. package/build/dist/chunks/T6O2L6HF.js +1 -0
  117. package/build/dist/chunks/TEVKPJV5.js +1 -0
  118. package/build/dist/chunks/UCMNB2UP.js +1 -0
  119. package/build/dist/chunks/{64EN6Y7E.js → Y3P6SUNL.js} +1 -1
  120. package/build/dist/chunks/YX4NVVSX.js +1 -0
  121. package/build/dist/chunks/ZUC6ILK2.js +1 -0
  122. package/package.json +9 -13
  123. package/build/dist/chunks/24JYIH53.js +0 -1
  124. package/build/dist/chunks/25EOXUBI.js +0 -1
  125. package/build/dist/chunks/4P6XI564.js +0 -1
  126. package/build/dist/chunks/6YU3JLQQ.js +0 -1
  127. package/build/dist/chunks/AE6YEEZP.js +0 -1
  128. package/build/dist/chunks/BH3CI6WO.js +0 -1
  129. package/build/dist/chunks/CUBRTOMA.js +0 -1
  130. package/build/dist/chunks/FSSCJNAQ.js +0 -1
  131. package/build/dist/chunks/MGEJPRXP.js +0 -1
  132. package/build/dist/chunks/S3YSJ7XH.js +0 -1
  133. package/build/dist/chunks/SGDWO7XI.js +0 -1
  134. package/build/dist/chunks/T5E4OJEU.js +0 -1
  135. package/build/dist/chunks/VBV366XQ.js +0 -1
  136. package/build/dist/chunks/XUL6NKAK.js +0 -1
  137. package/build/dist/chunks/ZERWRK6X.js +0 -1
@@ -1 +0,0 @@
1
- import{b as re,o as z}from"./VBV366XQ.js";import{a as K}from"./S3YSJ7XH.js";import{b as oe}from"./SGDWO7XI.js";import{a as T,i as se}from"./25EOXUBI.js";import{a as ie}from"./B5RZYFQC.js";import{a}from"./T5E4OJEU.js";import{decodeErrorResult as me,decodeEventLog as X,encodeAbiParameters as $,encodeFunctionData as S,erc20Abi as he,getAddress as ye,isAddress as ge,parseAbi as de,parseAbiParameters as C,toHex as we,zeroAddress as k}from"viem";var m=se[T].poolsTrade,E=m.liquidityLauncher.address,H=m.uerc20BeneficiaryVault.address,G=m.universalRouter.address,W=10n**27n,L=(1n<<128n)-1n,ae=`0x${"00".repeat(32)}`,be=63127652n,J=10000000n,Te={address:K,symbol:"ETH",decimals:18,chainId:T},h=de(["function multicall(bytes[] data) payable returns (bytes[])","function createToken(address factory,string name,string symbol,uint8 decimals,uint128 initialSupply,address recipient,bytes tokenData) payable returns (address)","function distributeToken(address token,(address strategy,uint128 amount,bytes configData) distribution,bytes32 salt) payable","function distributeWithNative(address strategy,bytes configData,bytes32 salt,uint256 nativeAmount) payable","function getGraffiti(address sender) view returns (bytes32)","function getUERC20Address(string name,string symbol,uint8 decimals,address recipient,bytes32 graffiti) view returns (address)","function execute(bytes commands,bytes[] inputs,uint256 deadline) payable","function collectFees(uint256[] ids)","function claim(uint256 id,uint256 minCurrency0Amount,uint256 minCurrency1Amount)","function amounts(uint256 id) view returns (uint128 eth,uint128 token)","function ownerOf(uint256 id) view returns (address)","function approve(address token,address spender,uint160 amount,uint48 expiration)","error V4TooLittleReceived(uint256 minAmountOut,uint256 amountOut)"]),D=de(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)","event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"]),M=[m.instantLaunchStrategyFeesOn.address,m.instantLaunchStrategyFeesOff.address],p=(o,c)=>o.toLowerCase()===c.toLowerCase();function ce(o){if(o.status!=="success")throw new a("The launch receipt did not succeed.");let c=[];for(let f of o.logs){let y=M.findIndex(x=>p(x,f.address));if(y===-1||f.topics[0]!=="0x3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4")continue;let F=X({abi:D,eventName:"TokenLaunched",data:f.data,topics:[...f.topics]}),{token:g,poolId:q,poolKey:I,feeSplitter:U}=F.args,j=y===0?m.feeSplitterFeesOn.address:m.feeSplitterFeesOff.address;if(!p(U,j)||!p(I.currency0,k)||!p(I.currency1,g)||I.fee!==2500||I.tickSpacing!==25||!p(I.hooks,k))throw new a("The launch does not match the current native ETH strategy.");let B=o.logs.filter(x=>p(x.address,m.v4PositionManager.address)).flatMap(x=>{if(x.topics[0]!=="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")return[];let O=X({abi:D,eventName:"Transfer",data:x.data,topics:[...x.topics]}).args;return p(O.from,k)&&p(O.to,M[y])?[O.tokenId]:[]});if(B.length!==1)throw new a("The launch receipt must identify one matching position mint.");c.push({token:g,poolId:q,positionId:B[0].toString(),creatorFees:y===0})}return c}function A(o){if(typeof o!="string"||!ge(o,{strict:!1}))throw new a("Provide a valid wallet or token address.");return ye(o)}function R(o,c,f=!1){if(typeof o!="string")throw new a(`${c} must be an integer string in base units.`);let y=ie(o);if(!f&&y===0n||y>=1n<<256n)throw new a(`${c} is outside its supported range.`);return y}function P(o,c,f=!1){if(f&&o===void 0)return"";if(typeof o!="string"||!f&&!o.trim()||o.length>4096)throw new a(`Provide a valid ${c}.`);return o}function xe(o){if(typeof o!="string"||!/^0x[0-9a-fA-F]{64}$/.test(o))throw new a("Provide a valid launch transaction hash.");return o}function Q(o,c,f="minAmountOut"){let y=c.slippageBps??re;if(typeof y!="number")throw new a("Slippage must be an integer in basis points.");let F=z(o.toString(),y),g=c[f]===void 0?BigInt(F):R(c[f],f,o===0n);if(g>o||o>0n&&g===0n||g>L)throw new a("The minimum output must be positive and no larger than the simulated output.");return g}function V(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}var Ae=o=>{let c=o.clientFor(T),f=(e,s,i,r)=>o.unsignedTx({to:e,data:s,value:i.toString(),chainId:T,description:r}),y=e=>{throw new a(o.plainError(e))};async function F(){if(await c.getChainId()!==T)throw new a("pools.trade requires Robinhood Chain 4663.")}async function g(e,s,i){let r=await o.preview(e,s),n=r.changes.map(({token:t,amount:d})=>{let u=d.startsWith("-");return`${u?"-":""}${o.formatAmount(u?d.slice(1):d,t.decimals)} ${t.symbol} (${t.address}, chain ${t.chainId})`});return{txs:e,summary:[i,r.summary,...n].join(" ")}}async function q(){return(await c.getBlock()).timestamp+600n}function I(e,s,i,r,n,t){let d=[k,e,2500,25,k],u=[$(C("((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"),[[d,s,i,r,0n,"0x"]]),$(C("address,uint256"),[s?k:e,i]),$(C("address,address,uint256"),[s?e:k,n,0n])],l=[$(C("bytes,bytes[]"),["0x060c0e",u])];return{inputs:l,encoded:$(C("bytes,bytes[],uint256"),["0x10",l,t])}}async function U(e,s){let i=await c.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(u=>({from:s,to:u.to,data:u.data,value:we(BigInt(u.value))}))}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(i)||i.length!==1||!V(i[0])||!Array.isArray(i[0].calls)||i[0].calls.length!==e.length)throw new a("The output simulation returned a malformed response.");let r=i[0].calls;if(!r.slice(0,-1).every(u=>V(u)&&u.status==="0x1"&&!u.error))throw new a("A prerequisite failed during the output simulation.");let n=r.at(-1);if(!V(n)||n.status!=="0x0")throw new a("The output simulation did not return the expected minimum-output control.");let t=typeof n.returnData=="string"&&n.returnData!=="0x"?n.returnData:V(n.error)?n.error.data:void 0;if(typeof t!="string"||!/^0x[0-9a-fA-F]+$/.test(t))throw new a("The output simulation did not report an expected amount.");let d=me({abi:h,data:t});if(d.errorName!=="V4TooLittleReceived"||d.args[0]!==L||d.args[1]<=0n||d.args[1]>=L)throw new a("The output simulation did not report a valid amount.");return d.args[1]}async function j(e,s){let i=await c.getBlockNumber(),r=new Map,n=new Set;for(let t=be;t<=i;t+=J){let d=t+J-1n>i?i:t+J-1n,u=await c.getLogs({address:M,event:D[0],...s?{args:{token:s}}:{},fromBlock:t,toBlock:d,strict:!0});for(let l of u){if(!l.transactionHash)throw new a("A launch log is missing its transaction hash.");r.has(l.transactionHash)||r.set(l.transactionHash,await c.getTransactionReceipt({hash:l.transactionHash}))}if(e){let l=await c.getLogs({address:H,event:D[1],args:{to:e},fromBlock:t,toBlock:d,strict:!0});for(let b of l){let N=X({abi:D,eventName:"Transfer",data:b.data,topics:b.topics}).args;n.add(N.tokenId.toString())}}}return{receipts:[...r.values()],feeIds:n}}async function B(e){let i=(e.launchTx!==void 0?[await c.getTransactionReceipt({hash:xe(e.launchTx)})]:(await j(void 0,e.token===void 0?void 0:A(e.token))).receipts).flatMap(ce).filter(r=>e.positionId!==void 0?r.positionId===R(e.positionId,"positionId").toString():p(r.token,A(e.token)));if(i.length!==1)throw new a("No unique current-strategy launch was found. Older strategy generations are unsupported.");return i[0]}async function x(e,s){if(typeof e.creatorFees!="boolean")throw new a("creatorFees must be an explicit boolean; the choice is permanent.");if(e.pair!==void 0&&!p(A(e.pair),k)&&!p(A(e.pair),K))throw new a("Only the native ETH pair is supported.");if(e.decimals!==void 0&&e.decimals!==18)throw new a("Instant Launch requires 18 decimals.");if(e.supply!==void 0&&R(e.supply,"supply")!==W)throw new a("Instant Launch requires a supply of one billion tokens.");let i=A(e.feeBeneficiary);if(p(i,k)||p(i,E))throw new a("The fee beneficiary must be a wallet other than the launcher or zero address.");let r=P(e.name,"name"),n=P(e.symbol,"symbol"),t=e.initialBuy===void 0?0n:R(e.initialBuy,"initialBuy",!0);if(t>L)throw new a("The initial buy exceeds uint128.");if(t===0n&&e.minAmountOut!==void 0)throw new a("A minimum output requires an initial buy.");let d=await c.readContract({address:E,abi:h,functionName:"getGraffiti",args:[s]}),u=A(await c.readContract({address:m.uerc20Factory.address,abi:h,functionName:"getUERC20Address",args:[r,n,18,E,d]})),l=await c.getCode({address:u});if(l&&l!=="0x")throw new a("This wallet already launched that name and symbol.");let b=$(C("(string,string,string,bytes)"),[[P(e.description,"description",!0),P(e.website,"website",!0),P(e.imageUri,"image URI",!0),"0x"]]),N=e.creatorFees?M[0]:M[1],ue=[S({abi:h,functionName:"createToken",args:[m.uerc20Factory.address,r,n,18,W,E,b]}),S({abi:h,functionName:"distributeToken",args:[u,{strategy:N,amount:W,configData:$(C("address"),[i])},ae]})],fe=await q(),ee=le=>{let ne=[...ue];if(t>0n){let pe=$(C("(address,address,bytes)"),[[G,s,I(u,!0,t,le,s,fe).encoded]]);ne.push(S({abi:h,functionName:"distributeWithNative",args:[m.universalRouterStrategyApp.address,pe,ae,t]}))}return f(E,S({abi:h,functionName:"multicall",args:[ne]}),t,`Atomic Instant Launch: creator fees ${e.creatorFees?"on":"off"} (permanent); beneficiary ${i}.`)},te=t>0n?Q(await U([ee(L)],s),e):0n;return g([ee(te)],s,`Launch ${r} (${u}, chain 4663), supply 1000000000, decimals 18. Creator fees ${e.creatorFees?"on":"off"} are permanent; fee beneficiary ${i}. Creator ETH fees come from buys only (recorded 0.09996%); sells compound into locked liquidity. Initial-buy minimum ${te} token base units. Off-chain image/display unproven; no private metadata registration. No transaction sent.`)}async function O(e,s,i){let r=R(e.amountIn,"amountIn");if(r>L)throw new a("The trade amount exceeds uint128.");let n=A(e.token);await B(e);let t=await q(),d=[];i||(await c.readContract({address:n,abi:he,functionName:"allowance",args:[s,m.permit2.address]})<r&&d.push(o.approval(n,m.permit2.address,r.toString(),T)),d.push(f(m.permit2.address,S({abi:h,functionName:"approve",args:[n,G,r,Number(t)]}),0n,`Permit the exact ${r} token base units until ${t}.`)));let u=N=>[...d,f(G,S({abi:h,functionName:"execute",args:["0x10",I(n,i,r,N,s,t).inputs,t]}),i?r:0n,`${i?"Buy":"Sell"} ${n} with minimum output ${N}.`)],l=await U(u(L),s),b=Q(l,e);return g(u(b),s,`${i?"Buy":"Sell"} token ${n} (chain 4663, 18 decimals), amountIn ${r}, minimum output ${b} ${i?"token":"ETH"} base units (18 decimals). Recorded swap fee 0.2899%; creator ETH fees from buys only, none from sells. No transaction sent.`)}async function Y(e,s,i){let r=await B(e),n=BigInt(r.positionId),t=r.creatorFees?m.feeSplitterFeesOn.address:m.feeSplitterFeesOff.address,d=await c.readContract({address:m.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[n]});if(!p(d,t))throw new a("The position is not locked in its current-strategy splitter.");if(!i)return g([f(t,S({abi:h,functionName:"collectFees",args:[[n]]}),0n,`Collect fees for position ${n}; permissionless.`)],s,"Collect fees for the entitled recipients; collection does not transfer creator fees to the collector. No transaction sent.");if(!r.creatorFees)throw new a("Creator fees are permanently disabled for this position.");let u=await c.readContract({address:H,abi:h,functionName:"ownerOf",args:[n]});if(!p(u,s))throw new a("Only the current fee NFT holder is entitled to claim.");let l=await c.readContract({address:H,abi:h,functionName:"amounts",args:[n]}),b=Q(l[0],e,"minEth");if(l[1]!==0n)throw new a("The current buy-only creator fee configuration returned unexpected token fees.");return g([f(H,S({abi:h,functionName:"claim",args:[n,b,0n]}),0n,`Claim collected ETH fees for position ${n} to ${s}.`)],s,`Claim collected fees: ${l[0]} ETH base units (18 decimals), minimum ${b}. Uncollected fees require poolstrade_collect first. No transaction sent.`)}let w={type:"string"},v={type:"string",pattern:"^[0-9]+$"},Z={chainId:{type:"integer",const:T},slippageBps:{type:"integer",minimum:0,maximum:9999}};function _(e,s,i,r){return{name:`poolstrade_${e}`,inputSchema:{type:"object",additionalProperties:!1,properties:{...Z,...s},required:i},execute:async(n,t)=>{try{let d=new Set([...Object.keys(Z),...Object.keys(s)]);if(Object.keys(n).some(u=>!d.has(u)))throw new a("Unsupported input; only the current atomic Instant Launch workflow is supported.");if(n.chainId!==void 0&&n.chainId!==T)throw new a("pools.trade requires chain 4663.");if(A(t),n.slippageBps!==void 0){if(typeof n.slippageBps!="number")throw new a("Slippage must be an integer in basis points.");z("10000",n.slippageBps)}return await F(),await r(n,t)}catch(d){y(d)}}}}return{tools:[_("launch",{name:w,symbol:w,creatorFees:{type:"boolean",description:"Permanent choice; must be explicit."},feeBeneficiary:w,pair:w,decimals:{type:"integer",const:18},supply:v,initialBuy:v,minAmountOut:v,description:w,website:w,imageUri:w},["name","symbol","creatorFees","feeBeneficiary"],x),...["buy","sell"].map(e=>_(e,{token:w,amountIn:v,minAmountOut:v,launchTx:w},["token","amountIn"],(s,i)=>O(s,i,e==="buy"))),_("collect",{positionId:v,launchTx:w},["positionId"],(e,s)=>Y(e,s,!1)),_("claim",{positionId:v,launchTx:w,minEth:v},["positionId"],(e,s)=>Y(e,s,!0))],positions:async e=>{try{A(e),await F();let{receipts:s,feeIds:i}=await j(e),r=[];for(let n of s)for(let t of ce(n)){let d=!1;if(t.creatorFees&&(i.has(t.positionId)||p(n.from,e))&&(d=p(await c.readContract({address:H,abi:h,functionName:"ownerOf",args:[BigInt(t.positionId)]}),e)),!d&&!p(n.from,e))continue;let u=d?[{token:Te,amount:(await c.readContract({address:H,abi:h,functionName:"amounts",args:[BigInt(t.positionId)]}))[0].toString()}]:[];r.push({module:"poolstrade",id:t.positionId,chainId:T,assets:u,description:`Current Instant Launch ${t.token} (18 decimals, supply 1000000000), pool ${t.poolId}; creator fees ${t.creatorFees?"on":"off"} (permanent). ${d?"Collected ETH fees only; uncollected fees excluded.":"Launch record; no fee entitlement held."} Liquidity is permanently locked.`})}return r}catch(s){return y(s)}}}};function Le(o){return oe("poolstrade",[Ae(o)])}export{ce as a,Ae as b,Le as c};
@@ -1 +0,0 @@
1
- import{b as ae,o as F}from"./VBV366XQ.js";import{a as h,i as re,j as K}from"./25EOXUBI.js";import{a as O}from"./T5E4OJEU.js";import{randomBytes as ue,randomUUID as le}from"node:crypto";import{isDeepStrictEqual as se}from"node:util";import{decodeFunctionData as oe,encodeAbiParameters as Z,erc20Abi as J,getAddress as pe,isAddress as me,keccak256 as ee,parseAbi as te,parseAbiParameters as ne,toEventSelector as fe,zeroAddress as U}from"viem";var ie=re[h].meridian,L=ie.PredictionMarketEscrow.address,H=ie.SecondaryMarketEscrow.address,C={address:ie.CollateralToken_USDe.address,chainId:h,symbol:"USDe",decimals:18},ye="wss://relayer.predict.meridian.xyz/auction",ge=ne("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),he=ne("bytes32,uint256,uint256,address,address,address,bytes"),be=ne("address,address,address,address,uint256,uint256"),j=te(["function getNonce(address) view returns (uint256)","function isNonceUsed(address,uint256) view returns (bool)"]),we=te(["function mint(((address conditionResolver,bytes conditionId,uint8 predictedOutcome)[] picks,uint256 predictorCollateral,uint256 counterpartyCollateral,address predictor,address counterparty,uint256 predictorNonce,uint256 counterpartyNonce,uint256 predictorDeadline,uint256 counterpartyDeadline,bytes predictorSignature,bytes counterpartySignature,bytes32 refCode,bytes predictorSessionKeyData,bytes counterpartySessionKeyData,address predictorSponsor,bytes predictorSponsorData) request)"]),ke=te(["function executeTrade((address token,address collateral,address seller,address buyer,uint256 tokenAmount,uint256 price,uint256 sellerNonce,uint256 buyerNonce,uint256 sellerDeadline,uint256 buyerDeadline,bytes sellerSignature,bytes buyerSignature,bytes32 refCode,bytes sellerSessionKeyData,bytes buyerSessionKeyData) request)"]),Ie=fe("Transfer(address,address,uint256)"),Be=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],Se=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function i(e){throw new O(e)}function R(e){return(!e||typeof e!="object"||Array.isArray(e))&&i("Meridian returned an invalid exchange object."),e}function S(e,n,d=!1){return d&&typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&(e=String(e)),(typeof e!="string"||!/^\d+$/.test(e)||BigInt(e)>=1n<<256n)&&i(`Provide ${n} as a decimal base-unit integer string.`),e}function x(e){return(typeof e!="string"||!me(e,{strict:!1})||e.toLowerCase()===U)&&i("Provide a nonzero token, resolver or wallet address."),pe(e)}function V(e,n){return(typeof e!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(e)||n!==void 0&&e.length!==2+n*2)&&i("Meridian returned invalid hexadecimal data."),e}function q(e){return(typeof e!="string"||e.length===0||e.length>256)&&i("Meridian returned an invalid exchange identifier."),e}function k(e,n){return e?.toLowerCase()===n.toLowerCase()}function G(){return BigInt(Math.floor(Date.now()/1e3))}function Me(e,n){let d=e==="buy"?["picks","stake","minCounterpartyCollateral","usdgAmountIn","slippageBps","continuation","signature"]:["token","amount","minPrice","slippageBps","continuation","signature"];Object.keys(n).some(I=>!d.includes(I))&&i("Unsupported Meridian arguments; use the tool input schema."),n.slippageBps!==void 0&&(typeof n.slippageBps!="number"||!Number.isInteger(n.slippageBps)||n.slippageBps<0||n.slippageBps>=1e4)&&i("Slippage must be an integer from 0 to 9999 basis points.");let c=n.slippageBps;if(e==="sell"){let I=S(n.amount,"the position amount");BigInt(I)===0n&&i("The position amount must be positive.");let b=x(n.token);(k(b,C.address)||k(b,K))&&i("Choose a Meridian position token to sell.");let $;if(n.minPrice!==void 0){let A=S(n.minPrice,"the minimum sale price");BigInt(A)<=1n&&i("The minimum sale price must be greater than 1 base unit."),$=c===void 0?A:F(A,c),BigInt($)<=1n&&i("The minimum sale price after slippage must be greater than 1 base unit.")}else{let A=BigInt(I)/100n>10n**18n?BigInt(I)/100n:10n**18n;$=c===void 0?A.toString():F(A.toString(),c)}return{side:e,token:b,amount:I,minPrice:$,...c===void 0?{}:{slippageBps:c}}}(!Array.isArray(n.picks)||n.picks.length<1||n.picks.length>10)&&i("Provide between one and ten Meridian picks.");let f=n.picks.map(I=>{let b=R(I);return(Object.keys(b).some($=>!["conditionResolver","conditionId","predictedOutcome"].includes($))||b.predictedOutcome!==0&&b.predictedOutcome!==1)&&i("Each pick needs a resolver, condition ID and outcome 0 or 1."),{conditionResolver:x(b.conditionResolver),conditionId:V(b.conditionId),predictedOutcome:b.predictedOutcome}}).sort((I,b)=>{let $=`${I.conditionResolver.toLowerCase()}:${I.conditionId.toLowerCase()}:${I.predictedOutcome}`,A=`${b.conditionResolver.toLowerCase()}:${b.conditionId.toLowerCase()}:${b.predictedOutcome}`;return $<A?-1:$>A?1:0}),m=f.map(I=>`${I.conditionResolver.toLowerCase()}:${I.conditionId.toLowerCase()}`);new Set(m).size!==f.length&&i("Do not repeat a condition in the same prediction.");let B=S(n.stake,"the USDe stake");BigInt(B)<10n**18n&&i("Meridian requires a stake of at least 1 USDe.");let M=n.usdgAmountIn===void 0?void 0:S(n.usdgAmountIn,"the USDG swap amount");M!==void 0&&BigInt(M)===0n&&i("The USDG swap amount must be positive.");let _=n.minCounterpartyCollateral!==void 0?S(n.minCounterpartyCollateral,"the minimum counterparty collateral"):F(B,c??ae);return BigInt(_)<=1n&&i("The minimum counterparty collateral must be greater than 1 base unit."),{side:e,picks:f,stake:B,minCounterpartyCollateral:_,...M===void 0?{}:{usdgAmountIn:M},...c===void 0?{}:{slippageBps:c}}}var X=class{constructor(n,d){this.id=n;this.prefix=d;this.socket=new globalThis.WebSocket(ye),this.socket.addEventListener("open",()=>{this.opened=!0,this.notify?.()}),this.socket.addEventListener("close",()=>this.stop("Meridian exchange socket was lost. Start a fresh auction.")),this.socket.addEventListener("error",()=>this.stop("Meridian exchange socket failed. Start a fresh auction.")),this.socket.addEventListener("message",c=>{try{(typeof c.data!="string"||c.data.length>65536)&&i("Meridian returned a malformed exchange message.");let f=R(JSON.parse(c.data));if(f.type==="pong")return;let m=q(f.type),B=R(f.payload);if((m==="error"||m===`${d}.error`||m===`${d}.rejected`||m===`${d}.failed`||m===`${d}.expired`)&&i("Meridian rejected or failed the exchange. Start a fresh auction."),m===`${d}.ack`){(B.id!==n||this.auctionId!==void 0)&&i("Meridian acknowledged a different exchange."),this.auctionId=q(B.auctionId);return}if((!m.startsWith(`${d}.`)||B.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),(m===`${d}.pending`||m===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),m===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:m,payload:B}),this.notify?.()}catch{this.stop("Meridian rejected or returned an invalid exchange message. Start a fresh auction.")}})}id;prefix;socket;queue=[];notify;error;auctionId;accepting=!1;opened=!1;check(){if(this.error)throw this.error;this.socket.readyState>1&&i("Meridian exchange socket was lost. Start a fresh auction.")}stop(n){this.error??=new O(n),this.notify?.(),this.socket.readyState<2&&this.socket.close()}async wait(n,d=3e4){return new Promise((c,f)=>{let m=setTimeout(()=>this.stop("Meridian exchange timed out. Start a fresh auction."),d),B=()=>{try{if(this.check(),n===void 0?!this.opened:!this.queue.length)return;let M=n===void 0?void 0:this.queue.shift();M&&M.type!==`${this.prefix}.${n}`&&i("Meridian returned an unexpected exchange stage."),clearTimeout(m),this.notify=void 0,c(M?.payload??{})}catch(M){clearTimeout(m),this.notify=void 0,f(M)}};this.notify=B,B()})}send(n,d){this.check(),this.socket.readyState!==1&&i("Meridian exchange socket is not open."),n==="accept"&&(this.accepting=!0),this.socket.send(JSON.stringify({...n==="start"?{id:this.id}:{},type:`${this.prefix}.${n}`,payload:d}))}};function Y(e){return ee(Z(ge,[e]))}function $e(e,n,d){return ee(Z(he,[Y(e.picks),BigInt(e.stake),BigInt(d.counterpartyCollateral),n,d.counterparty,U,"0x"]))}function Ae(e,n,d,c){return ee(Z(be,[e.token,C.address,n,d,BigInt(e.amount),BigInt(c)]))}function Q(e,n){let{input:d,wallet:c,nonce:f,deadline:m}=e,B={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:h,verifyingContract:e.continuation.escrowContract};return(!f||!m)&&i("Meridian exchange is missing its signing terms."),d.side==="buy"?(n||i("Meridian has not returned a winning bid."),{domain:B,primaryType:"MintApproval",types:{MintApproval:Be},message:{predictionHash:$e(d,c,n),signer:c,collateral:d.stake,nonce:f,deadline:m}}):{domain:B,primaryType:"TradeApproval",types:{TradeApproval:Se},message:{tradeHash:Ae(d,c,n?n.buyer:U,n?n.price:"0"),signer:c,nonce:f,deadline:m}}}function de(e){let n=[BigInt(e.deadline)],d=e.continuation;if(d.stage==="primary_accept"||d.stage==="secondary_accept"){n.push(BigInt(d.acceptDeadline));let c=d.winningBid;d.stage==="primary_accept"&&n.push(BigInt(c.counterpartyDeadline)),c.buyerDeadline!==void 0&&n.push(BigInt(S(c.buyerDeadline,"the buyer deadline",!0)))}return n.reduce((c,f)=>c<f?c:f)}function z(e){e.channel?.check(),e.deadline&&G()>=de(e)&&i("Meridian exchange expired. Start a fresh auction.")}var Ee=e=>{let n=new Map;function d(t){clearTimeout(t.timer),n.delete(t.continuation.requestId),t.channel?.stop("Meridian exchange is closed or expired. Start a fresh auction.")}function c(t,a){clearTimeout(t.timer),t.timer=setTimeout(()=>d(t),a),t.timer.unref?.()}function f(t){let{wallet:a,chainId:s,escrowContract:p,requestId:u}=t.continuation;return{wallet:a,chainId:s,escrowContract:p,requestId:u}}async function m(t){let{input:a,wallet:s}=t,p=e.clientFor(h),u=a.side==="buy"?C.address:a.token,r=a.side==="buy"?a.stake:a.amount,[y,w]=await Promise.all([p.readContract({address:u,abi:J,functionName:"balanceOf",args:[s]}),p.readContract({address:u,abi:J,functionName:"allowance",args:[s,t.continuation.escrowContract]})]);if(a.side==="sell"&&await p.readContract({address:u,abi:J,functionName:"decimals"})!==18&&i("Meridian position tokens must have 18 decimals."),y>=BigInt(r)&&w>=BigInt(r))return;(t.continuation.stage==="primary_accept"||t.continuation.stage==="secondary_accept")&&i("Meridian prerequisites changed during the auction. Start a fresh auction after funding and approval.");let l,D;if(y<BigInt(r)){a.side==="sell"&&i("The wallet does not have enough position tokens to sell."),a.usdgAmountIn||i("Not enough USDe. Provide usdgAmountIn in USDG base units to quote a swap before the auction.");let g=await e.quoteSwap({from:K,to:C.address,amountIn:a.usdgAmountIn,...a.slippageBps===void 0?{}:{slippageBps:a.slippageBps}},s);(G()>=BigInt(S(g.expiresAt,"the swap expiry"))||BigInt(S(g.minAmountOut,"the swap minimum"))+y<BigInt(r))&&i("The USDG swap minimum does not cover the USDe stake, or the quote expired. Request a fresh quote with sufficient input.");let o=await e.buildSwap(g.quoteId,s);(!("txs"in o)||!o.txs.length)&&i("The swap coordinator did not return prerequisite transactions."),l=o.txs,D=`${o.summary} Minimum USDe output: ${g.minAmountOut} base units (18 decimals).`}else l=[e.approval(u,t.continuation.escrowContract,r,h)],D=`Approve exactly ${r} base units (18 decimals) of ${u} for ${t.continuation.escrowContract} on chain ${h}.`;l.some(g=>g.chainId!==h)&&i("Meridian prerequisite transactions must use chain 4663.");let v=await e.preview(l,s),T=v.changes.map(g=>{let o=g.amount.startsWith("-");return`${o?"-":"+"}${e.formatAmount(o?g.amount.slice(1):g.amount,g.token.decimals)} ${g.token.symbol} (${g.token.address}, chain ${g.token.chainId}, ${g.token.decimals} decimals)`}).join("; ");return t.channel?.stop("Meridian prerequisites must be mined before the auction."),t.channel=void 0,t.deadline=void 0,t.nonce=void 0,t.continuation={...f(t),stage:"prerequisites"},{steps:l.map(g=>({kind:"tx",tx:g})),continuation:structuredClone(t.continuation),summary:`${D} ${v.summary} ${T}. Mine these prerequisites before continuing; no RFQ has started.`}}function B(t){let a=t.continuation;a.stage==="prerequisites"&&i("Meridian prerequisites need to finish before signing."),z(t),c(t,Number(de(t)-G())*1e3);let s=t.input,p=s.side==="buy"?`Stake ${s.stake} base units of USDe (${C.address}, 18 decimals)`:`Sell ${s.amount} base units of position ${s.token} (18 decimals)`,u=a.stage==="secondary_start"?"Initial buyer-zero, price-zero intent only.":a.stage==="primary_accept"?`Counterparty ${a.winningBid.counterparty}; counterparty collateral ${a.winningBid.counterpartyCollateral} USDe base units; counterparty deadline ${a.winningBid.counterpartyDeadline}.`:`Buyer ${a.winningBid.buyer}; receive ${a.winningBid.price} USDe base units (${C.address}, 18 decimals).`;return{steps:[{kind:"typedData",request:structuredClone(a.request)}],continuation:structuredClone(a),summary:`${p} on chain ${h}. Approval was checked on chain. ${u} Sign locally for domain ${a.request.domain.name}, version 1, escrow ${a.escrowContract}, signature deadline ${t.deadline}${"acceptDeadline"in a?`, acceptance deadline ${a.acceptDeadline}`:""}. External relayer settlement is pending; a signature is not a fill.`}}async function M(t){let a=await t.channel.wait("result"),s=R(a.winningBid),p=q(a.auctionId);s.auctionId!==p&&i("Meridian winning bid belongs to another auction.");let u=S(a.acceptDeadline,"the acceptance deadline",!0);if(t.input.side==="buy"){let r={auctionId:p,counterparty:q(s.counterparty),counterpartyCollateral:S(s.counterpartyCollateral,"the counterparty collateral"),counterpartyNonce:S(s.counterpartyNonce,"the counterparty nonce",!0),counterpartyDeadline:S(s.counterpartyDeadline,"the counterparty deadline",!0),receivedAt:q(s.receivedAt)};x(r.counterparty),(!Number.isFinite(Date.parse(r.receivedAt))||BigInt(r.counterpartyCollateral)<=1n||BigInt(r.counterpartyCollateral)<BigInt(t.input.minCounterpartyCollateral))&&i("Meridian winning bid counterparty collateral is below the caller minimum."),t.continuation={...f(t),stage:"primary_accept",auctionId:p,winningBid:r,acceptDeadline:u,request:Q(t,r)}}else{let r={auctionId:p,buyer:q(s.buyer),price:S(s.price,"the sale price"),...s.buyerDeadline!==void 0?{buyerDeadline:S(s.buyerDeadline,"the buyer deadline",!0)}:{},...s.buyerNonce!==void 0?{buyerNonce:S(s.buyerNonce,"the buyer nonce",!0)}:{},...s.receivedAt!==void 0?{receivedAt:q(s.receivedAt)}:{}};x(r.buyer),(BigInt(r.price)<=1n||BigInt(r.price)<BigInt(t.input.minPrice))&&i("Meridian winning bid sale price is below the caller minimum."),t.continuation={...f(t),stage:"secondary_accept",auctionId:p,winningBid:r,acceptDeadline:u,request:Q(t,r)}}return B(t)}async function _(t,a){let s=t.continuation;s.stage!=="primary_accept"&&s.stage!=="secondary_accept"&&i("Meridian exchange is not ready for acceptance."),z(t),t.channel.send("accept",{auctionId:s.auctionId,[t.input.side==="buy"?"predictorSignature":"sellerSignature"]:a}),c(t,15e4);let p=await t.channel.wait("filled",12e4),u=V(p.transactionHash,32),r=e.clientFor(h),[y,w]=await Promise.all([r.waitForTransactionReceipt({hash:u,timeout:12e4}),r.getTransaction({hash:u})]);(y.status!=="success"||!k(y.transactionHash,u)||!k(w.hash,u)||!k(y.to,s.escrowContract)||!k(w.to,s.escrowContract)||w.chainId!==h)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:l,wallet:D}=t;if(l.side==="buy"&&s.stage==="primary_accept"){let o=oe({abi:we,data:w.input}).args[0];(!k(Y([...o.picks]),Y(l.picks))||o.predictorCollateral!==BigInt(l.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!k(o.predictor,D)||!k(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(t.nonce)||o.counterpartyNonce!==BigInt(s.winningBid.counterpartyNonce)||o.predictorDeadline!==BigInt(t.deadline)||o.counterpartyDeadline!==BigInt(s.winningBid.counterpartyDeadline)||!k(o.predictorSponsor,U)||o.predictorSponsorData!=="0x"||o.predictorSignature!==a)&&i("Meridian mint receipt does not match the accepted prediction.")}else if(l.side==="sell"&&s.stage==="secondary_accept"){let o=oe({abi:ke,data:w.input}).args[0];(!k(o.token,l.token)||!k(o.collateral,C.address)||!k(o.seller,D)||!k(o.buyer,s.winningBid.buyer)||o.tokenAmount!==BigInt(l.amount)||o.price!==BigInt(s.winningBid.price)||o.sellerNonce!==BigInt(t.nonce)||o.sellerDeadline!==BigInt(t.deadline)||o.sellerSignature!==a)&&i("Meridian sale receipt does not match the accepted trade.")}let v=new Map,T=new Map;for(let o of y.logs){if(o.topics[0]!==Ie||o.topics.length!==3)continue;(!/^0x[0-9a-fA-F]{64}$/.test(o.data)||!o.topics.slice(1).every(ce=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ce)))&&i("Meridian receipt has malformed transfer logs.");let E=`0x${o.topics[1].slice(-40)}`,N=`0x${o.topics[2].slice(-40)}`,P=o.address.toLowerCase(),W=BigInt(o.data);v.set(P,(v.get(P)??0n)+(k(N,D)?W:0n)-(k(E,D)?W:0n)),k(E,U)&&k(N,D)&&T.set(P,(T.get(P)??0n)+W)}let g;if(l.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(l.stake)+BigInt(s.winningBid.counterpartyCollateral),E=[...T].filter(([N,P])=>!k(N,C.address)&&P===o&&v.get(N)===o);(E.length!==1||v.get(C.address.toLowerCase())!==-BigInt(l.stake))&&i("Meridian mint receipt does not prove the expected collateral and position delta."),g=`${o} base units received in position ${E[0][0]}`}else l.side==="sell"&&s.stage==="secondary_accept"?((v.get(l.token.toLowerCase())!==-BigInt(l.amount)||v.get(C.address.toLowerCase())!==BigInt(s.winningBid.price))&&i("Meridian sale receipt does not prove the expected collateral and position delta."),g=`${l.amount} base units sold from position ${l.token}; ${s.winningBid.price} USDe base units received`):i("Meridian fill has a different exchange stage.");return{txs:[],summary:`Meridian ${l.side} filled by the external relayer: ${u}. Successful receipt and transfer deltas verified on chain ${h}: ${g} (18 decimals); collateral USDe ${C.address} (18 decimals).`}}async function I(t,a,s){let p=x(s),u=Me(t,a),r;if(a.continuation!==void 0){let y=R(a.continuation),w=n.get(q(y.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!k(w.wallet,p)||!se(w.input,u)||!se(w.continuation,y))&&i("Meridian continuation or arguments do not match the active wallet exchange."),w.busy&&i("Meridian exchange is already processing this continuation."),r=w}else{a.signature!==void 0&&i("A signature requires an active Meridian continuation."),n.size>=1e3&&i("Too many active Meridian exchanges. Please try again later.");let y=le(),w=setTimeout(()=>{let l=n.get(y);l&&d(l)},9e5);w.unref?.(),r={input:u,wallet:p,continuation:{stage:"prerequisites",wallet:p,chainId:h,escrowContract:t==="buy"?L:H,requestId:y},busy:!1,timer:w},n.set(y,r)}r.busy=!0;try{z(r),await e.clientFor(h).getChainId()!==h&&i("Meridian requires an RPC on chain 4663.");let y=r.continuation.stage;y==="prerequisites"&&a.signature!==void 0&&i("Do not sign before Meridian prerequisites have mined.");let w=await m(r);if(w)return w;if(y==="prerequisites")return r.nonce=t==="buy"?(await e.clientFor(h).readContract({address:L,abi:j,functionName:"getNonce",args:[p]})).toString():BigInt(`0x${ue(16).toString("hex")}`).toString(),r.deadline=(G()+300n).toString(),t==="sell"&&await e.clientFor(h).readContract({address:H,abi:j,functionName:"isNonceUsed",args:[p,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),r.channel=new X(r.continuation.requestId,t==="buy"?"auction":"secondary.auction"),await r.channel.wait(),u.side==="buy"?(r.channel.send("start",{id:r.continuation.requestId,picks:u.picks,predictorCollateral:u.stake,predictor:p,predictorNonce:r.nonce,predictorDeadline:r.deadline,chainId:h,escrowContract:L,mode:"blind"}),await M(r)):(r.continuation={...f(r),stage:"secondary_start",request:Q(r)},B(r));let l=V(a.signature);if(t==="sell"&&await e.clientFor(h).readContract({address:H,abi:j,functionName:"isNonceUsed",args:[p,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),t==="buy"&&(await e.clientFor(h).readContract({address:L,abi:j,functionName:"getNonce",args:[p]})).toString()!==r.nonce&&i("Meridian predictor nonce changed. Start a fresh auction."),z(r),y==="secondary_start"&&u.side==="sell")return r.channel.send("start",{id:r.continuation.requestId,token:u.token,collateral:C.address,tokenAmount:u.amount,seller:p,sellerNonce:r.nonce,sellerDeadline:r.deadline,chainId:h,escrowContract:H,mode:"blind",sellerSignature:l}),await M(r);let D=await _(r,l);return d(r),D}catch(y){throw d(r),new O(e.plainError(y))}finally{r.busy=!1}}let b={type:"string",pattern:"^\\d+$"},$={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},A={continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...A,stake:{...b,description:"USDe stake in base units, 18 decimals, chain 4663."},minCounterpartyCollateral:{...b,description:"Optional caller minimum counterparty collateral in USDe base units, 18 decimals."},usdgAmountIn:{...b,description:"Optional exact USDG swap input in base units, 6 decimals, if USDe balance is insufficient."},slippageBps:{type:"integer",minimum:0,maximum:9999},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:$,conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"},predictedOutcome:{type:"integer",enum:[0,1]}}}}}},execute:(t,a)=>I("buy",t,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...A,token:{...$,description:"Position token address on chain 4663."},amount:{...b,description:"Position amount in base units, 18 decimals."},minPrice:{...b,description:"Optional caller minimum sale price in USDe base units, 18 decimals."},slippageBps:{type:"integer",minimum:0,maximum:9999}}},execute:(t,a)=>I("sell",t,a)}]}};export{Ee as a};
@@ -1 +0,0 @@
1
- import{a as q}from"./S3YSJ7XH.js";import{a as H}from"./VZWOWR6G.js";import{a as p,i as I}from"./25EOXUBI.js";import{a as d}from"./T5E4OJEU.js";import{encodeAbiParameters as K,encodeFunctionData as P,erc20Abi as D,keccak256 as Q,parseAbi as R,zeroAddress as b}from"viem";var s=R(["function launchFactory() view returns (address)","function curve() view returns (address)","function factory() view returns (address)","function feeEscrow() view returns (address)","function memeHook() view returns (address)","function getLaunchedToken(address) view returns ((address token,address curve,address deployer,address creatorFeeRecipient,address pairToken,uint256 graduationThreshold,uint24 poolFee,int24 tickSpacing,uint16 creatorTaxBps,bool buybackEnabled,uint8 phase,uint256 sweptQuote,uint256 sweptTokens,uint256 sweptAt,bool exists))","function balanceOf(address) view returns (uint256)","function quoteFeeBalance() view returns (uint256)","function creatorTaxBalance() view returns (uint256)","function pendingFees(bytes32,address) view returns (uint256)","function pendingCreatorTax(bytes32,address) view returns (uint256)"]),h=R(["function sweepFees(uint256 minBuybackTokensOut)","function sweepPoolFees(bytes32 poolId,uint256 minConversionQuoteOut,uint256 minBuybackTokensOut)","function claim()","error InternalSwapRequiresOperator()"]),F={address:q,chainId:p,symbol:"ETH",decimals:18};function u(n){if(typeof n!="string")throw new d("Provide a valid Pons coin address.");if(H(n),n.toLowerCase()===b)throw new d("Provide a nonzero Pons coin or contract address.");return n.toLowerCase()}function $(n){let l=new Set;for(;n&&typeof n=="object"&&!l.has(n)&&l.size<16;){l.add(n);let r=n;if(r.data==="0x31cdb504"||r.data&&typeof r.data=="object"&&r.data.errorName==="InternalSwapRequiresOperator")return!0;n=r.cause}return!1}async function G(n,l,r){if(!l||Object.keys(l).some(o=>o!=="token"))throw new d("Unsupported input. Provide only the Pons coin token address.");let i=u(l.token),A=u(r),e=n.clientFor(p);if(await e.getChainId()!==p)throw new d(`Pons claims require chain ${p}.`);let t=await e.getBlockNumber(),[U,j]=await Promise.all([e.readContract({address:i,abi:s,functionName:"launchFactory",blockNumber:t}),e.readContract({address:i,abi:s,functionName:"curve",blockNumber:t})]),k=u(I[p].pons.factory.address);if(u(U)!==k)throw new d("The coin must belong to the pinned Pons factory.");let f=u(j),[a,L,M]=await Promise.all([e.readContract({address:k,abi:s,functionName:"getLaunchedToken",args:[i],blockNumber:t}),e.readContract({address:f,abi:s,functionName:"factory",blockNumber:t}),e.readContract({address:f,abi:s,functionName:"feeEscrow",blockNumber:t})]);if(!a.exists||u(a.token)!==i||u(a.curve)!==f||u(L)!==k)throw new d("The coin does not resolve to a consistent Pons launch.");if(a.phase<0||a.phase>3)throw new d("This Pons launch phase is unsupported.");let x=u(a.creatorFeeRecipient);if(x!==A)throw new d("Only the current creator fee recipient can claim these fees. Use the recipient wallet or Safe.");if(a.pairToken.toLowerCase()!==b)throw new d("This claim tool supports native ETH pairs. Custom-pair token claims are not supported.");let T=u(M),S=await e.readContract({address:T,abi:s,functionName:"balanceOf",args:[A],blockNumber:t}),w=[],m=[],v=!1,C=!1,N=(o,c,g)=>n.unsignedTx({to:o,data:c,value:"0",chainId:p,description:g});if(a.phase===0){let[o,c]=await Promise.all([e.readContract({address:f,abi:s,functionName:"quoteFeeBalance",blockNumber:t}),e.readContract({address:f,abi:s,functionName:"creatorTaxBalance",blockNumber:t})]);o+c>0n&&(m.push({token:F,amount:(o+c).toString()}),a.buybackEnabled?C=!0:(await e.simulateContract({address:f,abi:h,functionName:"sweepFees",args:[0n],account:r,blockNumber:t}),w.push(N(f,P({abi:h,functionName:"sweepFees",args:[0n]}),"Sweep native curve fees into the recipient escrow."))))}else if(a.phase===2){let o=u(await e.readContract({address:k,abi:s,functionName:"memeHook",blockNumber:t})),c=Q(K([{type:"address"},{type:"address"},{type:"uint24"},{type:"int24"},{type:"address"}],[b,i,a.poolFee,a.tickSpacing,o])),[g,E,B,O]=await Promise.all([e.readContract({address:o,abi:s,functionName:"pendingFees",args:[c,b],blockNumber:t}),e.readContract({address:o,abi:s,functionName:"pendingCreatorTax",args:[c,b],blockNumber:t}),e.readContract({address:o,abi:s,functionName:"pendingFees",args:[c,i],blockNumber:t}),e.readContract({address:o,abi:s,functionName:"pendingCreatorTax",args:[c,i],blockNumber:t})]);if(g+E>0n&&m.push({token:F,amount:(g+E).toString()}),B+O>0n){let[y,z]=await Promise.all([e.readContract({address:i,abi:D,functionName:"symbol",blockNumber:t}),e.readContract({address:i,abi:D,functionName:"decimals",blockNumber:t})]);m.push({token:{address:i,chainId:p,symbol:y,decimals:z},amount:(B+O).toString()})}if(m.length)if(a.buybackEnabled)C=!0;else try{await e.simulateContract({address:o,abi:h,functionName:"sweepPoolFees",args:[c,0n,0n],account:r,blockNumber:t}),w.push(N(o,P({abi:h,functionName:"sweepPoolFees",args:[c,0n,0n]}),"Sweep native pool fees into the recipient escrow."))}catch(y){if(!$(y))throw y;v=!0}}(S>0n||w.length>0)&&w.push(N(T,P({abi:h,functionName:"claim"}),"Claim the caller\u2019s full native ETH escrow balance across all coins."));let V=await n.preview(w,r),_=[w.length?"Unsigned Pons fee claim prepared for the current recipient. The claim withdraws all native ETH owed to this wallet on this escrow across its coins.":"No native ETH claim is available from this escrow.",v?"Pending token-side conversion is awaiting Pons\u2019s keeper; the hook sweep was skipped.":"",C?"Buyback-enabled fee sweeps are not built here; pending fees await Pons\u2019s operator.":"","Pending amounts are pre-sweep fee and tax totals, not a guaranteed creator payout. Preview excludes gas. No transaction was sent."].filter(Boolean).join(" ");return{txs:w,summary:_,preview:V,claimable:{token:F,amount:S.toString()},pendingBeforeSweep:m,waitingForKeeper:v,recipient:x,escrow:T,phase:a.phase,blockNumber:t.toString()}}var ee=n=>({tools:[{name:"pons_claim",inputSchema:{type:"object",additionalProperties:!1,required:["token"],properties:{token:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$",description:"Pons coin address on chain 4663."}}},execute:async(l,r)=>{try{return await G(n,l,r)}catch(i){throw new d(n.plainError(i))}}}]});export{ee as a};
@@ -1 +0,0 @@
1
- import{b as K,o as de}from"./VBV366XQ.js";import{a as _,b as ae}from"./VZWOWR6G.js";import{a as g,i as M}from"./25EOXUBI.js";import{a as E,c as be}from"./B5RZYFQC.js";import{a as d,b as j,c as S}from"./T5E4OJEU.js";import{decodeFunctionResult as xe,encodeFunctionData as L,getAddress as m,parseAbi as G,zeroAddress as Y}from"viem";var ce=-887272,ue=887272,O=(1n<<128n)-1n,Te="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ce="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",Le="0x3067048beee31b25b2f1681f88dac838c8bba36af25bfb2b7cf7473a5847e35f",Q=2000n,Ne=5,qe=1800n,f=Object.freeze({factory:m(M[4663].uniswap.v3_factory.address),positionManager:m(M[4663].uniswap.v3_position_manager.address),swapRouter02:m(M[4663].uniswap.swap_router02.address),permit2:m(M[4663].uniswap.permit2.address),weth:m(M[4663].uniswap.WETH.address),usdg:m(M[4663].uniswap.USDG.address),ethUsdgPool:m(M[4663].oracle.ethUsdgPool.address)}),$e=Object.freeze({100:1,500:10,3e3:60,1e4:200}),tn=Object.freeze([{fee:100,tickSpacing:1,address:m("0x52e65B17fB6E5BA00Ed806f37Afcd2DaA50271Ca"),token0:f.weth,token1:f.usdg,recordedLiquidity:"1957537485734736219",recordedSqrtPriceX96:"3839219776288481168641554",recordedTick:-198707,feeProtocol:68},{fee:500,tickSpacing:10,address:m("0x69bfaf19c9f377bb306a89aed9f6b07e2c1a8d9a"),token0:f.weth,token1:f.usdg,recordedLiquidity:"714542894544667104",recordedSqrtPriceX96:"3839644024453020182443671",recordedTick:-198705,feeProtocol:68},{fee:3e3,tickSpacing:60,address:m("0xa9188730fe85be88ad499d7d52b099e800fb0334"),token0:f.weth,token1:f.usdg,recordedLiquidity:"310559629687003603",recordedSqrtPriceX96:"3843235825752878635548672",recordedTick:-198686,feeProtocol:102},{fee:1e4,tickSpacing:200,address:m("0x5f009e071f07e92b6c624e83f52f17bbda34680d"),token0:f.weth,token1:f.usdg,recordedLiquidity:"5822966536584155",recordedSqrtPriceX96:"3853297838190389678059735",recordedTick:-198634,feeProtocol:102}]),v=G(["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"]),ve=G(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)","function feeAmountTickSpacing(uint24 fee) view returns (int24)"]),Ee=G(["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)"]),_e=G(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),me=G(["function decimals() view returns (uint8)","function symbol() view returns (string)","function allowance(address owner, address spender) view returns (uint256)"]),Oe="0xd0e30db0";function Re(n){if(typeof n!="string")return!1;let e=n.trim().toLowerCase();return e===Y||e===Te||e==="eth"||e==="native"}function R(n,e){if(Re(n))throw new d(`Uniswap v3 requires wrapped ERC-20 WETH (${f.weth}) rather than native ETH in ${e}.`);if(typeof n!="string")throw new d(`${e} must be a valid 20-byte hex address.`);return _(n),m(n)}function Be(n,e,t){let r=Number(n),o=Number(e),i=Number(t);if(!Number.isInteger(i)||i<=0)throw new d("Uniswap v3 tickSpacing must be a positive integer.");if(!Number.isInteger(r)||!Number.isInteger(o))throw new d("Uniswap v3 tickLower and tickUpper must be integers.");if(r<ce||o>ue||r>ue||o<ce)throw new d(`Uniswap v3 ticks are out of bounds [${ce}, ${ue}].`);if(r>=o)throw new d("Uniswap v3 tickLower must be strictly less than tickUpper.");if(r%i!==0||o%i!==0)throw new d(`Uniswap v3 tickLower (${r}) and tickUpper (${o}) must be divisible by tickSpacing (${i}).`);return{tickLower:r,tickUpper:o,tickSpacing:i}}function De(n,e){let t=n.trim(),r=t.startsWith("-"),o=r||t.startsWith("+")?t.slice(1):t,i=be(E(o).toString(),e);return r&&i!=="0"?`-${i}`:i}function Ve(n){let e=typeof n=="string"?xe({abi:v,functionName:"positions",data:n}):n;return{nonce:BigInt(e[0]),operator:m(String(e[1])),token0:m(String(e[2])),token1:m(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 ke(n,e){if(!n||!Array.isArray(n.logs))return[];let t=e?m(e).toLowerCase():void 0,r=f.positionManager.toLowerCase(),o=new Set;for(let i of n.logs){if(!i||typeof i.address!="string"||i.address.toLowerCase()!==r)continue;let s=Array.isArray(i.topics)?i.topics.map(u=>String(u).toLowerCase()):[],a=s[0];if(a===Ce&&s.length>=4){let c=`0x${s[2].slice(-40)}`;if(!t||c===t){let p=BigInt(s[3]).toString();p!=="0"&&o.add(p)}}else if(a===Le&&s.length>=2&&!t){let u=BigInt(s[1]).toString();u!=="0"&&o.add(u)}}return[...o]}function on(n){let e=t=>typeof t=="bigint"?t:E(t);return L({abi:_e,functionName:"exactInputSingle",args:[{tokenIn:m(n.tokenIn),tokenOut:m(n.tokenOut),fee:n.fee,recipient:m(n.recipient),amountIn:e(n.amountIn),amountOutMinimum:e(n.amountOutMinimum),sqrtPriceLimitX96:n.sqrtPriceLimitX96!==void 0?e(n.sqrtPriceLimitX96):0n}]})}var ye=1n<<96n;function he(n){let e=Math.abs(n),t=(e&1)!==0?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&2)!==0&&(t=t*0xfff97272373d413259a46990580e213an>>128n),(e&4)!==0&&(t=t*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&8)!==0&&(t=t*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&16)!==0&&(t=t*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&32)!==0&&(t=t*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&64)!==0&&(t=t*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&128)!==0&&(t=t*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&256)!==0&&(t=t*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&512)!==0&&(t=t*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&1024)!==0&&(t=t*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&2048)!==0&&(t=t*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&4096)!==0&&(t=t*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&8192)!==0&&(t=t*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&16384)!==0&&(t=t*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&32768)!==0&&(t=t*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&65536)!==0&&(t=t*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&131072)!==0&&(t=t*0x5d6af8dedb81196699c329225ee604n>>128n),(e&262144)!==0&&(t=t*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&524288)!==0&&(t=t*0x48a170391f7dc42444e8fa2n>>128n),n>0&&(t=((1n<<256n)-1n)/t),(t>>32n)+(t%(1n<<32n)===0n?0n:1n)}function He(n,e,t,r){if(r<=0n)return{amount0:0n,amount1:0n};let[o,i]=e<t?[e,t]:[t,e];if(n<=o)return{amount0:(r<<96n)*(i-o)/i/o,amount1:0n};if(n<i){let a=(r<<96n)*(i-n)/i/n,u=r*(n-o)/ye;return{amount0:a,amount1:u}}return{amount0:0n,amount1:r*(i-o)/ye}}async function U(n,e,t,r){let o=m(e),i,s;if(t===g&&o===f.weth?(i=18,s="WETH"):t===g&&o===f.usdg&&(i=6,s="USDG"),i===void 0){let a=await n.readContract({address:o,abi:me,functionName:"decimals"});i=Number(a)}if(s===void 0)try{let a=await n.readContract({address:o,abi:me,functionName:"symbol"});if(typeof a!="string"||!a.trim())throw new d("Token symbol is unavailable.");s=a.trim()}catch(a){throw new d(`Could not read token metadata. ${S(a)}`)}if(!Number.isInteger(i)||i<0||i>255)throw new d("Token decimals are invalid.");if(r!=null){let a=Number(r);if(!Number.isInteger(a)||a!==i)throw new d(`Token ${o} on chain ${t} has ${i} decimals, not ${String(r)}.`)}return{address:o,symbol:s,decimals:i,chainId:t}}async function We(n){try{if(!n.getBlock)throw new d("Block timestamps are unavailable.");let e=await n.getBlock();if(typeof e.timestamp!="bigint")throw new d("Invalid block timestamp.");return e.timestamp}catch(e){throw new d(`Could not read the current block timestamp. ${S(e)}`)}}function X(n,e){if(typeof n=="bigint"){if(n<0n)throw new d(`${e} must be a non-negative integer.`);return n}if(typeof n=="number"){if(!Number.isSafeInteger(n)||n<0)throw new d(`${e} must be a non-negative integer.`);return BigInt(n)}if(typeof n=="string")return E(n);throw new d(`${e} must be a non-negative integer.`)}async function Ie(n,e){let t=await We(n);if(e==null)return t+qe;let r=X(e,"deadline");if(r<=t)throw new d(`Uniswap v3 deadline (${r.toString()}) has expired at timestamp ${t.toString()}.`);return r}function B(n,e){if(typeof n!="string"||!/^\d+$/.test(n))throw new d(`${e} must be a non-negative integer string in base units.`);return E(n)}function Se(n){let e=n.slippageBps??K;if(typeof e!="number")throw new d("Slippage must be an integer from 0 to 9999 bps.");return de("0",e),e}function J(n,e,t,r){let o=n===void 0?E(de(e.toString(),t)):B(n,r);if(o<=1n)throw new d(`${r} must exceed 1 base unit; the simulated amount may be too small.`);return o}function F(n,e){return ae({to:f.positionManager,data:n,value:"0",chainId:g,description:e})}async function Z(n,e,t){try{if(!n.request)throw new d("Sequential transaction simulation is unavailable.");let o=await n.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:t,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 d("Unexpected batch simulation response.");return o[0].calls.map((i,s)=>{if(i.status!=="0x1"||i.error||typeof i.returnData!="string"||!/^0x([a-fA-F0-9]{2})*$/.test(i.returnData))throw new d(`Simulation call ${s+1} failed. ${S(i.error)}`);return i.returnData})}catch(r){throw new d(`Uniswap v3 simulation failed. ${S(r)}`)}}function ee(n,e){try{return xe({abi:v,functionName:n,data:e})}catch{throw new d(`Uniswap v3 ${n} simulation returned invalid amounts.`)}}function z(n,e={}){if(e.chainId!==void 0&&Number(e.chainId)!==g)throw new d(`Uniswap v3 is only supported on Robinhood Chain (${g}).`);if(e.version!==void 0&&e.version!=="v3")throw new d(`Uniswap v3 handler received unsupported version "${String(e.version)}".`);let t=n.clientFor(g);return{...t,readContract:async r=>{try{return await t.readContract(r)}catch(o){throw new d(`Could not read Uniswap v3 ${r.functionName}. ${S(o)}`,{cause:o})}}}}async function fe(n,e,t){let r;try{r=await n.readContract({address:f.positionManager,abi:v,functionName:"ownerOf",args:[e]})}catch(s){throw new d(`Could not verify owner of Uniswap v3 position #${e}. ${S(s)}`)}let o=m(String(r)),i=m(t);if(o!==i)throw new d(`Wallet ${i} is not the owner of Uniswap v3 position #${e.toString()} (owned by ${o}).`);return o}async function ne(n,e){let t=await n.readContract({address:f.positionManager,abi:v,functionName:"positions",args:[e]});return Ve(t)}function pe(n,e){if(!Array.isArray(e.changes)||!e.changes.length)return n;let t=e.changes.map(r=>`${De(r.amount,r.token.decimals)} ${r.token.symbol}`);return`${n} (${t.join(", ")})`}async function Fe(n,e,t){_(t);let r=m(t),o=z(n,e),i=await Ie(o,e.deadline),s=Se(e),a=e.tokenId===void 0?void 0:X(e.tokenId,"tokenId"),u;if(a!==void 0){if(a<=0n)throw new d("Uniswap v3 tokenId must be a positive integer.");await fe(o,a,r),u=await ne(o,a)}let c=u?.token0??R(e.token0,"token0"),p=u?.token1??R(e.token1,"token1");if(BigInt(c)>=BigInt(p))throw new d("Uniswap v3 requires distinct sorted token addresses.");let w=u?.fee??Number(e.fee??100),l=$e[w];if(!l)throw new d("Unsupported Uniswap v3 fee tier.");let y=m(String(await o.readContract({address:f.factory,abi:ve,functionName:"getPool",args:[c,p,w]})));if(y===Y)throw new d("No Uniswap v3 pool exists for these tokens and fee tier.");let{tickLower:h,tickUpper:T,tickSpacing:N}=Be(u?.tickLower??e.tickLower,u?.tickUpper??e.tickUpper,l),A=await U(o,c,g,e.token0Decimals),b=await U(o,p,g,e.token1Decimals),k=B(e.amount0Desired,"amount0Desired"),x=B(e.amount1Desired,"amount1Desired");if(k===0n&&x===0n)throw new d("Liquidity addition requires a positive desired amount.");let P=e.recipient===void 0?r:R(e.recipient,"recipient");if(P!==r)throw new d("Uniswap recipient must be the signing wallet.");if(e.wrapNative===!0&&c!==f.weth&&p!==f.weth)throw new d("Wrapping requires a positive WETH desired amount.");let D=await Promise.all([c,p].map(async C=>BigInt(await o.readContract({address:C,abi:me,functionName:"allowance",args:[r,f.positionManager]})))),q=(C,H)=>{let re=[];if(e.wrapNative===!0){let W=c===f.weth?C:H;W>0n&&re.push(ae({to:f.weth,data:Oe,value:W.toString(),chainId:g,description:"Wrap ETH into WETH."}))}for(let[W,Ue]of[c,p].entries()){let se=W===0?C:H;se>0n&&D[W]<se&&re.push(n.approval(Ue,f.positionManager,se.toString(),g))}return re},$=a===void 0?"mint":"increaseLiquidity",le=(C,H)=>F(a===void 0?L({abi:v,functionName:"mint",args:[{token0:c,token1:p,fee:w,tickLower:h,tickUpper:T,amount0Desired:k,amount1Desired:x,amount0Min:C,amount1Min:H,recipient:P,deadline:i}]}):L({abi:v,functionName:"increaseLiquidity",args:[{tokenId:a,amount0Desired:k,amount1Desired:x,amount0Min:C,amount1Min:H,deadline:i}]}),`${$==="mint"?"Mint":"Increase"} Uniswap v3 ${A.symbol}/${b.symbol} liquidity.`),ge=await Z(o,[...q(k,x),le(0n,0n)],r),I=ee($,ge[ge.length-1]),Pe=I[I.length-2],Me=I[I.length-1];if(Pe>k||Me>x)throw new d("Simulated liquidity spend exceeds the desired amounts.");let V=q(k,x),ie=J(e.amount0Min,I[I.length-2],s,"amount0Min"),oe=J(e.amount1Min,I[I.length-1],s,"amount1Min");if(ie>k||oe>x)throw new d("Uniswap v3 minimum amount cannot exceed desired amount.");V.push(le(ie,oe));let we=await n.preview(V,r);return{txs:V,preview:we,summary:pe(V[V.length-1].description,we),details:{version:"v3",action:$,...a===void 0?{}:{tokenId:a.toString()},pool:y,fee:w,tickSpacing:N,tickLower:h,tickUpper:T,token0:A,token1:b,amount0Desired:k.toString(),amount1Desired:x.toString(),amount0Min:ie.toString(),amount1Min:oe.toString(),deadline:i.toString(),recipient:P,expectedAmount0:I[I.length-2].toString(),expectedAmount1:I[I.length-1].toString()}}}async function Ge(n,e,t){_(t);let r=m(t),o=z(n,e),i=X(e.tokenId,"tokenId");if(i<=0n)throw new d("Uniswap v3 tokenId must be a positive integer.");await fe(o,i,r);let s=await ne(o,i),a=await U(o,s.token0,g),u=await U(o,s.token1,g),c=e.recipient===void 0?r:R(e.recipient,"recipient");if(c!==r)throw new d("Uniswap recipient must be the signing wallet.");let p=e.amount0Max===void 0?O:B(e.amount0Max,"amount0Max"),w=e.amount1Max===void 0?O:B(e.amount1Max,"amount1Max");if(p===0n&&w===0n||p>O||w>O)throw new d("Collect requires a positive amountMax within uint128.");let l=[F(L({abi:v,functionName:"collect",args:[{tokenId:i,recipient:c,amount0Max:p,amount1Max:w}]}),`Collect Uniswap v3 fees from position #${i}.`)],y=ee("collect",(await Z(o,l,r))[0]),h=await n.preview(l,r);return{txs:l,preview:h,summary:pe(l[0].description,h),details:{version:"v3",action:"collect",tokenId:i.toString(),recipient:c,token0:a,token1:u,amount0Max:p.toString(),amount1Max:w.toString(),expectedAmount0:y[0].toString(),expectedAmount1:y[1].toString()}}}async function Xe(n,e,t){_(t);let r=m(t),o=z(n,e),i=X(e.tokenId,"tokenId");if(i<=0n)throw new d("Uniswap v3 tokenId must be a positive integer.");await fe(o,i,r);let s=await ne(o,i);if(s.liquidity<=0n)throw new d("Position has zero active liquidity to remove.");if(e.liquidity===void 0)throw new d('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let a=e.liquidity==="all"?s.liquidity:B(e.liquidity,"liquidity");if(a<=0n)throw new d("Liquidity to remove must be positive.");if(a>s.liquidity)throw new d("Requested liquidity exceeds position liquidity.");let u=await Ie(o,e.deadline),c=Se(e),p=await U(o,s.token0,g),w=await U(o,s.token1,g),l=e.recipient===void 0?r:R(e.recipient,"recipient");if(l!==r)throw new d("Uniswap recipient must be the signing wallet.");let y=(D,q)=>F(L({abi:v,functionName:"decreaseLiquidity",args:[{tokenId:i,liquidity:a,amount0Min:D,amount1Min:q,deadline:u}]}),`Decrease ${a} liquidity on Uniswap v3 position #${i}.`),h=ee("decreaseLiquidity",(await Z(o,[y(0n,0n)],r))[0]),T=J(e.amount0Min,h[0],c,"amount0Min"),N=J(e.amount1Min,h[1],c,"amount1Min"),A=[y(T,N),F(L({abi:v,functionName:"collect",args:[{tokenId:i,recipient:l,amount0Max:O,amount1Max:O}]}),`Collect principal and fees from Uniswap v3 position #${i}.`)],b=a===s.liquidity,k=b&&e.burn===!0;k&&A.push(F(L({abi:v,functionName:"burn",args:[i]}),`Burn empty Uniswap v3 position #${i}.`));let x=ee("collect",(await Z(o,A,r))[1]),P=await n.preview(A,r);return{txs:A,preview:P,summary:pe(`Remove Uniswap v3 liquidity from position #${i}${k?" and burn NFT":""}`,P),details:{version:"v3",action:"remove",tokenId:i.toString(),recipient:l,token0:p,token1:w,liquidityRemoved:a.toString(),amount0Min:T.toString(),amount1Min:N.toString(),deadline:u.toString(),expectedAmount0:x[0].toString(),expectedAmount1:x[1].toString(),fullExit:b,burned:k}}}async function ze(n,e,t={}){let r=m(e),o=new Set;if(Array.isArray(t.tokenIds))for(let s of t.tokenIds){let a=X(s,"tokenId");a>0n&&o.add(a.toString())}if(Array.isArray(t.receipts))for(let s of t.receipts)for(let a of ke(s,r))o.add(a);let i=!1;try{let s=BigInt(await n.readContract({address:f.positionManager,abi:v,functionName:"balanceOf",args:[r]})),a=s>64n?64n:s;for(let u=0n;u<a;u++){try{let c=BigInt(await n.readContract({address:f.positionManager,abi:v,functionName:"tokenOfOwnerByIndex",args:[r,u]}));c>0n&&o.add(c.toString())}catch(c){if(!j(c,3,-32601,-32004))throw c;break}u+1n===s&&(i=!0)}s===0n&&(i=!0)}catch(s){if(!j(s,3,-32601,-32004))throw s}if(typeof n.getLogs=="function"&&typeof n.getBlockNumber=="function")try{let s=t.toBlock??await n.getBlockNumber(),a=t.maxChunks??Ne,u=t.fromBlock??(s>Q*BigInt(a)?s-Q*BigInt(a)+1n:0n),c=s,p=0;for(;c>=u&&p<a;){let w=c>=Q-1n?c-(Q-1n):0n,l=w<u?u:w,y=await n.getLogs({address:f.positionManager,fromBlock:l,toBlock:c});for(let h of ke({logs:y},r))o.add(h);if(p+=1,l===0n||l<=u)break;c=l-1n}}catch(s){throw new d(`Could not discover Uniswap v3 positions from logs. ${S(s)}`)}else if(!i&&t.tokenIds===void 0&&t.receipts===void 0)throw new d("Uniswap v3 position discovery is unavailable; supply candidate token IDs or receipts.");return[...o].map(s=>BigInt(s)).sort((s,a)=>s<a?-1:s>a?1:0)}async function Ae(n,e,t={}){_(e);let r=m(e),o=z(n),i=await ze(o,r,t),s=[];for(let a of i){let u;try{let b=await o.readContract({address:f.positionManager,abi:v,functionName:"ownerOf",args:[a]});u=m(String(b))}catch(b){if(j(b,3))continue;throw new d(`Could not verify owner of position #${a}. ${S(b)}`)}if(u!==r)continue;let c;try{c=await ne(o,a)}catch(b){throw new d(`Could not read position #${a}. ${S(b)}`)}if(c.liquidity===0n&&c.tokensOwed0===0n&&c.tokensOwed1===0n&&!t.includeEmpty)continue;let w=await U(o,c.token0,g),l=await U(o,c.token1,g),y=0n,h=0n;if(c.liquidity>0n)try{let b=await o.readContract({address:f.factory,abi:ve,functionName:"getPool",args:[c.token0,c.token1,c.fee]}),k=m(String(b));if(k===Y)throw new d("Position pool was not found.");if(k!==Y){let x=await o.readContract({address:k,abi:Ee,functionName:"slot0"}),P=BigInt(x[0]);if(P<=0n)throw new d("Position pool has no initialized price.");let D=he(c.tickLower),q=he(c.tickUpper),$=He(P,D,q,c.liquidity);y=$.amount0,h=$.amount1}}catch(b){throw new d(`Could not value Uniswap v3 position #${a}. ${S(b)}`)}let T=y+c.tokensOwed0,N=h+c.tokensOwed1,A=[{token:w,amount:T.toString()},{token:l,amount:N.toString()}];s.push({module:"uniswap",id:`uniswap:v3:${a.toString()}`,chainId:g,assets:A,description:`Uniswap v3 LP position #${a.toString()} (${w.symbol}/${l.symbol} fee ${c.fee} ticks [${c.tickLower}, ${c.tickUpper}] liquidity ${c.liquidity.toString()})`})}return s}async function je(n,e,t){z(n,e);let r=e.wallet!==void 0?R(e.wallet,"wallet"):m(t),o=Array.isArray(e.tokenIds)?e.tokenIds:void 0,i=Array.isArray(e.receipts)?e.receipts:void 0,s=e.includeEmpty===!0,a=await Ae(n,r,{tokenIds:o,receipts:i,includeEmpty:s});return{positions:a,details:{version:"v3",wallet:r,count:a.length,positionManager:f.positionManager}}}function Ke(n){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},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:K},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},wrapNative:{type:"boolean",description:"Optional: wrap native ETH into WETH before minting."}}},execute:(i,s)=>Fe(n,i,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:(i,s)=>Ge(n,i,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:K},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},burn:{type:"boolean",description:"Whether to burn the NFT after removing 100% of liquidity."}},required:["tokenId"]},execute:(i,s)=>Xe(n,i,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:(i,s)=>je(n,i,s)}]}var te=n=>({tools:Ke(n),positions:e=>Ae(n,e)}),rn=te,sn=te,an=te,dn=te;export{ce as a,ue as b,O as c,f as d,$e as e,tn as f,v as g,ve as h,Ee as i,_e as j,Be as k,De as l,Ve as m,ke as n,on as o,Fe as p,Ge as q,Xe as r,Ae as s,je as t,Ke as u,te as v,rn as w,sn as x,an as y,dn as z};
@@ -1 +0,0 @@
1
- import{b as qe,o as se}from"./VBV366XQ.js";import{a as P}from"./S3YSJ7XH.js";import{a as Ae}from"./VZWOWR6G.js";import{a as q,i as ge}from"./25EOXUBI.js";import{a as be}from"./B5RZYFQC.js";import{a as t}from"./T5E4OJEU.js";import{decodeFunctionData as Re,erc20Abi as Ce,isAddress as Se,parseAbi as Pe}from"viem";var Ee="https://api.relay.link",T="0x0000000000000000000000000000000000000000",Oe=60,$e=30,Be=Pe(["function depositNative(address depositor, bytes32 id) payable"]),n=ge[q].relay.depository.address.toLowerCase(),Y="0x59916da825d2d2ec1bf878d71c88826f6633ecca",_e=new Map([[1,{chainId:"ethereum",depository:n}],[10,{chainId:"optimism",depository:n}],[25,{chainId:"cronos",depository:Y}],[56,{chainId:"bnb",depository:n}],[100,{chainId:"gnosis",depository:n}],[130,{chainId:"unichain",depository:n}],[137,{chainId:"polygon",depository:n}],[143,{chainId:"monad",depository:n}],[146,{chainId:"sonic",depository:n}],[169,{chainId:"manta",depository:n}],[196,{chainId:"xlayer",depository:n}],[288,{chainId:"boba",depository:n}],[324,{chainId:"zksync",depository:n}],[360,{chainId:"shape",depository:n}],[480,{chainId:"worldchain",depository:n}],[747,{chainId:"flow",depository:n}],[988,{chainId:"stable",depository:n}],[999,{chainId:"hyperevm",depository:n}],[1088,{chainId:"metis",depository:Y}],[1135,{chainId:"lisk",depository:n}],[1868,{chainId:"soneium",depository:n}],[2020,{chainId:"ronin",depository:n}],[2741,{chainId:"abstract",depository:n}],[2818,{chainId:"morph",depository:n}],[4217,{chainId:"tempo",depository:n}],[4326,{chainId:"megaeth",depository:n}],[5e3,{chainId:"mantle",depository:Y}],[5031,{chainId:"somnia",depository:n}],[5042,{chainId:"arc",depository:n}],[8453,{chainId:"base",depository:n}],[9745,{chainId:"plasma",depository:n}],[33139,{chainId:"apechain",depository:n}],[34443,{chainId:"mode",depository:n}],[42018,{chainId:"mythos",depository:n}],[42161,{chainId:"arbitrum",depository:n}],[42220,{chainId:"celo",depository:n}],[43114,{chainId:"avalanche",depository:n}],[48900,{chainId:"zircuit",depository:n}],[57073,{chainId:"ink",depository:n}],[59144,{chainId:"linea",depository:Y}],[60808,{chainId:"bob",depository:n}],[80094,{chainId:"berachain",depository:n}],[97477,{chainId:"doma",depository:n}],[98866,{chainId:"plume",depository:n}],[534352,{chainId:"scroll",depository:n}],[685689,{chainId:"gensyn",depository:n}],[747474,{chainId:"katana",depository:n}],[5064014,{chainId:"ethereal",depository:n}],[7777777,{chainId:"zora",depository:n}]]),ae={type:"string",pattern:"^[0-9]+$"},J={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"};function s(e){if(!e||typeof e!="object"||Array.isArray(e))throw new t("Relay returned an unexpected response.");return e}function E(e){if(typeof e!="string"||!Se(e,{strict:!1}))throw new t("Provide a token or wallet address.");return e.toLowerCase()}function I(e){let o=E(e);return o===P?T:o}function w(e,o){return E(e)===E(o)}function l(e){if(typeof e!="string")throw new t("Provide a decimal base-unit amount string.");return be(e),e}function X(e){let o=l(e);if(BigInt(o)<=0n)throw new t("Provide a positive base-unit amount.");return o}function Me(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new t("Provide a positive integer origin chain ID.");return e}function ke(e,o){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new t(`${o} is missing or invalid.`);return e}async function z(e,o,c,i,p){let a=s(c);if(a.chainId!==i||I(a.address)!==p||typeof a.symbol!="string"||!/^[A-Za-z0-9._-]{1,32}$/.test(a.symbol))throw new t("Relay quote token metadata does not match the requested chain and address.");if(p===T){if(a.decimals!==18)throw new t("Native token decimals must be 18.");return{address:P,chainId:i,symbol:a.symbol,decimals:18}}let g=`${i}:${p}`,m=o.get(g);if(m===void 0){let d=await e.clientFor(i).readContract({address:p,abi:Ce,functionName:"decimals"}),f=typeof d=="bigint"?Number(d):d;if(typeof f!="number"||!Number.isInteger(f)||f<0||f>255)throw new t("Could not read valid ERC-20 decimals() on-chain.");m=f,o.set(g,m)}return{address:p,chainId:i,symbol:a.symbol,decimals:m}}async function Fe(e,o,c,i,p,a,g){if(c.swap===void 0)return[];let m=s(c.swap),d=s(m.from);if(d.chainId!==p)throw new t("The swap prerequisite token must be on the origin chain.");let f=await z(e,o,d,p,I(d.address)),O=a===T?P:a;if(w(f.address,O))throw new t("The swap prerequisite must use a different input token.");let de=X(m.amountIn),y=m.slippageBps;if(y!==void 0&&(typeof y!="number"||!Number.isInteger(y)||y<0||y>1e4))throw new t("Provide swap slippage in basis points from 0 to 10000.");let v=await e.quoteSwap({from:f.address,to:O,amountIn:de,...y===void 0?{}:{slippageBps:y}},i);if(BigInt(l(v.expiresAt))<=BigInt(Math.floor(Date.now()/1e3)))throw new t("The swap prerequisite quote expired. Request a fresh quote.");if(BigInt(l(v.minAmountOut))<BigInt(g))throw new t("The swap prerequisite minimum cannot cover the bridge amount.");let R=await e.buildSwap(v.quoteId,i);if(!("txs"in R)||!R.txs.length)throw new t("The swap prerequisite must return unsigned transactions.");if(R.txs.some(x=>x.chainId!==p))throw new t("The injected swap coordinator does not support this origin chain.");return R.txs.map(x=>e.unsignedTx(x))}async function je(e,o,c){Ae(c);let i=Me(o.originChainId);if(i===q)throw new t("Inbound bridging requires an origin chain other than 4663.");let p=_e.get(i);if(!p)throw new t("Relay inbound does not support this origin chain.");if(o.destinationChainId!==void 0&&o.destinationChainId!==q)throw new t("Inbound bridge destination must be chain 4663.");let a=I(o.originCurrency??P),g=I(o.destinationCurrency??P),m=E(o.recipient??c),d=X(o.amount),f=o.minAmountOut===void 0?void 0:l(o.minAmountOut),O=o.slippageBps===void 0?qe:o.slippageBps;if(se("0",O),await e.clientFor(i).getChainId()!==i)throw new t("The RPC chain does not match the inbound origin chain.");let y=new Map,v=await Fe(e,y,o,c,i,a,d),R,x=process.env.OAK_RELAY_API_KEY?.trim();try{let r=await e.http(`${Ee}/quote/v2`,{method:"POST",headers:{"content-type":"application/json","user-agent":"oak-core/0.1.0",...x?{"x-api-key":x}:{}},body:JSON.stringify({user:c,recipient:m,originChainId:i,destinationChainId:q,originCurrency:a,destinationCurrency:g,amount:d,tradeType:"EXACT_INPUT"})});if(!r.ok)throw new Error("Relay HTTP failure.");R=await r.json()}catch{throw new t("Relay quote request failed. Please try again.")}let b=s(R);if(typeof b.requestId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(b.requestId))throw new t("Relay returned an invalid request ID.");let D=b.requestId,ue=`/intents/status/v3?requestId=${D}`,B=s(b.details);if(!w(B.sender,c)||!w(B.recipient,m))throw new t("Relay quote sender or recipient does not match the request.");let ce=s(B.currencyIn),Z=s(B.currencyOut),ee=await z(e,y,ce.currency,i,a),N=await z(e,y,Z.currency,q,g);if(l(ce.amount)!==d)throw new t("Relay quote input amount does not match the request.");let _=X(Z.amount),S=X(Z.minimumAmount);if(BigInt(S)>BigInt(_))throw new t("Relay quote minimum output exceeds the expected output.");if(f!==void 0){if(S!==f)throw new t("Relay order minimum must exactly match minAmountOut. Request a new quote.")}else{let r=se(_,O);if(BigInt(S)<BigInt(r))throw new t("Relay order minimum is below the allowed slippage minimum. Request a new quote.")}let pe=s(s(b.fees).relayer),me=s(pe.currency),H=await z(e,y,me,i,I(me.address)),he={token:H,amount:l(pe.amount)},ye=s(B.refundCurrency),Te=s(ye.currency),M=await z(e,y,Te,i,a),te=l(ye.amount),F=s(s(b.protocol).v2);if(typeof F.orderId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(F.orderId))throw new t("Relay returned an invalid order ID.");let K=F.orderId.toLowerCase(),G=s(F.paymentDetails),j=E(G.depository);if(G.chainId!==p.chainId||j!==p.depository||I(G.currency)!==a||l(G.amount)!==d)throw new t("Relay payment details do not match the origin chain depository and input.");let V=s(F.orderData),$=s(V.output);if($.chainId!=="robinhood"||!Array.isArray($.calls)||$.calls.length!==0||!Array.isArray($.payments)||$.payments.length!==1)throw new t("Relay order output does not match destination chain 4663.");let Q=s($.payments[0]);if(!w(Q.recipient,m)||I(Q.currency)!==g||l(Q.minimumAmount)!==S||l(Q.expectedAmount)!==_)throw new t("Relay order output payment does not match the quoted recipient and amounts.");let ne=ke($.deadline,"Relay order output deadline");if(!Array.isArray(V.inputs)||!V.inputs.length)throw new t("Relay order has no inputs.");let W=[],oe=[];for(let r of V.inputs){let u=s(r),k=s(u.payment);if(k.chainId!==p.chainId||I(k.currency)!==a||l(k.amount)!==d||!Array.isArray(u.refunds)||!u.refunds.length)throw new t("Relay order input does not match the quoted input.");for(let C of u.refunds){let h=s(C);if(!w(h.recipient,c))throw new t("Relay refund recipient does not match the agent wallet. Request a new quote.");if(W.push(ke(h.deadline,"Relay order refund deadline")),oe.push(l(h.minimumAmount)),!(h.chainId===p.chainId?w(h.recipient,c)&&I(h.currency)===a:h.chainId==="robinhood"&&I(h.currency)===g))throw new t("Relay order refund terms do not match the sender or recipient.")}}let le=Math.min(ne,...W),L=0,fe=()=>{let r=Math.floor(Date.now()/1e3),u=L||r+Oe;if(le-r<=$e)throw new t("Relay order deadline is expired or too soon to sign safely. Request a new quote.");if(L=Math.min(u,le-$e),L<=r)throw new t("Relay quote expired before signing. Request a new quote.")};if(fe(),!Array.isArray(b.steps)||!b.steps.length)throw new t("Relay returned no origin transactions.");let A=[];for(let r of b.steps){let u=s(r);if(u.kind!=="transaction"||u.requestId!==D||!Array.isArray(u.items)||!u.items.length)throw new t("Relay returned an unsupported origin step.");for(let k of u.items){let C=s(k),h=s(C.data),re=s(C.check);if(C.status!=="incomplete"||h.chainId!==i||!w(h.from,c))throw new t("Relay transaction does not match the origin chain and sender.");if(re.method!=="GET"||re.endpoint!==ue)throw new t("Relay status endpoint does not match the request ID.");A.push(e.unsignedTx({to:E(h.to),data:h.data,value:l(h.value),chainId:i,description:`Relay inbound deposit for request ${D}; destination chain 4663.`}))}}if(!A.length)throw new t("Relay returned no origin transactions.");if(a===T&&A.length!==1)throw new t("Relay native deposit must be a single depositNative transaction.");if(a!==T&&A.length>2)throw new t("Relay ERC-20 deposit allows at most one exact-amount approval before depositNative.");for(let r of A.slice(0,-1)){if(!r.data.toLowerCase().startsWith("0x095ea7b3"))throw new t("Relay returned an unsupported prerequisite transaction.");let u=Re({abi:Ce,data:r.data});if(u.functionName!=="approve")throw new t("Relay returned an invalid approval.");let[k,C]=u.args;if(a===T||!w(r.to,a)||!w(k,j)||C!==BigInt(d)||r.value!=="0")throw new t("Relay approval must authorize the exact input amount for the origin depository.");r.description=`Approve exactly ${e.formatAmount(d,ee.decimals)} ${ee.symbol} (${d} base units of ${a}) for ${j} on chain ${i}.`}let U=A[A.length-1],ve=a===T?d:"0";if(!w(U.to,j)||U.value!==ve||!/^0x[0-9a-fA-F]{136}$/.test(U.data))throw new t("Relay deposit transaction does not target the origin depository with depositNative calldata.");let ie;try{ie=Re({abi:Be,data:U.data})}catch{throw new t("Relay deposit transaction must call depositNative(address,bytes32).")}if(ie.functionName!=="depositNative")throw new t("Relay deposit transaction must call depositNative(address,bytes32).");let[xe,De]=ie.args;if(!w(xe,c)||De.toLowerCase()!==K)throw new t("Relay depositNative depositor or orderId does not match the wallet and quoted protocol.v2.orderId.");U.description=`Relay inbound depositNative for order ${K} (request ${D}); destination chain 4663.`;let we=[...v,...A],Ie=await e.preview(we,c);fe();let Ne=Ie.changes.map(r=>{let u=r.amount.startsWith("-");return`${u?"-":""}${e.formatAmount(u?r.amount.slice(1):r.amount,r.token.decimals)} ${r.token.symbol} (${r.token.address}, chain ${r.token.chainId})`});return{txs:we,preview:Ie,requestId:D,orderId:K,depository:j,originChainId:i,destinationChainId:q,recipient:m,amountIn:{token:ee,amount:d},amountOut:{token:N,amount:_},minAmountOut:S,relayerFee:he,refundCurrency:{token:M,amount:te,minimumAmounts:oe},orderDeadline:String(ne),refundDeadlines:W.map(String),expiresAt:String(L),status:"pending",statusEndpoint:ue,summary:`${v.length?"Swap prerequisite first, then ":""}Relay inbound from chain ${i} to chain 4663 for ${m}; expected ${e.formatAmount(_,N.decimals)} ${N.symbol}, minimum ${e.formatAmount(S,N.decimals)} ${N.symbol} (${N.address}). Quoted relay fee ${e.formatAmount(he.amount,H.decimals)} ${H.symbol} (${H.address}, chain ${i}); output is net of quoted fees. Order ${K} (request ${D}); output deadline ${ne}, refund deadlines ${W.join(", ")}, quote expires ${L}. Refund terms: details.refundCurrency quotes ${e.formatAmount(te,M.decimals)} ${M.symbol} (${te} base units) on chain ${M.chainId} (${M.address}), but protocol.v2 order refund floor is ${oe.join(", ")} base units. ${Ne.join("; ")}. Unsigned origin transactions only; destination fulfillment remains pending. Track with relay_status; timeout or refund is not fulfillment.`}}var Qe=e=>({tools:[{name:"relay_bridge_in",inputSchema:{type:"object",additionalProperties:!1,required:["originChainId","amount"],properties:{originChainId:{type:"integer",minimum:1},destinationChainId:{const:q},originCurrency:J,destinationCurrency:J,amount:ae,minAmountOut:ae,slippageBps:{type:"integer",minimum:0,maximum:9999},recipient:J,swap:{type:"object",additionalProperties:!1,required:["from","amountIn"],properties:{from:{type:"object",additionalProperties:!1,required:["address","chainId","symbol","decimals"],properties:{address:J,chainId:{type:"integer",minimum:1},symbol:{type:"string"},decimals:{type:"integer",minimum:0,maximum:255}}},amountIn:ae,slippageBps:{type:"integer",minimum:0,maximum:1e4}}}}},async execute(o,c){try{return await je(e,o,c)}catch(i){throw new t(e.plainError(i))}}}]});export{Qe as a};
@@ -1 +0,0 @@
1
- import{c as b}from"./25EOXUBI.js";import{a as T}from"./B5RZYFQC.js";import{a as o}from"./T5E4OJEU.js";import{decodeAbiParameters as N,parseAbiParameters as B}from"viem";var L="12333333",Y="9000000",$="20000000000000000000",Q="300000000000000000000",j=["100000000000000000000000","500000000000000000000000","1000000000000000000000000","10000000000000000000000000"],v=1800,q=(1n<<256n)-1n,m=10n**18n,W=10n**30n,U=1n<<192n,E=20n*m,P=75n*m,_=100n*m,I=300n*m,k=100000n*m,w=500000n*m,p=1000000n*m,y=10000000n*m;function e(t){let n=typeof t=="bigint"?t:T(t);if(n<0n||n>q)throw new o("Amount must be within the uint256 range.");return n}function h(t){if(typeof t=="bigint")return t;if(typeof t=="number"){if(!Number.isSafeInteger(t))throw new o("Integer parameter must be a safe integer.");return BigInt(t)}if(typeof t!="string"||!/^-?\d+$/.test(t))throw new o("Value must be a signed integer decimal string.");return BigInt(t)}function x(t){let n=typeof t=="number"?t:typeof t=="string"&&/^\d+$/.test(t)?Number(t):NaN;if(!Number.isInteger(n)||n<0||n>77)throw new o("Token decimals must be an integer from 0 to 77.");return n}function O(t){return 10n**BigInt(t)}function A(t,n="Result"){if(t<0n||t>q)throw new o(`${n} exceeds uint256 bounds.`);return t}function f(t,n,i="Factor"){return A(t*n,i)}function g(t,n,i,c="floor"){if(i<=0n)throw new o("The denominator must be positive.");let r=t*n;if(r===0n)return 0n;let s=c==="ceil"?r/i+(r%i===0n?0n:1n):r/i;return A(s,"Math.mulDiv result")}function z(t){let n=e(t);return n<k?E.toString():n<w?(E+g(n-k,P-E,w-k)).toString():n<p?(P+g(n-w,_-P,p-w)).toString():n<y?(_+g(n-p,I-_,y-p)).toString():I.toString()}function G(t){let n=e(t);return A(9000000n+n/1000000000000n/6n,"noHoldPriceBase").toString()}function J(t){let n=e(t),i=n/4n,c=n-i;return{burn:i.toString(),treasury:c.toString()}}function R(t){let n=e(t);return g(n,5n,100n,"ceil").toString()}function Z(t){let n=e(t);return(n-BigInt(R(n))).toString()}function tt(t,n){let i=e(t),c=e(n);if(c<=0n)throw new o("OAK-per-ETH price must be positive.");return g(i,m,c,"floor").toString()}function nt(t,n,i=b){let c=e(t),r=e(n);if(r<=0n)throw new o("OAK USD price must be positive.");let s=O(x(i));return g(c,s,r,"ceil").toString()}function it(t,n,i=b){let c=e(t),r=e(n),s=O(x(i));return g(c,r,s,"floor").toString()}function et(t,n,i,c=b){let r=x(c);if(r<6)throw new o("OAK decimals must be at least 6 for burner conversion.");let s=e(t),u=e(n),a=e(i);if(a<=0n)throw new o("ETH USD price must be positive.");let d=O(r-6),l=f(s,d,"burnerMinOut usdgIn * decimalScale"),D=f(u,49n,"burnerMinOut oakPerEthE18 * 49"),S=f(a,51n,"burnerMinOut ethUsdE18 * 51");return g(l,D,S,"floor").toString()}function rt(t,n,i=v){let c=h(t),r=h(n),s=h(i);if(s<=0n)throw new o("Observation window seconds must be positive.");let u=r-c,d=u/s-(u<0n&&u%s!==0n?1n:0n);return Number(d)}function ot(t,n){if(!t||typeof n!="string"||!/^0x[0-9a-fA-F]*$/.test(n))throw new o("Oracle observe call failed or returned invalid hex.");if(n==="0x"||n.length<258)throw new o("Oracle observe return data is empty or too short.");try{let[i]=N(B("int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s"),n);if(!Array.isArray(i)||i.length<2)throw new o("Oracle observe did not return two tick cumulatives.");return[i[0].toString(),i[1].toString()]}catch(i){throw i instanceof o?i:new o("Oracle observe return data could not be decoded.")}}function ct(t){let n=e(t);if(n<=0n)throw new o("sqrtRatioX96 must be positive.");let i=f(n,n,"sqrtRatioX96 squared");return g(i,W,U,"floor").toString()}function X(t){let n=e(t);if(n<=0n)throw new o("sqrtPriceX96 must be positive.");let i=f(n,n,"sqrtPriceX96 squared");return g(i,m,U,"floor").toString()}function C(t){let n="ethAmountWei"in t&&t.ethAmountWei!==void 0?t.ethAmountWei:"ethVolumeWei"in t?t.ethVolumeWei:void 0;if(n===void 0)throw new o("SwapTrade must provide ethAmountWei.");let i=h(n),c=i<0n?-i:i;if(c<=0n)throw new o("SwapTrade ETH volume must be positive.");let r;t.sqrtPriceX96!==void 0&&t.sqrtPriceX96!==""&&t.sqrtPriceX96!=="0"&&(r=BigInt(X(t.sqrtPriceX96)));let s;if(t.oakPerEthE18!==void 0&&t.oakPerEthE18!==""&&(s=e(t.oakPerEthE18)),r!==void 0&&s!==void 0&&r!==s)throw new o("SwapTrade oakPerEthE18 does not match post-swap sqrtPriceX96.");let u=r??s;if(u===void 0||u<=0n)throw new o("SwapTrade must provide a positive post-swap price.");let a=t.timestamp!==void 0&&t.timestamp!==""?e(t.timestamp):void 0;return{volumeWei:c,oakPerEth:u,timestamp:a}}function M(t,n){if(!Array.isArray(t)||t.length===0)throw new o("At least one SwapTrade is required to compute the 30-minute average.");let i=n?.windowEnd!==void 0?e(BigInt(n.windowEnd)):n?.now!==void 0?e(BigInt(n.now)):void 0,c=n?.windowStart!==void 0?e(BigInt(n.windowStart)):i!==void 0?i-BigInt(v):void 0,r=0n,s=0n;for(let u of t){let{volumeWei:a,oakPerEth:d,timestamp:l}=C(u);c!==void 0&&i!==void 0&&l!==void 0&&(l<c||l>=i)||(r+=a*d,s+=a)}if(s<=0n)throw new o("No trades with positive ETH volume fell inside the 30-minute window.");return(r/s).toString()}function st(t,n,i=v){let c=e(BigInt(n)),r=e(BigInt(i));if(r<=0n||c<r)throw new o("Invalid 30-minute observation window bounds.");let s=c-r,u=[],a=0n;for(let l of t){let{volumeWei:D,timestamp:S}=C(l);S!==void 0&&(S<s||S>=c)||(u.push(l),a+=D)}return{oakPerEthE18:M(u),tradeCount:u.length,ethVolumeWei:a.toString(),windowStart:s.toString(),windowEnd:c.toString()}}function ut(t,n){return e(t)<=e(n)}function at(t,n){return e(t)<=e(n)}export{L as a,Y as b,$ as c,Q as d,j as e,v as f,z as g,G as h,J as i,R as j,Z as k,tt as l,nt as m,it as n,et as o,rt as p,ot as q,ct as r,X as s,M as t,st as u,ut as v,at as w};
@@ -1 +0,0 @@
1
- import{a as O,b as _}from"./LIUXNOLP.js";import{a as R}from"./P7Q6MJZH.js";import{a as M,b as x}from"./VZWOWR6G.js";import{a as P,b as N,i as L,t as T}from"./25EOXUBI.js";import{a as d,b as E,c as C}from"./T5E4OJEU.js";import{decodeFunctionResult as V,encodeFunctionData as W,erc20Abi as G,getAddress as F,isAddress as j,toEventSelector as q,toHex as v,zeroAddress as J}from"viem";var p="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";function Q(e){let s=e.toLowerCase();return s===J||s===p?p:e}var X=q("Transfer(address,address,uint256)"),H="Simulation only: transfer-based token changes exclude gas and do not prove external settlement. No transaction was sent.";function b(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function y(){throw new d("The endpoint returned an unexpected simulation response.")}async function $(e,s,l,o){let r=await e.getChainId();if(r!==s)throw new d(`Preview is on chain ${s}, but the endpoint reports chain ${r}.`);let c=await O(e),t=await _(e,c);if(c.number===null||typeof c.baseFeePerGas!="bigint"||c.baseFeePerGas<0n||typeof t!="bigint"||t<c.baseFeePerGas)throw new d("Current block base fee and gas price are unavailable or inconsistent. Retry the preview.");return e.request({method:"eth_simulateV1",params:[{blockStateCalls:[{blockOverrides:{baseFeePerGas:v(c.baseFeePerGas)},calls:l.map(n=>({from:o,to:n.to,data:n.data,value:v(BigInt(n.value)),gasPrice:v(t)}))}],validation:!1,traceTransfers:!0},v(c.number)]},{retryCount:0})}function I(e,s,l,o){(!Array.isArray(e)||e.length!==1||!b(e[0])||!Array.isArray(e[0].calls)||e[0].calls.length!==s)&&y();let r=new Map;for(let[c,t]of e[0].calls.entries()){if(b(t)||y(),t.status==="0x0")throw new d(`Preview call ${c+1} on chain ${o} reverted. ${C(t.error)}`);(t.status!=="0x1"||t.error||!Array.isArray(t.logs))&&y();for(let n of t.logs){if((!b(n)||!Array.isArray(n.topics))&&y(),typeof n.topics[0]!="string"||n.topics[0].toLowerCase()!==X||n.topics.length===4)continue;(n.topics.length!==3||typeof n.address!="string"||!j(n.address,{strict:!1})||typeof n.data!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n.data)||!n.topics.slice(1).every(i=>typeof i=="string"&&/^0x0{24}[0-9a-fA-F]{40}$/.test(i)))&&y();let f=n.topics[1].slice(-40).toLowerCase(),g=n.topics[2].slice(-40).toLowerCase(),u=l.slice(2).toLowerCase(),A=BigInt(n.data),a=(g===u?A:0n)-(f===u?A:0n);if(a!==0n){let i=Q(n.address.toLowerCase());r.set(i,(r.get(i)??0n)+a)}}}return r}async function U(e,s,l,o){let r=s===P?T.mainnet:s===N?T.testnet:void 0,c=r&&[{address:r.usdg,symbol:"USDG",decimals:6},{address:r.weth,symbol:"WETH",decimals:18},...s===P?[{address:L[4663].meridian.CollateralToken_USDe.address,symbol:"USDe",decimals:18}]:[]].find(n=>n.address.toLowerCase()===e);if(c)return{...c,address:F(e),chainId:s};let t;if(e===p){let n=l.chain?.nativeCurrency??(s===4663?{symbol:"ETH",decimals:18}:void 0);if(!n)throw new d(`Native token metadata is unavailable for chain ${s}.`);t={address:e,chainId:s,symbol:n.symbol,decimals:n.decimals}}else if(o)t=await o(e,s,l);else{let n=await R(l,s,e,"decimals");t={address:e,chainId:s,symbol:e,decimals:n}}if(!t||typeof t.address!="string"||t.address.toLowerCase()!==e||t.chainId!==s||typeof t.symbol!="string"||!t.symbol.trim()||!Number.isInteger(t.decimals)||t.decimals<0||t.decimals>255)throw new d(`Invalid token metadata for ${e} on chain ${s}.`);return{address:e===p?e:F(e),chainId:s,symbol:e===p?t.symbol:F(e),decimals:t.decimals}}function se(e){return async(s,l)=>{M(l);let o=s.map(x),r=o[0]?.chainId;if(r===void 0)return{txs:o,changes:[],summary:H};let c=o.find(t=>t.chainId!==r);if(c)throw new d(`Preview cannot combine chain ${r} with chain ${c.chainId}. Preview each chain separately.`);try{let t=e.clientFor(r),n;try{n=await $(t,r,o,l)}catch(a){if(!E(a,-32601,-32004)||!e.anvilFor)throw a;t=await e.anvilFor(r),n=await $(t,r,o,l)}let f=I(n,o.length,l,r),g=new Map,u=[];for(let[a,i]of f)if(i!==0n)try{g.set(a,await U(a,r,t,e.tokenFor))}catch(k){if(a===p||e.tokenFor||(await t.getCode({address:a})??"0x")!=="0x")throw k;u.push(a)}if(u.length){let a=u.flatMap(h=>["symbol","decimals"].map(m=>x({to:h,data:W({abi:G,functionName:m}),value:"0",chainId:r,description:`Read simulated token ${m}.`}))),i=await $(t,r,[...o,...a],l);(!Array.isArray(i)||i.length!==1||!b(i[0])||!Array.isArray(i[0].calls)||i[0].calls.length!==o.length+a.length)&&y();let k=i[0].calls,D=I([{calls:k.slice(0,o.length)}],o.length,l,r);if(f.size!==D.size||[...f].some(([h,m])=>D.get(h)!==m))throw new d("Simulation changed while reading new-token metadata. Refresh the preview.");for(let[h,m]of u.entries()){let S=(B,K)=>{let w=k[o.length+h*2+K];if(!b(w)||w.status!=="0x1"||w.error||typeof w.returnData!="string"||!/^0x[0-9a-fA-F]+$/.test(w.returnData))throw new d(`Invalid simulated token metadata for ${m} on chain ${r}.`);return V({abi:G,functionName:B,data:w.returnData})},z={address:m,chainId:r,symbol:S("symbol",0),decimals:S("decimals",1)};g.set(m,await U(m,r,t,async()=>z))}}let A=[...f].filter(([,a])=>a!==0n).map(([a,i])=>({token:g.get(a),amount:i.toString()}));return{txs:o,changes:A,summary:H}}catch(t){throw new d(`Preview on chain ${r} failed: ${C(t)}`)}}}export{p as a,Q as b,se as c};
@@ -1 +0,0 @@
1
- import{a as m}from"./Z25UKUJF.js";import{b as x,c as S}from"./VZWOWR6G.js";import{b as w,c as M}from"./B5RZYFQC.js";import{a as i,c as f}from"./T5E4OJEU.js";function C(t){return{...t,unsignedTx:x,approval:S,parseAmount:w,formatAmount:M,plainError:f}}function h(t,l,e){let a=new Set(l);if(!Array.isArray(t))throw new i("A module must provide a tools array.");for(let o of t){if(!o||typeof o.name!="string"||!/^[a-z][a-z0-9_]*$/.test(o.name)||e&&(!o.name.startsWith(`${e}_`)||o.name.length<=e.length+1))throw new i("A tool must have a valid name with its module prefix.");if(a.has(o.name))throw new i(`Tool ${o.name} is already registered.`);if(!o.inputSchema||typeof o.inputSchema!="object"||Array.isArray(o.inputSchema)||o.inputSchema.type!=="object"||typeof o.execute!="function")throw new i(`Tool ${o.name} must provide an object input schema and an execute function.`);a.add(o.name)}}function b(t,l,e){if(typeof t!="string"||!/^[a-z][a-z0-9]*$/.test(t))throw new i("Provide a valid module name.");let a=[],o=[];for(let n of l){if(!n||!Array.isArray(n.tools))throw new i(`Module ${t} has an invalid part.`);if(a.push(...n.tools),n.positions!==void 0){if(typeof n.positions!="function")throw new i(`Module ${t} has an invalid positions reader.`);o.push(n.positions.bind(n))}}if(h(a,new Set,t),e&&(typeof e.name!="string"||!e.name||typeof e.quote!="function"||typeof e.build!="function"))throw new i(`Module ${t} has an invalid swap provider.`);return{name:t,tools:a,...o.length?{positions:async n=>(await Promise.all(o.map(d=>d(n)))).flat()}:{},...e?{swapProvider:e}:{}}}function k(t,l,e=[]){h(e,new Set);let a=[...e],o=[],n=[],d=new Set,y=new Set(e.map(c=>c.name));for(let[c,g]of l.entries())try{let u=g(t),r=b(u.name,[u],u.swapProvider);if(d.has(r.name))throw new i(`Module ${r.name} is already registered.`);h(r.tools,y,r.name);for(let s of r.tools){let p=s.execute;s.execute=async(v,P)=>m(await p(v,P))}if(r.positions){let s=r.positions;r.positions=async p=>m(await s(p))}a.push(...r.tools),o.push(r),d.add(r.name),r.tools.forEach(s=>y.add(s.name))}catch(u){n.push({index:c,error:f(u)})}return{tools:a,modules:o,errors:n}}export{C as a,b,k as c};
@@ -1 +0,0 @@
1
- import{a as i,b as u}from"./XN4WDN3O.js";var o=class extends Error{name="OakError"};function d(e){let n=[],s=new Set;for(;e&&typeof e=="object"&&!s.has(e)&&n.length<16;){s.add(e);let a=e;n.push(a),e=a.cause}return n}function r(e,...n){return d(e).some(s=>typeof s.code=="number"&&n.includes(s.code))}function f(e){if(e instanceof o)return u(e.message)||e.message.length>1024?i(e.message):e.message;let n=d(e),s=n.find(t=>t instanceof o&&/^(?:The RPC request timed out\. Please try again\.|The RPC endpoint returned malformed JSON\.|The RPC endpoint returned HTTP [1-5]\d{2}\. Please try again\.|The RPC endpoint is busy; retry in [1-9]\d* seconds\.)$/.test(t.message));if(s)return String(s.message);if(n.some(t=>t.name==="TimeoutError"))return"The request timed out. Please try again.";if(n.some(t=>t.name==="AbortError"))return"The request was cancelled.";if(r(e,4001))return"The request was declined.";if(r(e,-32601,-32004))return"This endpoint does not support the requested operation.";let a=n.map(t=>typeof t.message=="string"?t.message:"").join(" ");return/insufficient funds for gas \* price \+ value/i.test(a)?"Insufficient funds for the simulation gas budget. Check wallet ETH and the endpoint or fork block gas limit; no transaction was sent.":/revert/i.test(a)||r(e,3)?"The contract call reverted.":/fetch failed|ECONNREFUSED|ENOTFOUND|network/i.test(a)?"The service could not be reached. Please try again.":"The request failed. Please try again."}export{o as a,r as b,f as c};
@@ -1 +0,0 @@
1
- import{b as C}from"./S3YSJ7XH.js";import{c as H}from"./64EN6Y7E.js";import{a as f,b as $,c as J}from"./VZWOWR6G.js";import{A as R,B as X,C as Y,a as b,i as V,z as U}from"./25EOXUBI.js";import{a as o,d as Z}from"./B5RZYFQC.js";import{a as r}from"./T5E4OJEU.js";import{decodeFunctionData as k,encodeFunctionData as Q,parseAbi as K}from"viem";var ce=60,j=50,ke=200,ee=K(["function buy(uint256 quoteIn,uint256 minTokensOut,address recipient) payable returns (uint256)","function sell(uint256 tokensIn,uint256 minQuoteOut,address recipient) returns (uint256)"]),le="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",W="0x0000000000000000000000000000000000000000",B=V[4663].routes.kyberswap.address,L=V[4663].routes.velora.address,te=U[4663].kyberswap.toLowerCase(),ne=U[4663].velora.toLowerCase(),me="0x0000000000000000000000000000000000000000000000000000000000000000",P=K(["function swap((address callTarget, address approveTarget, bytes targetData, (address srcToken, address dstToken, address[] srcReceivers, uint256[] srcAmounts, address[] feeReceivers, uint256[] feeAmounts, address dstReceiver, uint256 amount, uint256 minReturnAmount, uint256 flags, bytes permit) desc, bytes clientData) execution) payable returns (uint256 returnAmount, uint256 gasUsed)"]),_=K(["function swapExactAmountIn(address executor, (address srcToken, address destToken, uint256 fromAmount, uint256 toAmount, uint256 quotedAmount, bytes32 metadata, address beneficiary) swapData, uint256 partnerAndFee, bytes permit, bytes executorData) payable returns (uint256 receivedAmount, uint256 submittedAmount, uint256 augustusFeeAmount)"]),E=class extends r{name="NoRouteError";constructor(t="No swap route is available for this token pair and amount."){super(t)}},F=class extends r{name="ExpiredQuoteError";constructor(t="Quote has expired. Request a fresh quote."){super(t)}},pe=1e3,S=new Map;function oe(e){for(let[t,n]of S)BigInt(e)>=o(n.expiresAt)&&S.delete(t)}function G(e){return{...e,...e.txs?{txs:e.txs.map(t=>({...t}))}:{}}}function q(e){let t=G(e);return t.txs&&(t.txs.forEach(Object.freeze),Object.freeze(t.txs)),Object.freeze(t)}var fe=["router","from","to","wallet","amountIn","amountOut","minAmountOut","expiresAt","chainId","spender","value","ponsCurveToken","blockNumber","calldataMinAmountOut","expectedSpend","expectedRefund"];function N(e,t,n=!1){for(let i of fe)if(!(i==="expiresAt"&&n&&o(e.expiresAt)<=o(t.expiresAt))&&e[i]!==void 0&&String(e[i]).toLowerCase()!==String(t[i]).toLowerCase())throw new r(`Quote ${i} does not match the accepted quote.`)}function M(e=Date.now){let t=e();if(!Number.isFinite(t)||t<0)throw new r("Clock must return a non-negative timestamp.");return t>1e11?Math.floor(t/1e3):Math.floor(t)}function I(e){let t=e.toLowerCase();return t===le.toLowerCase()||t===W.toLowerCase()}function we(e,t=j){if(!Number.isInteger(t)||t<0||t>=1e4)throw new r("Slippage must be an integer from 0 to 9999 bps.");return Z(e,String(1e4-t),"10000","floor")}function re(e){return o(e)*10000n/9999n+1n}function ae(e){if(e.oakFee!==void 0&&o(e.oakFee)!==0n)throw new r("Oak charges 0 swap fee; venue fees must never be counted as Oak income.");let t=e.provider??"venue";return`Venue fee: ${e.venueFee} base units (${e.venueFeeBps} bps) retained by ${t}; Oak swap fee: 0 (venue fee is never Oak income).`}function Ae(e){f(e.from),f(e.to),f(e.wallet);let t=e.callTarget??R[b].kyberswap.address,n=e.approveTarget??W;f(t),f(n);let i=o(e.amountIn),a=o(e.minAmountOut);return Q({abi:P,functionName:"swap",args:[{callTarget:t,approveTarget:n,targetData:e.targetData??"0x",desc:{srcToken:e.from,dstToken:e.to,srcReceivers:I(e.from)?[]:[t],srcAmounts:I(e.from)?[]:[i],feeReceivers:[],feeAmounts:[],dstReceiver:e.wallet,amount:i,minReturnAmount:a,flags:0n,permit:"0x"},clientData:e.clientData??"0x"}]})}function ge(e){f(e.from),f(e.to),f(e.wallet);let t=e.executor??R[b].velora.address;return f(t),Q({abi:_,functionName:"swapExactAmountIn",args:[t,{srcToken:e.from,destToken:e.to,fromAmount:o(e.amountIn),toAmount:o(e.minAmountOut),quotedAmount:o(e.amountOut),metadata:e.metadata??me,beneficiary:e.wallet},e.partnerAndFee??0n,"0x",e.executorData??"0x"]})}function ve(e){if(typeof e!="string"||!/^0x([0-9a-fA-F]{2})+$/.test(e)||e.length<10)throw new r("Swap calldata must contain a 4-byte function selector.");let t=e.slice(0,10).toLowerCase();if(t===te)return k({abi:P,data:e}).args[0].desc.minReturnAmount;if(t===ne)return k({abi:_,data:e}).args[1].toAmount;let n=k({abi:ee,data:e});if(n.functionName==="buy"||n.functionName==="sell")return n.args[1];throw new r(`Unsupported swap router selector ${t}.`)}function se(e,t,n=!1){let i=o(t),a=ve(e);if(a!==i&&!(n&&a>i))throw new r(`Built swap calldata minimum output (${a}) does not match the accepted quote minimum (${i}).`);return a}function ue(e,t){let{from:n,to:i,wallet:a,amountIn:d}=t;if(!n||!i||!a||d===void 0)throw new r("Accepted quote must include input, output, amount and wallet.");for(let s of[n,i,a,t.router,e.to])f(s);let l=(s,c,A)=>{if(s.toLowerCase()!==c.toLowerCase())throw new r(`Built swap ${A} does not match the accepted quote.`)};if(l(e.to,t.router,"router"),e.chainId!==(t.chainId??b))throw new r("Built swap chain does not match the accepted quote.");let g=I(n)?o(d):0n;if(o(e.value)!==g||t.value!==void 0&&o(t.value)!==g)throw new r("Built swap value does not match the accepted quote input.");let w=e.data.slice(0,10).toLowerCase(),u=t.router.toLowerCase(),p;if(u===B.toLowerCase()&&w===te){l(t.spender??t.router,B,"spender");let s=k({abi:P,data:e.data});if(Q({abi:P,...s}).toLowerCase()!==e.data.toLowerCase())throw new r("KyberSwap calldata must be canonically decodable.");let{callTarget:c,approveTarget:A,desc:m}=s.args[0];l(c,R[b].kyberswap.address,"executor"),l(A,W,"executor approval target");let v=I(n);if(m.srcReceivers.length!==(v?0:1)||m.srcAmounts.length!==(v?0:1)||!v&&(m.srcReceivers[0].toLowerCase()!==c.toLowerCase()||m.srcAmounts[0]!==o(d)))throw new r("KyberSwap source transfers must send the exact input to the pinned executor.");if(m.feeReceivers.length||m.feeAmounts.length||m.flags!==0n&&m.flags!==512n||m.permit!=="0x")throw new r("KyberSwap fee recipients, fee amounts, flags and permit must match the pinned zero-fee policy.");p={from:m.srcToken,to:m.dstToken,wallet:m.dstReceiver,amount:m.amount}}else if(u===L.toLowerCase()&&w===ne){l(t.spender??t.router,L,"spender");let s=k({abi:_,data:e.data});if(Q({abi:_,...s}).toLowerCase()!==e.data.toLowerCase())throw new r("Velora calldata must be canonically decodable.");let[c,A,m,v]=s.args;if(!Y.some(T=>T.toLowerCase()===c.toLowerCase()))throw new r("Built swap executor does not match the accepted quote.");if(m!==0n&&(m!==X||t.venueFeeBps!==1)||v!=="0x")throw new r("Velora partnerAndFee and permit must match the pinned venue fee policy.");if(t.calldataMinAmountOut!==void 0&&o(t.calldataMinAmountOut)!==re(t.minAmountOut))throw new r("Velora calldata minimum must cover the accepted net output, venue fee and router dust.");if(t.calldataMinAmountOut!==void 0&&(A.quotedAmount!==o(t.grossAmountOut??"0")||A.quotedAmount<o(t.calldataMinAmountOut)))throw new r("Velora quoted gross output must match the accepted quote and cover its calldata minimum.");if(m!==0n&&t.calldataMinAmountOut===void 0)throw new r("Velora venue fee requires a fee-adjusted calldata minimum.");p={from:A.srcToken,to:A.destToken,wallet:A.beneficiary,amount:A.fromAmount}}else if(t.provider==="pons"&&t.ponsCurveToken){let s=k({abi:ee,data:e.data}),c=I(n);if(s.functionName!==(c?"buy":"sell")||!I(c?n:i))throw new r("Pons curve direction does not match the accepted quote.");l(c?i:n,t.ponsCurveToken,"curve token"),l(t.spender??t.router,t.router,"curve spender"),p={from:n,to:i,wallet:s.args[2],amount:s.args[0]}}else throw new r("Built swap selector does not match the accepted router.");if(l(p.from,n,"input token"),l(p.to,i,"output token"),l(p.wallet,a,"recipient"),p.amount!==o(d))throw new r("Built swap input amount does not match the accepted quote.");se(e.data,t.calldataMinAmountOut??t.minAmountOut,u===B.toLowerCase())}function z(e,t={}){if(!e||typeof e.quoteId!="string"||!e.quoteId.trim())throw new r("Quote must include a non-empty quoteId.");if(f(e.router),e.oakFee!==void 0&&o(e.oakFee)!==0n)throw new r("Oak charges 0 swap fee; venue fees must never be counted as Oak income.");let n=o(e.amountOut),i=e.destAmountAfterFee??e.netAmountOut,a,d,l;if(i!==void 0){if(d=o(i),a=e.grossAmountOut!==void 0?o(e.grossAmountOut):n>=d?n:d,a<d)throw new r("Gross output cannot be less than net output.");l=e.venueFee!==void 0?o(e.venueFee):a-d}else if(e.grossAmountOut!==void 0){if(a=o(e.grossAmountOut),d=n,a<d)throw new r("Gross output cannot be less than net output.");l=e.venueFee!==void 0?o(e.venueFee):a-d}else e.venueFee!==void 0?(l=o(e.venueFee),d=n,a=d+l):(d=n,a=n,l=0n);if(d<=0n)throw new E("Quote output amount must be positive.");let g=t.slippageBps??e.slippageBps??j,w=e.minAmountOut!==void 0?o(e.minAmountOut):o(we(d.toString(),g));if(w<=0n||w>a)throw new r("Quote minAmountOut must be positive and not exceed gross output.");if((t.provider??e.provider)==="velora"&&e.calldataMinAmountOut!==void 0){if(o(e.calldataMinAmountOut)!==re(w.toString())||o(e.calldataMinAmountOut)>a)throw new r("Velora calldata minimum must cover the accepted net output, venue fee and router dust.")}else if(e.calldataMinAmountOut!==void 0||e.ponsCurveToken!==void 0){if((t.provider??e.provider)!=="pons"||!e.ponsCurveToken)throw new r("Curve minimum requires a Pons curve quote.");f(e.ponsCurveToken);let h=o(t.amountIn??e.amountIn??"0"),x=o(e.expectedSpend??"0"),ie=o(e.expectedRefund??"0"),de=o(e.calldataMinAmountOut??"0");if(h<=0n||x<=0n||x+ie!==h||de*x/h!==w)throw new r("Pons actual minimum and refund do not match the encoded minimum.")}let u=M(t.now),p=BigInt(u+ce),s=e.expiresAt!==void 0?o(e.expiresAt):p,c=(s>p?p:s).toString(),A=l.toString(),m=e.venueFeeBps??(a>0n&&l>0n?Number((l*10000n+a/2n)/a):0),v=t.provider??e.provider??(e.router.toLowerCase()===L.toLowerCase()?"velora":"kyberswap"),T=v==="pons"&&e.feeDisclosure?e.feeDisclosure:ae({provider:v,venueFee:A,venueFeeBps:m,oakFee:"0"}),O={...e,quoteId:e.quoteId,amountOut:d.toString(),minAmountOut:w.toString(),router:e.router,expiresAt:c,provider:v,grossAmountOut:a.toString(),destAmountAfterFee:d.toString(),netAmountOut:d.toString(),venueFee:A,venueFeeBps:m,oakFee:"0",feeDisclosure:T,...t.from??e.from?{from:C(t.from??e.from)}:{},...t.to??e.to?{to:C(t.to??e.to)}:{},...t.amountIn??e.amountIn?{amountIn:t.amountIn??e.amountIn}:{},...t.wallet??e.wallet?{wallet:t.wallet??e.wallet}:{},slippageBps:g,chainId:t.chainId??e.chainId??b,spender:e.spender??e.router,...t.allowance??e.allowance?{allowance:t.allowance??e.allowance}:{}};if(BigInt(u)>=o(c))throw new F;if(t.cache===!1)return O;if(oe(u),BigInt(u)>=o(c))throw new F;let y=S.get(O.quoteId);if(y){N(O,y,!0);let h=q({...y,expiresAt:O.expiresAt});return S.set(h.quoteId,h),G(h)}for(;S.size>=pe;)S.delete(S.keys().next().value);let D=q(O);return S.set(D.quoteId,D),G(D)}async function Ee(e,t,n={}){e={...e},f(e.from),f(e.to),f(e.wallet),e.from=C(e.from),e.to=C(e.to);let i=o(e.amountIn);if(i<=0n)throw new r("Swap amountIn must be greater than zero.");let a=e.slippageBps??j;if(!Number.isInteger(a)||a<0||a>=1e4)throw new r("Slippage must be an integer from 0 to 9999 bps.");if(!Array.isArray(t)||t.length===0)throw new E;let d={from:e.from,to:e.to,amountIn:i.toString(),slippageBps:a},l=await Promise.allSettled(t.map(async u=>{let p=await(u.quotePrices??u.quote).call(u,{...d},e.wallet);return{quote:z(p,{provider:u.name,from:e.from,to:e.to,amountIn:i.toString(),wallet:e.wallet,slippageBps:a,chainId:e.chainId??b,allowance:e.allowance,now:e.now,cache:!1}),provider:u}})),g,w=[];for(let u of l)u.status==="rejected"&&(g??=H(u.reason)),u.status==="fulfilled"&&o(u.value.quote.expiresAt)>BigInt(M(e.now))&&w.push(u.value);if(w.length===0)throw g??new E;w.sort((u,p)=>{let c=o(p.quote.amountOut)-o(u.quote.amountOut)||o(p.quote.minAmountOut)-o(u.quote.minAmountOut);return c>0n?1:c<0n?-1:0});for(let{quote:u,provider:p}of w)try{if(BigInt(M(e.now))>=o(u.expiresAt))continue;if(n.deferBuild||!p.prepareQuote)return z(u,{now:e.now});let s=await p.prepareQuote(u.quoteId,e.wallet);if(s.quoteId!==u.quoteId)throw new r("Prepared quote ID does not match the selected route.");if(N(s,u,!0),!s.data)throw new r("Selected route did not return swap calldata.");let c={...u,expiresAt:s.expiresAt,data:s.data,value:s.value,allowance:s.allowance??u.allowance};return ue($({to:c.router,data:s.data,value:s.value??"0",chainId:c.chainId??b,description:"Selected swap route"}),c),z(c,{now:e.now})}catch(s){g??=H(s);continue}throw g??new E}function Te(e,t={}){if(!e||typeof e.quoteId!="string"||!e.quoteId.trim())throw new r("Provide a valid quote to build a swap.");f(e.router);let n=S.get(e.quoteId),i=M(t.now);if(oe(i),!n||BigInt(i)>=o(n.expiresAt))throw S.delete(e.quoteId),new F;if(e.oakFee!==void 0&&o(e.oakFee)!==0n)throw new r("Oak charges 0 swap fee; venue fees must never be counted as Oak income.");N(e,n),N({...n,...t},n);let a=n.from,d=n.to,l=n.amountIn,g=n.wallet;if(!a||!d||!g||l===void 0)throw new r("Accepted quote must include input, output, amount and wallet.");let w=n.chainId??b,u=n.spender??n.router,p=t.allowance??e.allowance??n?.allowance??"0";f(a),f(d),f(g),f(u);let s=o(l);if(s<=0n)throw new r("Swap amountIn must be greater than zero.");let c=o(n.minAmountOut);if(c<=0n)throw new r("Swap minAmountOut must be greater than zero.");let A=e.router.toLowerCase()===L.toLowerCase(),m=t.data??e.data??n?.data??(A?ge({from:a,to:d,amountIn:s.toString(),amountOut:n.amountOut,minAmountOut:c.toString(),wallet:g}):Ae({from:a,to:d,amountIn:s.toString(),minAmountOut:c.toString(),wallet:g}));se(m,n.calldataMinAmountOut??c.toString(),n.router.toLowerCase()===B.toLowerCase());let v=n.venueFee??"0",T=n.venueFeeBps??0,O=n.provider??(A?"velora":"kyberswap"),y=n.feeDisclosure??ae({provider:O,venueFee:v,venueFeeBps:T,oakFee:"0"}),D=I(a),h=t.value??e.value??n?.value??(D?s.toString():"0"),x=$({to:e.router,data:m,value:h,chainId:w,description:`Swap ${s} base units of ${a} for at least ${c} base units of ${d} via ${O} (${e.router}). ${y}`});return ue(x,n),D||o(p)>=s?[x]:[J(a,u,s.toString(),w),x]}export{ce as a,j as b,ke as c,ee as d,le as e,W as f,E as g,F as h,pe as i,G as j,q as k,N as l,M as m,I as n,we as o,re as p,ae as q,Ae as r,ge as s,ve as t,se as u,ue as v,z as w,Ee as x,Te as y};
@@ -1 +0,0 @@
1
- import{b as $}from"./SGDWO7XI.js";import{a as y}from"./VZWOWR6G.js";import{t as C}from"./25EOXUBI.js";import{a as d}from"./T5E4OJEU.js";import{a as M}from"./XN4WDN3O.js";import{Buffer as k}from"node:buffer";import{decodeEventLog as j,encodeFunctionData as U,parseAbi as W,toEventSelector as O}from"viem";var m=W(["function register(string agentURI) returns (uint256 agentId)","function setMetadata(uint256 agentId,string metadataKey,bytes metadataValue)","event MetadataSet(uint256 indexed agentId,string indexed indexedMetadataKey,string metadataKey,bytes metadataValue)","function setAgentURI(uint256 agentId,string newURI)","function ownerOf(uint256 agentId) view returns (address)","function tokenURI(uint256 agentId) view returns (string)","function getApproved(uint256 agentId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)","function getAgentWallet(uint256 agentId) view returns (address)","function getMetadata(uint256 agentId,string metadataKey) view returns (bytes)","event Registered(uint256 indexed agentId,string agentURI,address indexed owner)","event URIUpdated(uint256 indexed agentId,string newURI,address indexed updatedBy)"]),ae={register:"erc8004_register"};function h(e){let{chainId:t,identityRegistry:n}=C[e.network??"mainnet"];return{chainId:t,registry:n,registryId:`eip155:${t}:${n}`}}var q="https://eips.ethereum.org/EIPS/eip-8004#registration-v1",I="oak.registrar",P="0x6f616b",B="Profile contents and oak.registrar are mutable, self-asserted metadata, not registry-validated claims or proof of provenance.",H={type:"string",pattern:"^[0-9]+$",description:"Agent ID as a decimal uint256 integer string."},_={type:"object",required:["type","name","description","image","services","x402Support","active","registrations"],properties:{type:{const:q},name:{type:"string",minLength:1},description:{type:"string"},image:{type:"string"},services:{type:"array",items:{type:"object",required:["name","endpoint"]}},x402Support:{type:"boolean"},active:{type:"boolean"},registrations:{type:"array"},tags:{type:"array",items:{type:"string"}},supportedTrust:{type:"array",items:{type:"string"}}}};function A(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function f(e,t){return e.toLowerCase()===t.toLowerCase()}function v(e){if(typeof e!="string"||!/^[0-9]+$/.test(e)||e.length>78||BigInt(e)>=2n**256n)throw new d("Provide an agent ID as a decimal uint256 integer string.");return BigInt(e)}function w(e,t,n=!1){if(typeof e!="string"||!n&&!e.trim())throw new d(`Provide a valid profile ${t}.`)}function N(e,t){w(e,t);try{let n=new URL(e);if(!["https:","ipfs:"].includes(n.protocol)||!n.hostname||n.username||n.password)throw new Error}catch{throw new d(`Profile ${t} must be an HTTPS or IPFS URI without credentials.`)}}function J(e,t,n,r){let{registryId:s}=h(e);if(!A(t))throw new d("Provide a registration-v1 profile object.");if(n!==void 0&&typeof n!="boolean")throw new d("The tag option must be a boolean.");if(t.type!==q)throw new d("Use the ERC-8004 registration-v1 profile type.");if(w(t.name,"name"),w(t.description,"description",!0),N(t.image,"image"),typeof t.active!="boolean"||typeof t.x402Support!="boolean")throw new d("Profile active and x402Support must be booleans.");if(!Array.isArray(t.services)||!Array.isArray(t.registrations))throw new d("Profile services and registrations must be arrays.");for(let o of t.services){if(!A(o))throw new d("Provide valid profile services.");w(o.name,"service name"),N(o.endpoint,"service endpoint"),o.version!==void 0&&w(o.version,"service version")}for(let o of["tags","supportedTrust"])if(t[o]!==void 0&&(!Array.isArray(t[o])||!t[o].every(p=>typeof p=="string"&&p.trim())))throw new d(`Profile ${o} must be an array of nonempty strings.`);let g=t.registrations.map(o=>{if(!A(o)||typeof o.agentRegistry!="string"||!/^eip155:[1-9][0-9]*:0x[0-9a-fA-F]{40}$/.test(o.agentRegistry))throw new d("Provide a valid agentRegistry for every registration.");let p=typeof o.agentId=="number"&&Number.isSafeInteger(o.agentId)?String(o.agentId):o.agentId,l=v(p);if(f(o.agentRegistry,s)){if(r===void 0)throw new d("Do not predict a registration ID; obtain it from the mined Registered receipt.");if(l!==r)throw new d("Profile registration ID does not match the agent being updated.")}return{...o}});r!==void 0&&!g.some(o=>f(o.agentRegistry,s))&&g.push({agentId:r.toString(),agentRegistry:s});let i=[...new Set((t.tags??[]).filter(o=>o!==I))];n!==!1&&i.push(I);let c={...t,registrations:g,...i.length?{tags:i}:{}};i.length||delete c.tags;let a;try{if(a=JSON.stringify(c),k.byteLength(a)>65536)throw new Error;JSON.parse(a)}catch{throw new d("Profile must be JSON data no larger than 64 KiB.")}return`data:application/json;base64,${k.from(a,"utf8").toString("base64")}`}async function R(e,t){try{let{chainId:n,registry:r}=h(e),s=v(t),g=e.clientFor(n),i=await g.readContract({address:r,abi:m,functionName:"ownerOf",args:[s]});y(i);let[c,a,o]=await Promise.all([g.readContract({address:r,abi:m,functionName:"tokenURI",args:[s]}),g.readContract({address:r,abi:m,functionName:"getAgentWallet",args:[s]}),g.readContract({address:r,abi:m,functionName:"getMetadata",args:[s,I]})]);if(y(a),typeof c!="string"||typeof o!="string"||!/^0x([0-9a-fA-F]{2})*$/.test(o))throw new d("The registry returned invalid identity data.");return{agentId:s.toString(),chainId:n,registry:r,owner:i,uri:c,agentWallet:a,registrarMetadata:o,registryValidated:!1,summary:B}}catch(n){throw new d(e.plainError(n))}}async function ie(e,t){let n=await R(e,t);return{...n,uri:M(n.uri)}}async function E(e,t,n){let{chainId:r,registry:s}=h(e),g=e.clientFor(r),i=await g.readContract({address:s,abi:m,functionName:"ownerOf",args:[t]});if(y(i),f(i,n))return;let[c,a]=await Promise.all([g.readContract({address:s,abi:m,functionName:"getApproved",args:[t]}),g.readContract({address:s,abi:m,functionName:"isApprovedForAll",args:[i,n]})]);if(y(c),typeof a!="boolean")throw new d("The registry returned invalid operator approval data.");if(!f(c,n)&&!a)throw new d("Only the agent owner or an approved operator can update this profile.")}async function L(e,t,n,r){let{chainId:s,registry:g}=h(e);if(typeof t!="string"||!/^0x[0-9a-fA-F]{64}$/.test(t))throw new d("Provide the mined transaction hash.");let i=e.clientFor(s),c=await i.getTransactionReceipt({hash:t});if(!c)throw new d("The transaction is not mined yet. Try again after confirmation.");if(c.status!=="success"||!c.to||!f(c.to,g)||!f(c.from,n)||!f(c.transactionHash,t))throw new d("The receipt is not a successful matching registry transaction.");let a=await i.getTransaction({hash:t});if(a.chainId!==s||a.value!==0n||!a.to||!f(a.to,g)||!f(a.from,n))throw new d("The transaction does not match this chain, registry and wallet.");if(typeof a.input!="string"||!f(a.input,r))throw new d("The mined transaction calldata does not match the exact operation Oak built.");return c}async function z(e,t,n,r,s,g){let{registry:i}=h(e),c=await L(e,t,n,s),a=g===void 0?"Registered":"URIUpdated",o=O(g===void 0?"Registered(uint256,string,address)":"URIUpdated(uint256,string,address)"),p=c.logs.filter(x=>f(x.address,i)&&x.topics[0]===o&&!x.removed);if(p.length!==1)throw new d(`The receipt must contain one matching ${a} event.`);let l=p[0],u=j({abi:m,eventName:a,topics:l.topics,data:l.data,strict:!0}),b=u.args.agentId,K=u.eventName==="Registered"?u.args.agentURI:u.args.newURI,V=u.eventName==="Registered"?u.args.owner:u.args.updatedBy;if(g!==void 0&&b!==g||K!==r||!f(V,n))throw new d("The registry event does not match the expected agent, URI and wallet.");let T=await R(e,b.toString());if(T.uri!==r||g===void 0&&!f(T.owner,n))throw new d("The current agent owner or URI does not match the confirmed operation.");return T}function S(e,t){let{chainId:n,registry:r}=h(e);return e.unsignedTx({to:r,chainId:n,value:"0",data:U({abi:m,functionName:"setMetadata",args:[t,I,P]}),description:`Set mutable oak.registrar metadata to oak for agent ${t}.`})}async function G(e,t,n,r){let{registry:s}=h(e),g=v(r.agentId),i=await L(e,t,n,S(e,g).data),c=O("MetadataSet(uint256,string,string,bytes)"),a=i.logs.filter(u=>f(u.address,s)&&u.topics[0]===c&&!u.removed);if(a.length!==1)throw new d("The receipt must contain one matching MetadataSet event.");let o=a[0],{args:p}=j({abi:m,eventName:"MetadataSet",topics:o.topics,data:o.data,strict:!0});if(p.agentId!==g||p.metadataKey!==I||p.metadataValue!==P)throw new d("The metadata event does not match this agent and registrar marker.");let l=await R(e,r.agentId);if(l.registrarMetadata!==P||l.uri!==r.uri||!f(l.owner,r.owner))throw new d("The current agent metadata, owner or URI does not match the confirmed operation.");return l}async function F(e,t,n,r){let s=await e.preview(t,n),g=s.changes.map(({amount:i,token:c})=>{let a=i.startsWith("-");return`${a?"-":""}${e.formatAmount(a?i.slice(1):i,c.decimals)} ${c.symbol} (${c.address}, chain ${c.chainId})`});return{txs:t,summary:`${s.summary} ${g.join("; ")} ${B} ${r}`}}async function D(e,t,n,r){let{chainId:s,registry:g}=h(e);if(y(r),n.chainId!==void 0&&n.chainId!==s)throw new d(`ERC-8004 actions are supported only on chain ${s}.`);let i=t?v(n.agentId):void 0,c=J(e,n.profile,n.tag,i),a=n.tag!==!1;if(n.metadataTransactionHash!==void 0&&(!a||n.transactionHash===void 0))throw new d("A metadata transaction hash requires tagging and the profile transaction hash.");let o=i===void 0?U({abi:m,functionName:"register",args:[c]}):U({abi:m,functionName:"setAgentURI",args:[i,c]});if(n.transactionHash!==void 0){let l=await z(e,n.transactionHash,r,c,o,i);if(!a)return l;if(n.metadataTransactionHash!==void 0)return G(e,n.metadataTransactionHash,r,l);let u=v(l.agentId);await E(e,u,r);let b=await F(e,[S(e,u)],r,`Profile transaction confirmed for agent ${u}; onchain registrar metadata is pending. Submit this metadata transaction locally if not already submitted, then repeat the original arguments with transactionHash and metadataTransactionHash to verify both calls.`);return{...l,...b}}i!==void 0&&await E(e,i,r);let p=[e.unsignedTx({to:g,data:o,value:"0",chainId:s,description:i===void 0?"Register an ERC-8004 agent profile.":`Update ERC-8004 agent ${i} profile.`})];return i!==void 0&&a&&p.push(S(e,i)),F(e,p,r,`Submit locally, then repeat the original arguments with transactionHash to verify the profile receipt and URI.${a?i===void 0?" The mined Registered event supplies the actual agent ID; confirmation then builds a separate setMetadata transaction for oak.registrar. Both transactions require network gas.":" Submit the profile and metadata transactions in order, then supply metadataTransactionHash as well to verify the onchain oak.registrar marker. Both transactions require network gas.":" No registrar metadata transaction is built; --no-tag does not clear existing onchain metadata."}${i===void 0?" Update the profile registrations with the mined ID afterward.":""}`)}var Q=e=>{let t=(r,s,g)=>({name:r,inputSchema:s,execute:async(i,c)=>{try{let a=await g(i,c);return A(a)&&typeof a.uri=="string"?{...a,uri:M(a.uri)}:a}catch(a){throw new d(e.plainError(a))}}}),n=r=>({type:"object",additionalProperties:!1,required:r?["agentId","profile"]:["profile"],properties:{profile:_,tag:{type:"boolean",default:!0,description:"Set false for --no-tag; removes the profile tag and skips setMetadata, leaving existing onchain metadata unchanged."},transactionHash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$",description:"After local submission, verify exact calldata, event and URI; if tagged, build the metadata follow-up unless metadataTransactionHash is supplied."},metadataTransactionHash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$",description:"Hash of the separate setMetadata transaction; supplied with transactionHash to complete tagged confirmation."},...r?{agentId:H}:{}}});return{tools:[t("erc8004_register",n(!1),(r,s)=>D(e,!1,r,s)),t("erc8004_update",n(!0),(r,s)=>D(e,!0,r,s)),t("erc8004_identity",{type:"object",additionalProperties:!1,required:["agentId"],properties:{agentId:H}},r=>R(e,r.agentId))]}},oe=e=>$("erc8004",[Q(e)]);export{m as a,ae as b,ie as c,Q as d,oe as e};
@@ -1 +0,0 @@
1
- import{i as re}from"./VZPFBWVH.js";import{b as ge,o as ke}from"./VBV366XQ.js";import{a as ie}from"./S3YSJ7XH.js";import{a as S,b as be}from"./VZWOWR6G.js";import{a as l,d as Me,i as G,j as qe}from"./25EOXUBI.js";import{a as I}from"./B5RZYFQC.js";import{a as r,b as Te,c as oe}from"./T5E4OJEU.js";import{encodeAbiParameters as b,encodeFunctionData as J,erc20Abi as Ee,getAddress as y,isAddress as an,keccak256 as cn,pad as un,parseAbi as me,parseAbiParameters as U,toEventSelector as dn,toHex as De}from"viem";var Vn=y(G[4663].uniswap.v4_pool_manager.address),L=y(G[4663].uniswap.v4_position_manager.address),Xe=y(G[4663].uniswap.v4_state_view.address),xe=y(G[4663].uniswap.permit2.address),_e=y(G[4663].ponsTrade.universal_router.address),ee=y(G[4663].uniswap.WETH.address),E=y(qe),f="0x0000000000000000000000000000000000000000",je=8388608,Ie=-887272,ue=887272,ze=(1n<<48n)-1n,F=(1n<<128n)-1n,pn=(1n<<160n)-1n,ae=1n<<96n,$e=1800n,ln="0xbac3aa3b91584a53a579b3c999a56756e954e59247e497bad1d25a4334bde551",Hn={DECREASE_LIQUIDITY:1,MINT_POSITION:2,BURN_POSITION:3,SWAP_EXACT_IN_SINGLE:6,SETTLE_ALL:12,SETTLE_PAIR:13,TAKE_ALL:15,TAKE_PAIR:17,SWEEP:20},We=[{poolId:"0xbac3aa3b91584a53a579b3c999a56756e954e59247e497bad1d25a4334bde551",key:{currency0:f,currency1:E,fee:8388608,tickSpacing:10,hooks:y("0x06a889870c8f83640d6816319f72e2aa579b6080")},liquidity:"5532026605872066941",sqrtPriceX96:"3839897026469220985301794",tick:-198703,protocolFee:0,lpFee:0},{poolId:"0x387bf619da4d3fb62bb276482693dba1b9b3520f573cabdfe033384a24125982",key:{currency0:f,currency1:E,fee:500,tickSpacing:10,hooks:f},liquidity:"225820987949255613",sqrtPriceX96:"3840577772610961024680304",tick:-198700,protocolFee:512125,lpFee:500},{poolId:"0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32",key:{currency0:f,currency1:E,fee:460,tickSpacing:9,hooks:f},liquidity:"85654324417347171",sqrtPriceX96:"3840419018843648722761192",tick:-198701,protocolFee:479349,lpFee:460},{poolId:"0xc7b615a3721594f73664eb3f62d8290d0fcc8d9d1156aed1ddecbd7f32efd9f5",key:{currency0:f,currency1:E,fee:8388608,tickSpacing:10,hooks:y("0xcb787a5cdea8b3715d984d82f1203fd7bfebe0c4")},liquidity:"50517446454827887",sqrtPriceX96:"3840495145865430860317598",tick:-198700,protocolFee:0,lpFee:0},{poolId:"0x24107d152f14a76d292123265ae3f3c71f863fc2f4ef7ba49d64e78d28ea379e",key:{currency0:f,currency1:E,fee:100,tickSpacing:1,hooks:f},liquidity:"36478878201789434",sqrtPriceX96:"3840363370720475418748563",tick:-198701,protocolFee:102425,lpFee:100},{poolId:"0x84bd4e2d8be11aeb0afc1195b38f587b61e90068548f1063fdbe448fb8cad0b6",key:{currency0:ee,currency1:E,fee:200,tickSpacing:4,hooks:f},liquidity:"5980655057479791",sqrtPriceX96:"3839891926195366283625355",tick:-198703,protocolFee:213044,lpFee:200},{poolId:"0x3b0cbf0603ecc67b5fc9bb4fbb6ac9e08d3b2f406b63d1662a36063a7fe5e866",key:{currency0:f,currency1:E,fee:87,tickSpacing:1,hooks:f},liquidity:"5486760264498148",sqrtPriceX96:"3840563617639470134132117",tick:-198700,protocolFee:90134,lpFee:87}],mn=new Set(We.map(e=>e.key.hooks.toLowerCase())),fn=U("address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks"),yn=U("(address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, int24 tickLower, int24 tickUpper, uint256 liquidity, uint128 amount0Max, uint128 amount1Max, address owner, bytes hookData"),wn=U("address currency0, address currency1"),bn=U("address currency, address recipient"),he=U("uint256 tokenId, uint256 liquidity, uint128 amount0Min, uint128 amount1Min, bytes hookData"),gn=U("uint256 tokenId, uint128 amount0Min, uint128 amount1Min, bytes hookData"),ve=U("address currency0, address currency1, address recipient"),se=U("bytes actions, bytes[] params"),kn=U("((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, bool zeroForOne, uint128 amountIn, uint128 amountOutMinimum, bytes hookData)"),Ue=U("address currency, uint256 amount"),V=me(["function modifyLiquidities(bytes unlockData, uint256 deadline) payable","function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)","function getPositionLiquidity(uint256 tokenId) view returns (uint128 liquidity)","function getPoolAndPositionInfo(uint256 tokenId) view returns ((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, uint256 info)","function positionInfo(uint256 tokenId) view returns (uint256 info)","function ownerOf(uint256 tokenId) view returns (address owner)","function nextTokenId() view returns (uint256 tokenId)"]),Ge=me(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),hn=me(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),vn=me(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),An=dn("Transfer(address,address,uint256)");function de(e){if(typeof e!="string"||!an(e,{strict:!1}))throw new r("Provide a valid v4 currency address.");let n=e.toLowerCase();return n===f||n===ie.toLowerCase()?f:y(e)}function $(e){let n=e.toLowerCase();return n===f||n===ie.toLowerCase()}function pe(e){let n=de(e.currency0),o=de(e.currency1);S(e.hooks);let s=y(e.hooks);return cn(b(fn,[n,o,e.fee,e.tickSpacing,s]))}function Ze(e){return((typeof e=="number"?e:e.fee)&je)!==0}function Pn(e,n){return Ze(e)?{dynamicFee:!0,storedLpFee:n,swapsAreFree:!1,feeNote:"Pool uses dynamic fee flag 0x800000; stored lpFee=0 does not mean swaps are free. The hook determines the swap fee; a past observation is not a current quote."}:{dynamicFee:!1,storedLpFee:n,swapsAreFree:n===0,feeNote:`Static LP fee ${n} pips.`}}function le(e,n){if(!e||typeof e!="object")throw new r("Provide a valid v4 PoolKey.");let o=de(e.currency0),s=de(e.currency1);if(BigInt(o)>=BigInt(s))throw new r("PoolKey currencies must be strictly sorted (currency0 < currency1).");if(!Number.isInteger(e.tickSpacing)||e.tickSpacing<=0||e.tickSpacing>32767)throw new r("PoolKey tickSpacing must be a positive integer.");if(!Number.isInteger(e.fee)||e.fee<0||e.fee>16777215)throw new r("PoolKey fee must be a valid uint24.");S(e.hooks);let c=y(e.hooks),t=Ze(e.fee);if(t&&e.fee!==je)throw new r("Dynamic-fee PoolKey must use exact fee flag 0x800000 (8388608).");if(t&&c.toLowerCase()===f)throw new r("Dynamic-fee PoolKey requires a non-zero hook address.");if(!mn.has(c.toLowerCase()))throw new r(`Unsupported v4 hook ${c}: Oak does not assure arbitrary v4 hooks outside measured PoolKeys.`);let i={currency0:o,currency1:s,fee:e.fee,tickSpacing:e.tickSpacing,hooks:c},a=pe(i);if(n!==void 0){if(typeof n!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n))throw new r("Provide a 32-byte hex poolId.");if(a.toLowerCase()!==n.toLowerCase())throw new r(`PoolKey hash (${a}) does not match expected poolId (${n}).`)}return i}function xn(e){if(!Number.isInteger(e)||e<=0||e>ue)throw new r("tickSpacing must be a positive integer.");let n=Math.trunc(Ie/e)*e,o=Math.trunc(ue/e)*e;return{tickLower:n===0?0:n,tickUpper:o===0?0:o}}function In(e,n,o){if(!Number.isInteger(o)||o<=0)throw new r("tickSpacing must be a positive integer.");if(!Number.isInteger(e)||!Number.isInteger(n))throw new r("tickLower and tickUpper must be integers.");if(e<Ie||n>ue)throw new r(`Ticks [${e}, ${n}] are outside Uniswap bounds [${Ie}, ${ue}].`);if(e>=n)throw new r("tickLower must be strictly less than tickUpper.");if(e%o!==0||n%o!==0)throw new r(`Ticks [${e}, ${n}] must be divisible by tickSpacing ${o}.`)}function Ke(e,n,o,s,c=l){if(S(e),S(n),$(e))throw new r("Native ETH does not use Permit2 approval.");let t=I(o);if(t<=0n||t>pn)throw new r("Permit2 approval amount must be a positive integer within uint160.");let i=I(String(s));if(i<=0n||i>ze)throw new r("Permit2 expiration must be a positive timestamp within uint48.");let a=J({abi:hn,functionName:"approve",args:[e,n,t,Number(i)]});return be({to:xe,data:a,value:"0",chainId:c,description:`Approve Permit2 allowance of ${t} base units of ${e} for ${n} until ${i}.`})}function Bn(e){let n=le(e.poolKey),o=I(e.amountIn),s=I(e.amountOutMinimum),c=I(String(e.deadline));if(o<=0n||o>F)throw new r("Swap amountIn must be a positive uint128.");if(s>F)throw new r("Swap amountOutMinimum exceeds uint128.");let t=e.hookData??"0x",i=e.zeroForOne?n.currency0:n.currency1,a=e.zeroForOne?n.currency1:n.currency0,d=b(kn,[{poolKey:{currency0:n.currency0.toLowerCase(),currency1:n.currency1.toLowerCase(),fee:n.fee,tickSpacing:n.tickSpacing,hooks:n.hooks.toLowerCase()},zeroForOne:e.zeroForOne,amountIn:o,amountOutMinimum:s,hookData:t}]),u=b(Ue,[i.toLowerCase(),o]),k=b(Ue,[a.toLowerCase(),s]),p=b(se,["0x060c0f",[d,u,k]]),m=J({abi:vn,functionName:"execute",args:["0x10",[p],c]});return be({to:_e.toLowerCase(),data:m,value:$(i)?o.toString():"0",chainId:e.chainId??l,description:`Execute Uniswap v4 swap of ${o} base units on UniversalRouter (${_e}).`})}function Ne(e){return BigInt(e&16777215)}function Fe(e){let n=Number(e&0xffffffn);return(n&8388608)!==0?n-16777216:n}function On(e){if(typeof e.poolId!="string"||!/^0x[0-9a-fA-F]{50,64}$/.test(e.poolId))throw new r("Provide a valid poolId hex string.");let n=e.poolId.slice(2,52),o=BigInt(`0x${n}`)<<56n,s=Ne(e.tickUpper)<<32n,c=Ne(e.tickLower)<<8n,t=e.hasSubscriber?1n:0n;return o|s|c|t}function Sn(e){let n=(e&0xffn)!==0n,o=Fe(e>>8n&0xffffffn),s=Fe(e>>32n&0xffffffn);return{poolIdBytes25:`0x${(e>>56n&(1n<<200n)-1n).toString(16).padStart(50,"0")}`,tickLower:o,tickUpper:s,hasSubscriber:n}}function Ve(e,n,o,s=!1){let[c,t]=e<=n?[e,n]:[n,e];if(c<=0n||t<=0n)return 0n;let i=(o<<96n)*(t-c),a=t*c;return s?(i+a-1n)/a:i/a}function He(e,n,o,s=!1){let[c,t]=e<=n?[e,n]:[n,e],i=o*(t-c);return s?(i+ae-1n)/ae:i/ae}function Qe(e){if(e.liquidity<=0n)return{amount0:0n,amount1:0n};let n=re(e.tickLower),o=re(e.tickUpper);return e.sqrtPriceX96<=n?{amount0:Ve(n,o,e.liquidity,e.roundUp),amount1:0n}:e.sqrtPriceX96<o?{amount0:Ve(e.sqrtPriceX96,o,e.liquidity,e.roundUp),amount1:He(n,e.sqrtPriceX96,e.liquidity,e.roundUp)}:{amount0:0n,amount1:He(n,o,e.liquidity,e.roundUp)}}function Ln(e){let n=re(e.tickLower),o=re(e.tickUpper),s=(t,i,a)=>i<=t||a<=0n?0n:a*t*i/ae/(i-t),c=(t,i,a)=>i<=t||a<=0n?0n:a*ae/(i-t);if(e.sqrtPriceX96<=n)return s(n,o,e.amount0);if(e.sqrtPriceX96<o){let t=s(e.sqrtPriceX96,o,e.amount0),i=c(n,e.sqrtPriceX96,e.amount1);return t<i?t:i}return c(n,o,e.amount1)}function Ae(e,n){return e.map(o=>{let s=o.amount.trim(),c=s.startsWith("-"),t=c||s.startsWith("+")?s.slice(1):s,i=n(t,o.token.decimals);return`${c?"-":""}${i} ${o.token.symbol}`})}function Be(e,n=l){if($(e))return{address:ie,symbol:"ETH",decimals:18,chainId:n};let o=y(e);return o.toLowerCase()===E.toLowerCase()?{address:E,symbol:"USDG",decimals:Me,chainId:n}:o.toLowerCase()===ee.toLowerCase()?{address:ee,symbol:"WETH",decimals:18,chainId:n}:{address:o,symbol:o.slice(0,10),decimals:18,chainId:n}}async function X(e,n,o=l){if($(n))return Be(n,o);let s=y(n);if(s.toLowerCase()===E.toLowerCase()||s.toLowerCase()===ee.toLowerCase())return Be(s,o);let[c,t]=await Promise.all([e.readContract({address:s,abi:Ee,functionName:"symbol"}),e.readContract({address:s,abi:Ee,functionName:"decimals"})]);return{address:s,symbol:String(c),decimals:Number(t),chainId:o}}function Z(e,n){if(typeof e!="string"||!/^\d+$/.test(e))throw new r(`${n} must be a non-negative integer string in base units.`);return I(e)}function Oe(e,n,o,s){let c=e===void 0?I(ke(n.toString(),o)):Z(e,s);if(c<=1n||c>F)throw new r(`${s} must exceed 1 base unit and fit in uint128; the simulated amount may be too small.`);return c}async function Ye(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return BigInt(Math.floor(n>1e11?n/1e3:n));if(typeof n=="string"&&/^\d+$/.test(n.trim()))return BigInt(n.trim());try{let o=await e.request({method:"eth_getBlockByNumber",params:["latest",!1]});if(o&&typeof o.timestamp=="string")return BigInt(o.timestamp)}catch{}return BigInt(Math.floor(Date.now()/1e3))}async function Pe(e,n,o){let s=await Ye(e,o);if(n==null)return s+1800n;let c=I(String(n));if(c<=s)throw new r(`Transaction deadline ${c} has expired (current timestamp ${s}).`);return c}async function Je(e,n){let o=typeof n.poolId=="string"?n.poolId.trim():void 0,s=n.poolKey&&typeof n.poolKey=="object"&&!Array.isArray(n.poolKey)?n.poolKey:void 0,c=s?{currency0:String(s.currency0??f),currency1:String(s.currency1??E),fee:Number(s.fee),tickSpacing:Number(s.tickSpacing),hooks:String(s.hooks??f)}:n.currency0!==void 0&&n.currency1!==void 0&&n.fee!==void 0&&n.tickSpacing!==void 0?{currency0:String(n.currency0),currency1:String(n.currency1),fee:Number(n.fee),tickSpacing:Number(n.tickSpacing),hooks:String(n.hooks??f)}:void 0;if(c){if($(c.currency0)&&typeof n.token0=="string"&&n.token0.toLowerCase()===ee.toLowerCase())throw new r("Native ETH currency0 differs from WETH; do not supply WETH for a native-ETH v4 pool.");let w=le(c,o);return{poolId:pe(w),poolKey:w}}let t=(o??ln).toLowerCase(),i=We.find(w=>w.poolId.toLowerCase()===t);if(i){if($(i.key.currency0)&&typeof n.token0=="string"&&n.token0.toLowerCase()===ee.toLowerCase())throw new r("Native ETH currency0 differs from WETH; do not supply WETH for a native-ETH v4 pool.");return{poolId:i.poolId,poolKey:i.key}}let a=t.slice(0,52),d=await e.readContract({address:L,abi:V,functionName:"poolKeys",args:[a]}),[u,k,p,m,T]=d;if(u.toLowerCase()===f&&k.toLowerCase()===f&&Number(m)===0)throw new r(`Unknown or uninitialized v4 poolId ${t}.`);let v=le({currency0:u,currency1:k,fee:Number(p),tickSpacing:Number(m),hooks:T},t);return{poolId:t,poolKey:v}}async function Se(e,n,o){try{let[s,c]=await e.readContract({address:L,abi:V,functionName:"getPoolAndPositionInfo",args:[n]}),t=le({currency0:s.currency0,currency1:s.currency1,fee:Number(s.fee),tickSpacing:Number(s.tickSpacing),hooks:s.hooks});if((o.poolKey||o.poolId)&&(await Je(e,o)).poolId.toLowerCase()!==pe(t).toLowerCase())throw new r("The supplied PoolKey does not match this v4 position.");let i=Sn(BigInt(c));return{poolKey:t,poolId:pe(t),tickLower:i.tickLower,tickUpper:i.tickUpper}}catch(s){throw new r(`Could not read v4 position #${n}. ${oe(s)}`)}}async function Re(e,n,o={}){S(n);let s=y(n),c=e.clientFor(l),t=new Set;if(o.tokenIds)for(let a of o.tokenIds)t.add(I(String(a)).toString());try{let a=await c.getBlockNumber(),d=10000000n;for(let u=0n;u<=a;u+=d){let k=u+d-1n<a?u+d-1n:a,p=await c.request({method:"eth_getLogs",params:[{address:L.toLowerCase(),topics:[An,null,un(s)],fromBlock:De(u),toBlock:De(k)}]});if(!Array.isArray(p))throw new r("Invalid v4 position log response.");for(let m of p){if(!Array.isArray(m.topics)||m.topics.length!==4||!/^0x[0-9a-fA-F]{64}$/.test(m.topics[3]??""))throw new r("Invalid v4 position transfer log.");t.add(BigInt(m.topics[3]).toString())}}}catch(a){if(!o.tokenIds)throw new r(`Could not discover v4 positions. ${oe(a)}`)}let i=[];for(let a of t){let d=BigInt(a);try{let u;try{u=await c.readContract({address:L,abi:V,functionName:"ownerOf",args:[d]})}catch(P){if(Te(P,3))continue;throw P}if(u.toLowerCase()!==s.toLowerCase())continue;let k=await c.readContract({address:L,abi:V,functionName:"getPositionLiquidity",args:[d]}),p=BigInt(k);if(p===0n&&!o.includeZero)continue;let{poolKey:m,poolId:T,tickLower:v,tickUpper:w}=await Se(c,d,{}),A=await c.readContract({address:Xe,abi:Ge,functionName:"getSlot0",args:[T]}),x=BigInt(A[0]),{amount0:h,amount1:D}=Qe({liquidity:p,tickLower:v,tickUpper:w,sqrtPriceX96:x}),[g,C]=await Promise.all([X(c,m.currency0,l),X(c,m.currency1,l)]);i.push({module:"uniswap",id:`uniswap:v4:${d.toString()}`,chainId:l,assets:[{token:g,amount:h.toString()},{token:C,amount:D.toString()}],description:`Uniswap v4 LP position #${d.toString()} (${g.symbol}/${C.symbol}, liquidity=${p.toString()}, ticks=[${v},${w}], poolId=${T})`})}catch(u){throw new r(`Could not read v4 position #${d}. ${oe(u)}`)}}return i}var Cn={type:"object",properties:{version:{type:"string",enum:["v4"]},poolId:{type:"string",description:"32-byte Uniswap v4 poolId hex string."},poolKey:{type:"object",properties:{currency0:{type:"string"},currency1:{type:"string"},fee:{type:"number"},tickSpacing:{type:"number"},hooks:{type:"string"}}},currency0:{type:"string"},currency1:{type:"string"},fee:{type:"number"},tickSpacing:{type:"number"},hooks:{type:"string"},tickLower:{type:"number"},tickUpper:{type:"number"},fullRange:{type:"boolean"},liquidity:{type:"string",description:"Position liquidity in base units."},amount0Max:{type:"string",description:"Maximum currency0 base units to spend."},amount1Max:{type:"string",description:"Maximum currency1 base units to spend."},recipient:{type:"string"},deadline:{type:"string"},permit2Expiration:{type:"string"},hookData:{type:"string"}}},Tn={type:"object",properties:{version:{type:"string",enum:["v4"]},tokenId:{type:"string"},poolId:{type:"string"},poolKey:{type:"object"},amount0Min:{type:"string"},amount1Min:{type:"string"},recipient:{type:"string"},deadline:{type:"string"},hookData:{type:"string"}},required:["tokenId"]},Mn={type:"object",properties:{version:{type:"string",enum:["v4"]},tokenId:{type:"string"},liquidity:{type:"string",description:"Positive base-unit liquidity amount, or all for a full burn."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:ge},fullExit:{type:"boolean"},burn:{type:"boolean"},amount0Min:{type:"string"},amount1Min:{type:"string"},poolId:{type:"string"},poolKey:{type:"object"},recipient:{type:"string"},deadline:{type:"string"},hookData:{type:"string"}},required:["tokenId"]},qn={type:"object",properties:{version:{type:"string",enum:["v4"]},tokenIds:{type:"array",items:{type:"string"}},includeZero:{type:"boolean"}}},Le=e=>({tools:[{name:"uniswap_add",inputSchema:Cn,async execute(t,i){if(S(i),t.version!==void 0&&t.version!=="v4")throw new r('Uniswap v4 part only handles version "v4".');if(t.tokenId!==void 0)throw new r("Increasing an existing v4 position is not implemented by this mint-only tool.");if(t.amount0Min!==void 0||t.amount1Min!==void 0||t.slippageBps!==void 0)throw new r("V4 mint encodes fixed liquidity and amount0Max/amount1Max; amount minima and slippageBps are not supported for minting.");let a=e.clientFor(l),{poolId:d,poolKey:u}=await Je(a,t),k=xn(u.tickSpacing),p=t.fullRange===!0&&t.tickLower===void 0?k.tickLower:Number(t.tickLower),m=t.fullRange===!0&&t.tickUpper===void 0?k.tickUpper:Number(t.tickUpper);In(p,m,u.tickSpacing);let[T,v]=await Promise.all([X(a,u.currency0,l),X(a,u.currency1,l)]),w=Z(t.amount0Max??t.amount0Desired,"amount0Max"),A=Z(t.amount1Max??t.amount1Desired,"amount1Max");if(w<=0n&&A<=0n||w>F||A>F)throw new r("Provide positive amount0Max/amount1Max within uint128.");let x=await a.readContract({address:Xe,abi:Ge,functionName:"getSlot0",args:[d]}),h=BigInt(x[0]),D=Number(x[3]);if(h<=0n)throw new r(`Pool ${d} is not initialized on StateView.`);let g=t.liquidity!==void 0?Z(t.liquidity,"liquidity"):Ln({amount0:w,amount1:A,tickLower:p,tickUpper:m,sqrtPriceX96:h});if(g<=0n||g>F)throw new r("Position liquidity must be a positive integer within uint128.");let{amount0:C,amount1:P}=Qe({liquidity:g,tickLower:p,tickUpper:m,sqrtPriceX96:h,roundUp:!0});if(C>w||P>A)throw new r("Liquidity requires more tokens than amount0Max or amount1Max.");let M=t.recipient!==void 0?String(t.recipient):i;if(S(M),y(M)!==y(i))throw new r("Uniswap recipient must be the signing wallet.");let K=await Ye(a),Q=await Pe(a,t.deadline,K.toString()),ne=Q<K+$e?Q:K+$e,H=t.permit2Expiration===void 0?ne:I(String(t.permit2Expiration));if(H<=K||H>ne||H>ze)throw new r("Permit2 expiration must be in the next 30 minutes and no later than the transaction deadline.");let fe=typeof t.hookData=="string"?t.hookData:"0x",N=(j,z)=>{let R=[];if(!$(u.currency0)&&j>0n){let te=u.currency0.toLowerCase();R.push(e.approval(te,xe.toLowerCase(),j.toString(),l)),R.push(Ke(te,L.toLowerCase(),j.toString(),H.toString(),l))}if(!$(u.currency1)&&z>0n){let te=u.currency1.toLowerCase();R.push(e.approval(te,xe.toLowerCase(),z.toString(),l)),R.push(Ke(te,L.toLowerCase(),z.toString(),H.toString(),l))}let W={currency0:u.currency0.toLowerCase(),currency1:u.currency1.toLowerCase(),fee:u.fee,tickSpacing:u.tickSpacing,hooks:u.hooks.toLowerCase()},we=b(yn,[W,p,m,g,j,z,M.toLowerCase(),fe]),nn=b(wn,[W.currency0,W.currency1]),tn=b(bn,[f,M.toLowerCase()]),on=b(se,["0x020d14",[we,nn,tn]]),rn=J({abi:V,functionName:"modifyLiquidities",args:[on,Q]}),sn=$(u.currency0)?j.toString():"0";return R.push(e.unsignedTx({to:L.toLowerCase(),data:rn,value:sn,chainId:l,description:`Mint Uniswap v4 position on pool ${d} (ticks [${p}, ${m}], liquidity ${g}).`})),R},Y=N(C,P),B=await e.preview(Y,i),O=(j,z)=>{let R=$(z)?ie:z.toLowerCase();return-j.changes.filter(W=>W.token.address.toLowerCase()===R).reduce((W,we)=>W+BigInt(we.amount),0n)},q=O(B,u.currency0),_=O(B,u.currency1);if(q<0n||_<0n||q>C||_>P||q===0n&&_===0n)throw new r("Invalid simulated v4 mint spend. Refresh the liquidity preview.");let Ce=N(q,_),ce=q===C&&_===P?B:await e.preview(Ce,i);if(O(ce,u.currency0)!==q||O(ce,u.currency1)!==_)throw new r("V4 mint spend changed. Refresh the liquidity preview.");let en=Ae(ce.changes,e.formatAmount),ye=Pn(u,D);return{txs:Ce,preview:ce,poolId:d,poolKey:u,tickLower:p,tickUpper:m,liquidity:g.toString(),amount0Max:{token:T,amount:w.toString()},amount1Max:{token:v,amount:A.toString()},dynamicFee:ye.dynamicFee,swapsAreFree:ye.swapsAreFree,summary:`Add Uniswap v4 liquidity (${g} L, ticks [${p}, ${m}]) on pool ${d}. Preview deltas: ${en.join(", ")||"none"}. ${ye.feeNote}`}}},{name:"uniswap_collect",inputSchema:Tn,async execute(t,i){if(S(i),t.version!==void 0&&t.version!=="v4")throw new r('Uniswap v4 part only handles version "v4".');let a=I(String(t.tokenId??""));if(a<=0n)throw new r("Provide a positive v4 position tokenId.");let d=e.clientFor(l),u=t.recipient!==void 0?String(t.recipient):i;if(S(u),y(u)!==y(i))throw new r("Uniswap recipient must be the signing wallet.");let k=await Pe(d,t.deadline,t.now),p=t.amount0Min!==void 0?Z(t.amount0Min,"amount0Min"):0n,m=t.amount1Min!==void 0?Z(t.amount1Min,"amount1Min"):0n;if(p>F||m>F)throw new r("amount0Min and amount1Min must fit in uint128.");let T=typeof t.hookData=="string"?t.hookData:"0x",{poolKey:v,poolId:w}=await Se(d,a,t),[A,x]=await Promise.all([X(d,v.currency0,l),X(d,v.currency1,l)]),h=b(he,[a,0n,p,m,T]),D=b(ve,[v.currency0.toLowerCase(),v.currency1.toLowerCase(),u.toLowerCase()]),g=b(se,["0x0111",[h,D]]),C=J({abi:V,functionName:"modifyLiquidities",args:[g,k]}),P=[e.unsignedTx({to:L.toLowerCase(),data:C,value:"0",chainId:l,description:`Collect Uniswap v4 fees from position #${a} to ${u}.`})],M=await e.preview(P,i),K=Ae(M.changes,e.formatAmount);return{txs:P,preview:M,tokenId:a.toString(),poolId:w,recipient:u,currencies:[A,x],summary:`Collect Uniswap v4 fees for position #${a} (actions 0x0111). Preview deltas: ${K.join(", ")||"0"}.`}}},{name:"uniswap_remove",inputSchema:Mn,async execute(t,i){if(S(i),t.version!==void 0&&t.version!=="v4")throw new r('Uniswap v4 part only handles version "v4".');let a=I(String(t.tokenId??""));if(a<=0n)throw new r("Provide a positive v4 position tokenId.");let d=e.clientFor(l),u=t.recipient!==void 0?String(t.recipient):i;if(S(u),y(u)!==y(i))throw new r("Uniswap recipient must be the signing wallet.");let k=await Pe(d,t.deadline,t.now),{poolKey:p,poolId:m}=await Se(d,a,t),[T,v]=await Promise.all([X(d,p.currency0,l),X(d,p.currency1,l)]),w=t.slippageBps??ge;if(typeof w!="number")throw new r("Slippage must be an integer from 0 to 9999 bps.");ke("0",w);let A=typeof t.hookData=="string"?t.hookData:"0x",x=t.fullExit===!0||t.burn===!0||t.liquidity==="all";if(!x&&t.liquidity===void 0)throw new r('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let h=t.liquidity===void 0||t.liquidity==="all"?void 0:Z(t.liquidity,"liquidity");if(h!==void 0&&(h<=0n||h>F))throw new r("Provide positive liquidity within uint128 for v4 removal.");let D;try{D=BigInt(await d.readContract({address:L,abi:V,functionName:"getPositionLiquidity",args:[a]}))}catch(N){throw new r(`Could not read v4 position liquidity. ${oe(N)}`)}if(D<=0n||h!==void 0&&h>D)throw new r("Removal requires a nonempty position and cannot exceed its liquidity.");if(x&&h!==void 0&&h!==D)throw new r("A full burn must match the position liquidity; omit the amount when explicitly choosing all.");let g=x?"0x0311":"0x0111",C=(N,Y,B)=>{let O=x?b(gn,[a,N,Y,A]):b(he,[a,h,N,Y,A]),q=b(ve,[p.currency0,p.currency1,B]);return e.unsignedTx({to:L.toLowerCase(),data:J({abi:V,functionName:"modifyLiquidities",args:[b(se,[g,[O,q]]),k]}),value:"0",chainId:l,description:`${x?"Burn and exit":"Decrease"} Uniswap v4 position #${a} (${g}).`})},P=0n,M=0n;if(t.amount0Min===void 0||t.amount1Min===void 0){let N=e.unsignedTx({to:L.toLowerCase(),data:J({abi:V,functionName:"modifyLiquidities",args:[b(se,["0x0111",[b(he,[a,0n,0n,0n,A]),b(ve,[p.currency0,p.currency1,L])]]),k]}),value:"0",chainId:l,description:"Simulation only: separate fees from removal principal."}),Y=await e.preview([N,C(2n,2n,i)],i),B=O=>Y.changes.reduce((q,_)=>_.token.chainId===l&&_.token.address.toLowerCase()===O.address.toLowerCase()?q+BigInt(_.amount):q,0n);if(P=B(T),M=B(v),P<0n||M<0n)throw new r("Removal simulation did not return the expected currencies.")}let K=Oe(t.amount0Min,P,w,"amount0Min"),Q=Oe(t.amount1Min,M,w,"amount1Min"),ne=[C(K,Q,u)],H=await e.preview(ne,i),fe=Ae(H.changes,e.formatAmount);return{txs:ne,preview:H,action:g,tokenId:a.toString(),poolId:m,amount0Min:{token:T,amount:K.toString()},amount1Min:{token:v,amount:Q.toString()},summary:`${x?"Full exit":"Partial remove"} Uniswap v4 position #${a} (${g}). Preview deltas: ${fe.join(", ")||"none"}.`}}},{name:"uniswap_list_positions",inputSchema:qn,async execute(t,i){if(S(i),t.version!==void 0&&t.version!=="v4")throw new r('Uniswap v4 part only handles version "v4".');let a=Array.isArray(t.tokenIds)?t.tokenIds:void 0,d=t.includeZero===!0,u=await Re(e,i,{tokenIds:a,includeZero:d});return{version:"v4",positions:u,summary:`Found ${u.length} active Uniswap v4 position(s) for ${i}.`}}}],positions:t=>Re(e,t)}),Rn=Le,Xn=Le,jn=Le;export{Vn as a,L as b,Xe as c,xe as d,_e as e,ee as f,E as g,f as h,je as i,Ie as j,ue as k,ln as l,Hn as m,We as n,$ as o,pe as p,Ze as q,Pn as r,le as s,xn as t,In as u,Ke as v,Bn as w,On as x,Sn as y,Qe as z,Ln as A,Ae as B,Be as C,Re as D,Cn as E,Tn as F,Mn as G,qn as H,Le as I,Rn as J,Xn as K,jn as L};