@oakagentkit/core 0.1.1 → 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 (125) hide show
  1. package/build/dist/api/addresses.js +1 -1
  2. package/build/dist/api/amounts.js +1 -1
  3. package/build/dist/api/args.d.ts +19 -0
  4. package/build/dist/api/args.js +1 -0
  5. package/build/dist/api/canonical.js +1 -1
  6. package/build/dist/api/chain.js +1 -1
  7. package/build/dist/api/errors.js +1 -1
  8. package/build/dist/api/gas.js +1 -1
  9. package/build/dist/api/grandfather.js +1 -1
  10. package/build/dist/api/history.js +1 -1
  11. package/build/dist/api/http.js +1 -1
  12. package/build/dist/api/identity-link.js +1 -1
  13. package/build/dist/api/merkle.js +1 -1
  14. package/build/dist/api/metadata.js +1 -1
  15. package/build/dist/api/module.js +1 -1
  16. package/build/dist/api/modules/beefy/index.js +1 -1
  17. package/build/dist/api/modules/clanker/index.js +1 -1
  18. package/build/dist/api/modules/erc8004/index.js +1 -1
  19. package/build/dist/api/modules/grove/index.js +1 -1
  20. package/build/dist/api/modules/heyresearch/index.js +1 -1
  21. package/build/dist/api/modules/hoodag/index.js +1 -1
  22. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  23. package/build/dist/api/modules/hoodlock/index.js +1 -1
  24. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  25. package/build/dist/api/modules/hookr/create-cancel.d.ts +2 -2
  26. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  27. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  28. package/build/dist/api/modules/hookr/index.js +1 -1
  29. package/build/dist/api/modules/kyberswap/index.js +1 -1
  30. package/build/dist/api/modules/lighter/index.js +1 -1
  31. package/build/dist/api/modules/longbow/index.d.ts +4 -2
  32. package/build/dist/api/modules/longbow/index.js +1 -1
  33. package/build/dist/api/modules/meridian/index.js +1 -1
  34. package/build/dist/api/modules/meridian/markets.js +1 -1
  35. package/build/dist/api/modules/meridian/rfq.js +1 -1
  36. package/build/dist/api/modules/merkl/index.js +1 -1
  37. package/build/dist/api/modules/morpho/index.d.ts +1 -1
  38. package/build/dist/api/modules/morpho/index.js +2 -2
  39. package/build/dist/api/modules/netnet/index.js +1 -1
  40. package/build/dist/api/modules/orbio/index.js +1 -1
  41. package/build/dist/api/modules/pons/claim.js +1 -1
  42. package/build/dist/api/modules/pons/index.js +1 -1
  43. package/build/dist/api/modules/pons/launch-status.js +1 -1
  44. package/build/dist/api/modules/pons/prices.js +1 -1
  45. package/build/dist/api/modules/pons/trade.d.ts +3 -1
  46. package/build/dist/api/modules/pons/trade.js +1 -1
  47. package/build/dist/api/modules/poolstrade/index.js +1 -1
  48. package/build/dist/api/modules/priors/index.js +1 -1
  49. package/build/dist/api/modules/relay/inbound.js +1 -1
  50. package/build/dist/api/modules/relay/index.js +1 -1
  51. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  52. package/build/dist/api/modules/spark/index.js +1 -1
  53. package/build/dist/api/modules/steakhouse/index.js +1 -1
  54. package/build/dist/api/modules/tickerspring/index.js +1 -1
  55. package/build/dist/api/modules/uniswap/index.js +1 -1
  56. package/build/dist/api/modules/uniswap/v3.js +1 -1
  57. package/build/dist/api/modules/uniswap/v4.js +1 -1
  58. package/build/dist/api/modules/velora/index.js +1 -1
  59. package/build/dist/api/positions.js +1 -1
  60. package/build/dist/api/pricenote.js +1 -1
  61. package/build/dist/api/prices.js +1 -1
  62. package/build/dist/api/pricing.d.ts +5 -1
  63. package/build/dist/api/pricing.js +1 -1
  64. package/build/dist/api/routes.js +1 -1
  65. package/build/dist/api/secret-fields.js +1 -1
  66. package/build/dist/api/send.d.ts +45 -0
  67. package/build/dist/api/send.js +1 -0
  68. package/build/dist/api/simulate.js +1 -1
  69. package/build/dist/api/swap.d.ts +1 -0
  70. package/build/dist/api/swap.js +1 -1
  71. package/build/dist/api/tokens.js +1 -1
  72. package/build/dist/api/tool-policy.d.ts +1 -0
  73. package/build/dist/api/tool-policy.js +1 -1
  74. package/build/dist/api/tx.js +1 -1
  75. package/build/dist/api/types.d.ts +10 -0
  76. package/build/dist/api/untrusted.js +1 -1
  77. package/build/dist/api/vendor-limits.js +1 -1
  78. package/build/dist/chunks/2IRORNOH.js +1 -0
  79. package/build/dist/chunks/{F3TOOLFQ.js → 3PA2XT75.js} +1 -1
  80. package/build/dist/chunks/52TGAWSI.js +1 -0
  81. package/build/dist/chunks/{5B3UVWMV.js → 66DWJWDA.js} +1 -1
  82. package/build/dist/chunks/{PQHU5A3U.js → 6SYTB6FB.js} +1 -1
  83. package/build/dist/chunks/{NNJLMS7F.js → 73EABRFC.js} +1 -1
  84. package/build/dist/chunks/{VBWJOG3N.js → A5ITAEUQ.js} +1 -1
  85. package/build/dist/chunks/A5KSG6LW.js +1 -0
  86. package/build/dist/chunks/{XTUXR43N.js → B4FOHEBE.js} +1 -1
  87. package/build/dist/chunks/{XAB4OIE3.js → B4MLWDPM.js} +1 -1
  88. package/build/dist/chunks/{B2LA6VVF.js → BHR46XNW.js} +1 -1
  89. package/build/dist/chunks/{6YQ2RX5I.js → BOFA26WU.js} +1 -1
  90. package/build/dist/chunks/{A5O3SRHY.js → CQNZWL7F.js} +1 -1
  91. package/build/dist/chunks/{Z53DADZ4.js → GDP4JSAX.js} +1 -1
  92. package/build/dist/chunks/{MEZH7RPA.js → GIBF3YJO.js} +1 -1
  93. package/build/dist/chunks/GN4QZ4JA.js +1 -0
  94. package/build/dist/chunks/{7I6TXFXR.js → I5CQ64EU.js} +1 -1
  95. package/build/dist/chunks/ICCJ3TOO.js +1 -0
  96. package/build/dist/chunks/{XN4WDN3O.js → JXOEJPJ4.js} +1 -1
  97. package/build/dist/chunks/{M643PYHO.js → KL5YE7JA.js} +1 -1
  98. package/build/dist/chunks/KVVTKM6E.js +1 -0
  99. package/build/dist/chunks/{R5CBH2CR.js → M6JGTQRY.js} +1 -1
  100. package/build/dist/chunks/{TU3KHOZK.js → MK6L6TGI.js} +1 -1
  101. package/build/dist/chunks/{SXBGOGYQ.js → MOVRI5IV.js} +1 -1
  102. package/build/dist/chunks/NA7HV7BR.js +1 -0
  103. package/build/dist/chunks/{Z3FZWNAJ.js → NGAI6GTU.js} +1 -1
  104. package/build/dist/chunks/{Y2SGXWFM.js → OBX7IZG5.js} +1 -1
  105. package/build/dist/chunks/{WFE3NXBF.js → OSQ4AAM2.js} +1 -1
  106. package/build/dist/chunks/{SUQ6PIAV.js → OWEUVFB6.js} +1 -1
  107. package/build/dist/chunks/{T4IYMYZD.js → P4G3EKF7.js} +1 -1
  108. package/build/dist/chunks/{TFYLOWFO.js → QGDHMVPE.js} +1 -1
  109. package/build/dist/chunks/{RYOVSHKO.js → SJ7HDRI4.js} +1 -1
  110. package/build/dist/chunks/{ZZLHDHOT.js → SPAKOCR7.js} +1 -1
  111. package/build/dist/chunks/T6O2L6HF.js +1 -0
  112. package/build/dist/chunks/{5SH3C7XP.js → TEVKPJV5.js} +1 -1
  113. package/build/dist/chunks/UCMNB2UP.js +1 -0
  114. package/build/dist/chunks/{74X7PXPR.js → Y3P6SUNL.js} +1 -1
  115. package/build/dist/chunks/YX4NVVSX.js +1 -0
  116. package/build/dist/chunks/{5BP72XOA.js → ZUC6ILK2.js} +1 -1
  117. package/package.json +2 -2
  118. package/build/dist/chunks/CWQ5WXZQ.js +0 -1
  119. package/build/dist/chunks/GOIVHR4B.js +0 -1
  120. package/build/dist/chunks/NDHEJGWR.js +0 -1
  121. package/build/dist/chunks/UB5U6SI2.js +0 -1
  122. package/build/dist/chunks/UIJWIFGV.js +0 -1
  123. package/build/dist/chunks/XEN45QST.js +0 -1
  124. package/build/dist/chunks/XKZOMGC3.js +0 -1
  125. package/build/dist/chunks/ZJUNO5N7.js +0 -1
@@ -1 +0,0 @@
1
- import{b as ae,o as F}from"./XEN45QST.js";import{a as h,i as re,j as K}from"./5BP72XOA.js";import{a as O}from"./Z3FZWNAJ.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:[],hashes:[u],status:"mined",summary:`Mined: ${u}. Status: mined. Meridian ${l.side} filled by the external relayer. 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 m}from"./Z25UKUJF.js";import{b as x,c as S}from"./VBWJOG3N.js";import{b as w,c as M}from"./7I6TXFXR.js";import{a as i,d as f}from"./Z3FZWNAJ.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{b as ae,o as K}from"./XEN45QST.js";import{a as G}from"./Z53DADZ4.js";import{b as re}from"./UB5U6SI2.js";import{a as T,i as se}from"./5BP72XOA.js";import{a as oe}from"./XAB4OIE3.js";import{a as ie}from"./7I6TXFXR.js";import{a}from"./Z3FZWNAJ.js";import{decodeErrorResult as ye,decodeEventLog as X,encodeAbiParameters as S,encodeFunctionData as $,erc20Abi as ge,getAddress as we,isAddress as be,parseAbi as fe,parseAbiParameters as C,toHex as ce,zeroAddress as k}from"viem";var m=se[T].poolsTrade,E=m.liquidityLauncher.address,H=m.uerc20BeneficiaryVault.address,z=m.universalRouter.address,W=10n**27n,L=(1n<<128n)-1n,de=`0x${"00".repeat(32)}`,Te=63127652n,J=10000000n,xe={address:G,symbol:"ETH",decimals:18,chainId:T},h=fe(["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=fe(["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 ue(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,_=y===0?m.feeSplitterFeesOn.address:m.feeSplitterFeesOff.address;if(!p(U,_)||!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 O=o.logs.filter(x=>p(x.address,m.v4PositionManager.address)).flatMap(x=>{if(x.topics[0]!=="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")return[];let B=X({abi:D,eventName:"Transfer",data:x.data,topics:[...x.topics]}).args;return p(B.from,k)&&p(B.to,M[y])?[B.tokenId]:[]});if(O.length!==1)throw new a("The launch receipt must identify one matching position mint.");c.push({token:g,poolId:q,positionId:O[0].toString(),creatorFees:y===0})}return c}function A(o){if(typeof o!="string"||!be(o,{strict:!1}))throw new a("Provide a valid wallet or token address.");return we(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 Ae(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??ae;if(typeof y!="number")throw new a("Slippage must be an integer in basis points.");let F=K(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 ke=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=[S(C("((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"),[[d,s,i,r,0n,"0x"]]),S(C("address,uint256"),[s?k:e,i]),S(C("address,address,uint256"),[s?e:k,n,0n])],l=[S(C("bytes,bytes[]"),["0x060c0e",u])];return{inputs:l,encoded:S(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,gas:ce(oe),to:u.to,data:u.data,value:ce(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=ye({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 _(e,s){let i=await c.getBlockNumber(),r=new Map,n=new Set;for(let t=Te;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 O(e){let i=(e.launchTx!==void 0?[await c.getTransactionReceipt({hash:Ae(e.launchTx)})]:(await _(void 0,e.token===void 0?void 0:A(e.token))).receipts).flatMap(ue).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),G))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=S(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],le=[$({abi:h,functionName:"createToken",args:[m.uerc20Factory.address,r,n,18,W,E,b]}),$({abi:h,functionName:"distributeToken",args:[u,{strategy:N,amount:W,configData:S(C("address"),[i])},de]})],pe=await q(),ee=me=>{let ne=[...le];if(t>0n){let he=S(C("(address,address,bytes)"),[[z,s,I(u,!0,t,me,s,pe).encoded]]);ne.push($({abi:h,functionName:"distributeWithNative",args:[m.universalRouterStrategyApp.address,he,de,t]}))}return f(E,$({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 B(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 O(e);let t=await q(),d=[];i||(await c.readContract({address:n,abi:ge,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,$({abi:h,functionName:"approve",args:[n,z,r,Number(t)]}),0n,`Permit the exact ${r} token base units until ${t}.`)));let u=N=>[...d,f(z,$({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 O(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,$({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,$({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 j(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.");K("10000",n.slippageBps)}return await F(),await r(n,t)}catch(d){y(d)}}}}return{tools:[j("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=>j(e,{token:w,amountIn:v,minAmountOut:v,launchTx:w},["token","amountIn"],(s,i)=>B(s,i,e==="buy"))),j("collect",{positionId:v,launchTx:w},["positionId"],(e,s)=>Y(e,s,!1)),j("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 _(e),r=[];for(let n of s)for(let t of ue(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:xe,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 He(o){return re("poolstrade",[ke(o)])}export{ue as a,ke as b,He as c};
@@ -1 +0,0 @@
1
- import{b as y}from"./Z53DADZ4.js";import{c as H}from"./74X7PXPR.js";import{a as f,b as U,c as ee}from"./VBWJOG3N.js";import{A as R,B as Z,C as J,a as b,i as V,z as $}from"./5BP72XOA.js";import{a as o,d as q}from"./7I6TXFXR.js";import{a as r}from"./Z3FZWNAJ.js";import{decodeFunctionData as E,encodeFunctionData as L,parseAbi as K}from"viem";var le=60,j=50,Fe=200,ne=K(["function buy(uint256 quoteIn,uint256 minTokensOut,address recipient) payable returns (uint256)","function sell(uint256 tokensIn,uint256 minQuoteOut,address recipient) returns (uint256)"]),me="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",W="0x0000000000000000000000000000000000000000",B=V[4663].routes.kyberswap.address,Q=V[4663].routes.velora.address,X=$[4663].kyberswap.toLowerCase(),oe=$[4663].velora.toLowerCase(),pe="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)"]),k=class extends r{name="NoRouteError";constructor(t="No swap route is available for this token pair and amount."){super(t)}},C=class extends r{name="ExpiredQuoteError";constructor(t="Quote has expired. Request a fresh quote."){super(t)}},fe=1e3,h=new Map;function re(e){for(let[t,n]of h)BigInt(e)>=o(n.expiresAt)&&h.delete(t)}function G(e){return{...e,...e.txs?{txs:e.txs.map(t=>({...t}))}:{}}}function te(e){let t=G(e);return t.txs&&(t.txs.forEach(Object.freeze),Object.freeze(t.txs)),Object.freeze(t)}var we=["router","from","to","wallet","amountIn","amountOut","minAmountOut","expiresAt","chainId","spender","value","ponsCurveToken","blockNumber","calldataMinAmountOut","expectedSpend","expectedRefund"];function N(e,t,n=!1){for(let s of we)if(!(s==="expiresAt"&&n&&o(e.expiresAt)<=o(t.expiresAt))&&e[s]!==void 0&&String(e[s]).toLowerCase()!==String(t[s]).toLowerCase())throw new r(`Quote ${s} 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===me.toLowerCase()||t===W.toLowerCase()}function Ae(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 q(e,String(1e4-t),"10000","floor")}var ge=200;function ye(e){if(typeof e!="number"||!Number.isFinite(e)||!/^\d+(?:\.\d{1,2})?$/.test(String(e)))throw new r("Velora returned an unsupported venue fee. Request a fresh quote.");let[t,n=""]=String(e).split("."),s=Number(t)*100+Number(n.padEnd(2,"0"));return Y(s),s}function Y(e){if(!Number.isInteger(e)||e<0||e>ge)throw new r("Velora returned an unsupported venue fee. Request a fresh quote.")}function ae(e,t=1){return Y(t),o(e)*10000n/BigInt(1e4-t)+1n}function ve(e,t){Y(t);let n=e>>96n,s=Z>>96n,a=0x3fffn,d=1n<<92n,l=e&(1n<<96n)-1n;if(n!==s&&!(n===0n&&t===0)||(l&a)!==BigInt(t)||(l&~(d|a))!==0n)throw new r("Velora partnerAndFee must match the accepted venue fee and recipient.")}function se(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 he(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 s=o(e.amountIn),a=o(e.minAmountOut);return L({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)?[]:[s],feeReceivers:[],feeAmounts:[],dstReceiver:e.wallet,amount:s,minReturnAmount:a,flags:0n,permit:"0x"},clientData:e.clientData??"0x"}]})}function Se(e){f(e.from),f(e.to),f(e.wallet);let t=e.executor??R[b].velora.address;return f(t),L({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??pe,beneficiary:e.wallet},e.partnerAndFee??0n,"0x",e.executorData??"0x"]})}function be(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===X)return E({abi:P,data:e}).args[0].desc.minReturnAmount;if(t===oe)return E({abi:_,data:e}).args[1].toAmount;let n=E({abi:ne,data:e});if(n.functionName==="buy"||n.functionName==="sell")return n.args[1];throw new r(`Unsupported swap router selector ${t}.`)}function ue(e,t,n=!1){let s=o(t),a=be(e);if(a<=0n||s<=0n||a!==s&&!(n&&(a>s||e.slice(0,10).toLowerCase()===X&&a+1n===s)))throw new r(`Built swap calldata minimum output (${a}) does not match the accepted quote minimum (${s}).`);return a}function ie(e,t){let{from:n,to:s,wallet:a,amountIn:d}=t;if(!n||!s||!a||d===void 0)throw new r("Accepted quote must include input, output, amount and wallet.");for(let u of[n,s,a,t.router,e.to])f(u);let l=(u,c,A)=>{if(u.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(),i=t.router.toLowerCase(),p;if(i===B.toLowerCase()&&w===X){l(t.spender??t.router,B,"spender");let u=E({abi:P,data:e.data});if(L({abi:P,...u}).toLowerCase()!==e.data.toLowerCase())throw new r("KyberSwap calldata must be canonically decodable.");let{callTarget:c,approveTarget:A,desc:m}=u.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(i===Q.toLowerCase()&&w===oe){l(t.spender??t.router,Q,"spender");let u=E({abi:_,data:e.data});if(L({abi:_,...u}).toLowerCase()!==e.data.toLowerCase())throw new r("Velora calldata must be canonically decodable.");let[c,A,m,v]=u.args;if(!J.some(T=>T.toLowerCase()===c.toLowerCase()))throw new r("Built swap executor does not match the accepted quote.");if(v!=="0x")throw new r("Velora permit must match the pinned empty-permit policy.");if((t.calldataMinAmountOut!==void 0||m!==0n)&&ve(m,t.venueFeeBps??0),t.calldataMinAmountOut!==void 0&&o(t.calldataMinAmountOut)!==ae(t.minAmountOut,t.venueFeeBps??1))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 u=E({abi:ne,data:e.data}),c=I(n);if(u.functionName!==(c?"buy":"sell")||!I(c?n:s))throw new r("Pons curve direction does not match the accepted quote.");l(c?s:n,t.ponsCurveToken,"curve token"),l(t.spender??t.router,t.router,"curve spender"),p={from:n,to:s,wallet:u.args[2],amount:u.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,s,"output token"),l(p.wallet,a,"recipient"),p.amount!==o(d))throw new r("Built swap input amount does not match the accepted quote.");ue(e.data,t.calldataMinAmountOut??t.minAmountOut,i===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),s=e.destAmountAfterFee??e.netAmountOut,a,d,l;if(s!==void 0){if(d=o(s),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 k("Quote output amount must be positive.");let g=t.slippageBps??e.slippageBps??j,w=e.minAmountOut!==void 0?o(e.minAmountOut):o(Ae(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)!==ae(w.toString(),e.venueFeeBps??1)||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 S=o(t.amountIn??e.amountIn??"0"),x=o(e.expectedSpend??"0"),de=o(e.expectedRefund??"0"),ce=o(e.calldataMinAmountOut??"0");if(S<=0n||x<=0n||x+de!==S||ce*x/S!==w)throw new r("Pons actual minimum and refund do not match the encoded minimum.")}let i=M(t.now),p=BigInt(i+le),u=e.expiresAt!==void 0?o(e.expiresAt):p,c=(u>p?p:u).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()===Q.toLowerCase()?"velora":"kyberswap"),T=v==="pons"&&e.feeDisclosure?e.feeDisclosure:se({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:y(t.from??e.from)}:{},...t.to??e.to?{to:y(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(i)>=o(c))throw new C;if(t.cache===!1)return O;if(re(i),BigInt(i)>=o(c))throw new C;let F=h.get(O.quoteId);if(F){N(O,F,!0);let S=te({...F,expiresAt:O.expiresAt});return h.set(S.quoteId,S),G(S)}for(;h.size>=fe;)h.delete(h.keys().next().value);let D=te(O);return h.set(D.quoteId,D),G(D)}async function Ce(e,t,n={}){e={...e},f(e.from),f(e.to),f(e.wallet),e.from=y(e.from),e.to=y(e.to);let s=o(e.amountIn);if(s<=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 k;let d={from:e.from,to:e.to,amountIn:s.toString(),slippageBps:a},l=await Promise.allSettled(t.map(async i=>{let p=await(i.quotePrices??i.quote).call(i,{...d},e.wallet);return{quote:z(p,{provider:i.name,from:e.from,to:e.to,amountIn:s.toString(),wallet:e.wallet,slippageBps:a,chainId:e.chainId??b,allowance:e.allowance,now:e.now,cache:!1}),provider:i}})),g,w=[];for(let i of l)i.status==="rejected"&&(g??=H(i.reason)),i.status==="fulfilled"&&o(i.value.quote.expiresAt)>BigInt(M(e.now))&&w.push(i.value);if(w.length===0)throw g??new k;w.sort((i,p)=>{let c=o(p.quote.amountOut)-o(i.quote.amountOut)||o(p.quote.minAmountOut)-o(i.quote.minAmountOut);return c>0n?1:c<0n?-1:0});for(let{quote:i,provider:p}of w)try{if(BigInt(M(e.now))>=o(i.expiresAt))continue;if(n.deferBuild||!p.prepareQuote)return z(i,{now:e.now});let u=await p.prepareQuote(i.quoteId,e.wallet);if(u.quoteId!==i.quoteId)throw new r("Prepared quote ID does not match the selected route.");if(N(u,i,!0),!u.data)throw new r("Selected route did not return swap calldata.");let c={...i,expiresAt:u.expiresAt,data:u.data,value:u.value,allowance:u.allowance??i.allowance};return ie(U({to:c.router,data:u.data,value:u.value??"0",chainId:c.chainId??b,description:"Selected swap route"}),c),z(c,{now:e.now})}catch(u){g??=H(u);continue}throw g??new k}function Re(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=h.get(e.quoteId),s=M(t.now);if(re(s),!n||BigInt(s)>=o(n.expiresAt))throw h.delete(e.quoteId),new C;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,i=n.spender??n.router,p=t.allowance??e.allowance??n?.allowance??"0";f(a),f(d),f(g),f(i);let u=o(l);if(u<=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()===Q.toLowerCase(),m=t.data??e.data??n?.data??(A?Se({from:a,to:d,amountIn:u.toString(),amountOut:n.amountOut,minAmountOut:c.toString(),wallet:g}):he({from:a,to:d,amountIn:u.toString(),minAmountOut:c.toString(),wallet:g}));ue(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"),F=n.feeDisclosure??se({provider:O,venueFee:v,venueFeeBps:T,oakFee:"0"}),D=I(a),S=t.value??e.value??n?.value??(D?u.toString():"0"),x=U({to:e.router,data:m,value:S,chainId:w,description:`Swap ${u} base units of ${a} for at least ${c} base units of ${d} via ${O} (${e.router}). ${F}`});return ie(x,n),D||o(p)>=u?[x]:[ee(a,i,u.toString(),w),x]}export{le as a,j as b,Fe as c,ne as d,me as e,W as f,k as g,C as h,fe as i,G as j,te as k,N as l,M as m,I as n,Ae as o,ge as p,ye as q,ae as r,ve as s,se as t,he as u,Se as v,be as w,ue as x,ie as y,z,Ce as A,Re as B};
@@ -1 +0,0 @@
1
- import{c as b}from"./5BP72XOA.js";import{a as T}from"./7I6TXFXR.js";import{a as o}from"./Z3FZWNAJ.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{b as K,o as de}from"./XEN45QST.js";import{a as E,b as ae}from"./VBWJOG3N.js";import{a as g,i as M}from"./5BP72XOA.js";import{a as ke}from"./XAB4OIE3.js";import{a as _,c as be}from"./7I6TXFXR.js";import{a as d,b as j,d as S}from"./Z3FZWNAJ.js";import{decodeFunctionResult as ve,encodeFunctionData as L,getAddress as m,parseAbi as G,zeroAddress as Y}from"viem";var ce=-887272,ue=887272,O=(1n<<128n)-1n,Ce="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Le="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",Ne="0x3067048beee31b25b2f1681f88dac838c8bba36af25bfb2b7cf7473a5847e35f",Q=2000n,qe=5,$e=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}),rn=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"]),Ie=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)"]),Oe=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)"]),Re="0xd0e30db0";function Be(n){if(typeof n!="string")return!1;let e=n.trim().toLowerCase();return e===Y||e===Ce||e==="eth"||e==="native"}function R(n,e){if(Be(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 E(n),m(n)}function De(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 Ve(n,e){let t=n.trim(),r=t.startsWith("-"),o=r||t.startsWith("+")?t.slice(1):t,i=be(_(o).toString(),e);return r&&i!=="0"?`-${i}`:i}function He(n){let e=typeof n=="string"?ve({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 ye(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===Le&&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===Ne&&s.length>=2&&!t){let u=BigInt(s[1]).toString();u!=="0"&&o.add(u)}}return[...o]}function sn(n){let e=t=>typeof t=="bigint"?t:_(t);return L({abi:Oe,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 he=1n<<96n;function xe(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 We(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)/he;return{amount0:a,amount1:u}}return{amount0:0n,amount1:r*(i-o)/he}}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 Fe(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 _(n);throw new d(`${e} must be a non-negative integer.`)}async function Se(n,e){let t=await Fe(n);if(e==null)return t+$e;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 _(n)}function Ae(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?_(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,gas:`0x${ke.toString(16)}`,to:i.to,data:i.data,value:`0x${BigInt(i.value).toString(16)}`}))}],validation:!1,traceTransfers:!0},"latest"]},{retryCount:0});if(!Array.isArray(o)||o.length!==1||!Array.isArray(o[0]?.calls)||o[0].calls.length!==e.length)throw new 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 ve({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 He(t)}function pe(n,e){if(!Array.isArray(e.changes)||!e.changes.length)return n;let t=e.changes.map(r=>`${Ve(r.amount,r.token.decimals)} ${r.token.symbol}`);return`${n} (${t.join(", ")})`}async function Ge(n,e,t){E(t);let r=m(t),o=z(n,e),i=await Se(o,e.deadline),s=Ae(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:Ie,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}=De(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:Re,value:W.toString(),chainId:g,description:"Wrap ETH into WETH."}))}for(let[W,Te]of[c,p].entries()){let se=W===0?C:H;se>0n&&D[W]<se&&re.push(n.approval(Te,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]),Me=I[I.length-2],Ue=I[I.length-1];if(Me>k||Ue>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 Xe(n,e,t){E(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 ze(n,e,t){E(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 Se(o,e.deadline),c=Ae(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 je(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 ye(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??qe,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 ye({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 Pe(n,e,t={}){E(e);let r=m(e),o=z(n),i=await je(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:Ie,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=xe(c.tickLower),q=xe(c.tickUpper),$=We(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 Ke(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 Pe(n,r,{tokenIds:o,receipts:i,includeEmpty:s});return{positions:a,details:{version:"v3",wallet:r,count:a.length,positionManager:f.positionManager}}}function Qe(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)=>Ge(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)=>Xe(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)=>ze(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)=>Ke(n,i,s)}]}var te=n=>({tools:Qe(n),positions:e=>Pe(n,e)}),an=te,dn=te,cn=te,un=te;export{ce as a,ue as b,O as c,f as d,_e as e,rn as f,v as g,Ie as h,Ee as i,Oe as j,De as k,Ve as l,He as m,ye as n,sn as o,Ge as p,Xe as q,ze as r,Pe as s,Ke as t,Qe as u,te as v,an as w,dn as x,cn as y,un as z};