@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 +1 @@
1
- import{b as se,o as ae}from"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import{c as re}from"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import{b as ie}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import{a as U}from"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import{a as w,d as $,i as G}from"../../../chunks/25EOXUBI.js";import{a as N}from"../../../chunks/B5RZYFQC.js";import{a as m}from"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";import{decodeEventLog as ye,decodeFunctionResult as Ce,encodeFunctionData as M,getAddress as C,parseAbi as j}from"viem";var Pe="https://priors.trade/api/check",Q=604800n,de=50n,le=10000n,ce=5000000n,ue=500000000n,ee=86400n,pe=2592000n,ve="0x6982e39521a070a3c40782548bfbed6dc8f566ef",$e=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],n={pool:C(G[4663].priors.pool.address),lens:C(G[4663].priors.lens.address),usdg:C(G[4663].priors.usdg.address),registry:C(G[4663].priors.registry.address),stockVault:C(G[4663].priors.stockVault.address)},z={address:n.usdg,symbol:"USDG",decimals:$,chainId:w},g=j(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool v1Checked, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 qualifiedRepaid, uint256 qualifiedVolume, uint256 lateRepayments, uint256 scorePoints)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),De=j(["function available(uint256 agentId) view returns (uint256)"]),te=j(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),ge=j(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Re(e){return e.chainId===w&&e.address.toLowerCase()===n.usdg.toLowerCase()}function Oe(e,t){let r=t.amount.trim(),l=r.startsWith("-"),b=l||r.startsWith("+")?r.slice(1):r,k=e.formatAmount(b,t.token.decimals),T=Re(t.token)?"USDG":t.token.address;return`${l?"-":"+"}${k} ${T}`}function W(e,t,r){if(!r.length)return t;let l=r.map(b=>Oe(e,b)).join(", ");return`${t} Preview changes: ${l}.`}function me(e,t,r,l){let b=e[t]===void 0?void 0:N(e[t]),k=e[r]===void 0?void 0:N(e[r]);if(b!==void 0)return b;if(k!==void 0)return k;throw new m(`Provide ${l} as an integer string in base units ("${t}" or "${r}").`)}async function he(e,t){try{return C(await e.clientFor(w).readContract({address:n.registry,abi:te,functionName:"ownerOf",args:[t]}))}catch{throw new m(`Could not read the owner of ERC-8004 agent ${t} from registry ${n.registry}. Check the agent ID and retry when the registry is available.`)}}function F(e,t){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let r=BigInt(e.trim());if(r>0n)return r}throw new m(`Provide a positive integer ${t}.`)}function ke(e,t){let r=t!==void 0?F(t,"agentId"):void 0,l=[];for(let b of e)if(!(!b||typeof b.address!="string")&&b.address.toLowerCase()===n.pool.toLowerCase()&&!(!Array.isArray(b.topics)||b.topics.length===0))try{let k=ye({abi:g,eventName:"Borrowed",data:b.data,topics:b.topics});if(r!==void 0&&k.args.agentId!==r)continue;l.push(k.args.loanId)}catch{continue}return l.length===0?null:l[l.length-1].toString()}function fe(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],v1Checked:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),qualifiedRepaid:BigInt(e[18]),qualifiedVolume:BigInt(e[19]),lateRepayments:BigInt(e[20]),scorePoints:BigInt(e[21])}}function H(e,t){return{loanId:e,agentId:BigInt(t[0]),sponsorId:BigInt(t[1]),principal:BigInt(t[2]),fee:BigInt(t[3]),sponsorCut:BigInt(t[4]),reserveCut:BigInt(t[5]),premium:BigInt(t[6]),owner:C(String(t[7])),issuedAt:BigInt(t[8]),dueAt:BigInt(t[9]),defaultableAt:BigInt(t[10]),minScoreTerm:BigInt(t[11]),closedAt:BigInt(t[12]),status:Number(t[13])}}async function oe(e,t){let r=e.clientFor(w),l=await r.readContract({address:n.registry,abi:te,functionName:"balanceOf",args:[t]});if(l<=0n)return[];let b=l>10n?10:Number(l),k=Array.from({length:b},(T,o)=>BigInt(o));return Promise.all(k.map(T=>r.readContract({address:n.registry,abi:te,functionName:"tokenOfOwnerByIndex",args:[t,T]})))}async function be(e,t,r){if(t.agentId!==void 0&&t.agentId!==null&&String(t.agentId).trim()!=="")return F(t.agentId,"agentId");let l=await oe(e,r);if(l.length===0)throw new m("Priors borrowing requires an already-funded ERC-8004 credit line on CreditPoolV2; this wallet owns no ERC-8004 agent identity and Oak does not perform credit-line enrollment or sponsorship.");return l[0]}async function we(e,t,r){let l=e.clientFor(w),b=await he(e,t),[k,T]=await Promise.all([l.readContract({address:n.pool,abi:g,functionName:"delegateOf",args:[t]}),l.readContract({address:n.pool,abi:g,functionName:"isController",args:[t,r]})]),o=C(k);if(!T)throw new m(`Wallet ${r} is not an on-chain controller for ERC-8004 agent ${t} (ownerOf=${b}, delegateOf=${o}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:b,delegate:o}}function Le(e,t){if(!t.enrolled||t.isRoot||t.sponsor===0n)throw new m(`ERC-8004 agent ${e} does not have an enrolled, sponsor-backed non-root credit line on CreditPoolV2 (enrolled=${t.enrolled}, sponsor=${t.sponsor}, isRoot=${t.isRoot}). Priors actions require an already-funded ERC-8004 credit line.`);if(t.defaulted||t.frozen)throw new m(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${t.defaulted}, frozen=${t.frozen}).`);let r=t.delegatedIn>t.principalOut?t.delegatedIn-t.principalOut:0n;if(r<=0n)throw new m(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${t.delegatedIn}, principalOut=${t.principalOut}).`);return r}function Be(e){let t=e.borrowReceiptLogs??(ne(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(t))return[];let r=[];for(let l of t)ne(l)&&(typeof l.address!="string"||!Array.isArray(l.topics)||typeof l.data!="string"||r.push({address:l.address,topics:l.topics,data:l.data}));return r}var Se=e=>{let t={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(o,I){U(I);let a=C(I),i=a;if(o.receiver!==void 0&&(typeof o.receiver!="string"||o.receiver.trim().toLowerCase()!==a.toLowerCase()))throw new m("Priors receiver must be the signing wallet.");let c=me(o,"assets","amount","USDG deposit amount");if(c<=0n)throw new m("Deposit amount must be greater than zero.");let p=o.minShares===void 0?void 0:N(o.minShares),s=e.approval(n.usdg,n.pool,c.toString(),w);if(p===void 0){let u;try{let A=await e.clientFor(w).simulateCalls({account:a,calls:[{to:s.to,data:s.data},{to:n.pool,data:M({abi:g,functionName:"deposit",args:[c,i,0n]})}]}),[B,O]=A.results;if(B?.status!=="success"||O?.status!=="success")throw new m("Approval or deposit simulation failed.");u=Ce({abi:g,functionName:"deposit",data:O.data})}catch(A){throw new m(`Could not simulate Priors deposit shares: ${e.plainError(A)}`)}if(p=N(ae(u.toString(),o.slippageBps??se)),p===0n)throw new m("The simulated deposit cannot provide a positive minimum share amount.")}let h=e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"deposit",args:[c,i,p]}),value:"0",chainId:w,description:`Deposit ${c} USDG base units into Priors CreditPoolV2 (${n.pool}) for ${i}.`}),y=[s,h],d=await e.preview(y,a),L=`Approve ${e.formatAmount(c.toString(),$)} USDG and deposit into Priors CreditPoolV2 (${n.pool}) for ${i} (minShares=${p}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:y,summary:W(e,L,d.changes)}}},r={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(o,I){U(I);let a=C(I),i=a;if(o.receiver!==void 0&&(typeof o.receiver!="string"||o.receiver.trim().toLowerCase()!==a.toLowerCase()))throw new m("Priors receiver must be the signing wallet.");let c=e.clientFor(w),p=o.shares!==void 0?N(o.shares):await c.readContract({address:n.pool,abi:g,functionName:"shares",args:[a]});if(p<=0n)throw new m(`Wallet ${a} has no Priors CreditPoolV2 shares to withdraw.`);let[s,h,y]=await Promise.all([c.readContract({address:n.pool,abi:g,functionName:"convertToAssets",args:[p]}),c.readContract({address:n.pool,abi:g,functionName:"lastDepositAt",args:[a]}),c.getBlock()]),d=h>0n&&y.timestamp<h+Q,S=d?s*de/le:0n,L=s-S,A=[e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"withdraw",args:[p,i]}),value:"0",chainId:w,description:`Withdraw ${p} shares from Priors CreditPoolV2 (${n.pool}) to ${i}.`})],B=await e.preview(A,a),O=e.formatAmount(L.toString(),$),_=e.formatAmount(s.toString(),$),D=e.formatAmount(S.toString(),$),P=d?`inside 7-day MIN_HOLD: ${D} USDG (0.5%) early-exit fee stays in pool, net payout ${O} USDG from ${_} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${O} USDG`,v=`Withdraw ${p} shares from Priors CreditPoolV2 (${n.pool}) to ${i} (${P}).`;return{txs:A,summary:W(e,v,B.changes)}}},l={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400").'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional maximum origination fee in USDG base units (defaults to exact quoteFee result)."}}},async execute(o,I){U(I);let a=C(I),i=a;if(o.recipient!==void 0&&(typeof o.recipient!="string"||o.recipient.trim().toLowerCase()!==a.toLowerCase()))throw new m("Priors recipient must be the signing wallet.");let c=await be(e,o,a);await we(e,c,a);let p=e.clientFor(w),s=await p.readContract({address:n.pool,abi:g,functionName:"getAgent",args:[c]}),h=fe(s),y=Le(c,h),d=me(o,"principal","amount","USDG borrow principal");if(d<ce||d>ue)throw new m(`Borrow principal must be between ${ce} (5 USDG) and ${ue} (500 USDG) base units.`);if(d>y)throw new m(`Borrow principal ${d} exceeds available credit line capacity ${y} USDG base units for agent ${c}.`);let S=o.term!==void 0&&String(o.term).trim()!==""?F(o.term,"term"):ee;if(S<ee||S>pe)throw new m(`Loan term must be between ${ee} (1 day) and ${pe} (30 days) seconds.`);let L=await p.readContract({address:n.pool,abi:g,functionName:"quoteFee",args:[c,d,S]}),u=L[0],A=o.maxFee!==void 0?N(o.maxFee):u;if(A<u)throw new m(`Provided maxFee ${A} is below the quoted fixed origination fee ${u} USDG base units.`);let B=d+u,O=d+A,D=[e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"borrow",args:[c,d,S,i,A]}),value:"0",chainId:w,description:`Borrow ${d} USDG base units on Priors CreditPoolV2 for agent ${c} to ${i} (quoted fee ${u}, expected debt ${B}, maxFee ${A}, debt ceiling ${O}).`})],P=await e.preview(D,a),v=e.formatAmount(d.toString(),$),x=e.formatAmount(u.toString(),$),E=e.formatAmount(B.toString(),$),X=e.formatAmount(A.toString(),$),J=e.formatAmount(O.toString(),$),V=L[1]+L[3],q=L[2],Y=u-V-q,Z=`Borrow ${v} USDG for ERC-8004 agent ${c} to recipient ${i} on Priors CreditPoolV2 (${n.pool}) for ${S}s: expected fixed origination fee ${x} USDG (${u} base units), expected total repayment due ${E} USDG (${B} base units); fee ceiling ${X} USDG (${A} base units), debt ceiling ${J} USDG (${O} base units). Fee recipient on repayment: CreditPoolV2 (${n.pool}), allocating the quoted fee to sponsor ${h.sponsor} (${V} base units including premium), reserve (${q} base units), and lenders (${Y} base units).`;return{txs:D,summary:W(e,Z,P.changes)}}},b={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay (defaults to exact fixed principal + fee)."}}},async execute(o,I){U(I);let a=C(I),i=await be(e,o,a);await we(e,i,a);let c=e.clientFor(w),p;if(o.loanId!==void 0&&o.loanId!==null&&String(o.loanId).trim()!=="")p=F(o.loanId,"loanId");else{let D=Be(o);if(D.length>0){let P=ke(D,i);P!==null&&(p=BigInt(P))}}let s;if(p!==void 0){let D=await c.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[p]}),P=H(p,D);if(P.agentId!==i)throw new m(`Loan ${p} belongs to agent ${P.agentId}, not agent ${i}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(P.status!==1)throw new m(`Loan ${p} for agent ${i} is not active (status=${P.status}).`);s=P}else{let D=await c.readContract({address:n.pool,abi:g,functionName:"loansOf",args:[i]});if(D.length===0)throw new m(`ERC-8004 agent ${i} has no recorded loans on Priors CreditPoolV2.`);let v=(await Promise.all(D.map(async x=>{let E=await c.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[x]});return H(x,E)}))).filter(x=>x.agentId===i&&x.status===1);if(v.length===0)throw new m(`ERC-8004 agent ${i} has no active loans to repay.`);s=v[v.length-1]}let h=s.principal+s.fee,y=o.maxDue!==void 0?N(o.maxDue):h;if(y<h)throw new m(`Provided maxDue ${y} is below the exact fixed loan debt ${h} USDG base units (principal ${s.principal} + fixed fee ${s.fee}).`);let d=e.approval(n.usdg,n.pool,h.toString(),w),S=e.unsignedTx({to:n.pool,data:M({abi:g,functionName:"repay",args:[s.loanId,i,y]}),value:"0",chainId:w,description:`Repay fixed debt ${h} USDG base units (principal ${s.principal} + fee ${s.fee}) for loan ${s.loanId} (agent ${i}).`}),L=[d,S],u=await e.preview(L,a),A=e.formatAmount(h.toString(),$),B=e.formatAmount(s.principal.toString(),$),O=e.formatAmount(s.fee.toString(),$),_=`Approve and repay ${A} USDG (${h} base units: ${B} USDG principal + ${O} USDG fixed fee) for Priors loan ${s.loanId} (agent ${i}).`;return{txs:L,summary:W(e,_,u.changes)}}},k={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(o,I){U(I);let a=C(I),i=e.clientFor(w),[c,p,s,h]=await Promise.all([i.readContract({address:n.pool,abi:g,functionName:"shares",args:[a]}),i.readContract({address:n.pool,abi:g,functionName:"lastDepositAt",args:[a]}),i.getBlock(),i.readContract({address:n.stockVault,abi:ge,functionName:"assetList"})]),y=c>0n?await i.readContract({address:n.pool,abi:g,functionName:"convertToAssets",args:[c]}):0n,d=c>0n&&p>0n&&s.timestamp<p+Q,S=d?y*de/le:0n,L=y-S,u=null;if(o.agentId!==void 0&&o.agentId!==null&&String(o.agentId).trim()!=="")u=F(o.agentId,"agentId");else{let v=await oe(e,a);v.length>0&&(u=v[0])}let A=null,B=!1,O=[],_=null,D=null;if(u!==null){let[v,x,E,X,J,V]=await Promise.all([i.readContract({address:n.pool,abi:g,functionName:"getAgent",args:[u]}),i.readContract({address:n.pool,abi:g,functionName:"loansOf",args:[u]}),i.readContract({address:n.lens,abi:De,functionName:"available",args:[u]}),i.readContract({address:n.stockVault,abi:ge,functionName:"borrowRoom",args:[u]}),i.readContract({address:n.pool,abi:g,functionName:"delegateOf",args:[u]}),i.readContract({address:n.pool,abi:g,functionName:"isController",args:[u,a]})]),q=await he(e,u),Y=C(J),Z=V,f=fe(v),Ae=f.delegatedIn>f.principalOut?f.delegatedIn-f.principalOut:0n;B=f.enrolled&&!f.isRoot&&!f.defaulted&&!f.frozen&&f.sponsor>0n&&f.delegatedIn>0n,_=E.toString(),D=X.toString();let Ie=await Promise.all(x.map(async R=>{let K=await i.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[R]});return H(R,K)}));for(let R of Ie)if(R.agentId===u&&R.status===1){let K=R.principal+R.fee;O.push({loanId:R.loanId.toString(),agentId:R.agentId.toString(),sponsorId:R.sponsorId.toString(),principal:R.principal.toString(),fee:R.fee.toString(),due:K.toString(),dueAt:R.dueAt.toString(),issuedAt:R.issuedAt.toString(),owner:R.owner,token:z})}A={agentId:u.toString(),owner:q,delegate:Y,isAuthorizedController:Z,enrolled:f.enrolled,isRoot:f.isRoot,defaulted:f.defaulted,frozen:f.frozen,sponsorId:f.sponsor.toString(),delegatedIn:f.delegatedIn.toString(),delegatedOut:f.delegatedOut.toString(),principalOut:f.principalOut.toString(),availableCapacity:Ae.toString(),activeLoansCount:f.activeLoans.toString(),loansRepaid:f.loansRepaid.toString(),volumeRepaid:f.volumeRepaid.toString(),feesPaid:f.feesPaid.toString(),scorePoints:f.scorePoints.toString()}}let P=null;if(o.includeApiCheck){let v=u!==null?`agent=${u.toString()}`:`address=${a}`;P={...await re(e.http,`${Pe}?${v}`,{method:"GET"},ne),grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:w,blockNumber:s.number?.toString()??null,blockTimestamp:s.timestamp.toString(),wallet:a,token:z,contracts:n,lender:{shares:c.toString(),grossAssets:y.toString(),earlyExitFeeAssets:S.toString(),netWithdrawAssets:L.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:d,minHoldSeconds:Q.toString()},hasFundedLine:B,agentId:u!==null?u.toString():null,agent:A,activeLoans:O,lens:{address:n.lens,available:_,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:n.stockVault,borrowRoom:D,onchainAssetCount:h.length,hostedMcpStockCount:35,extraNonStockAsset:C(ve),zeroCapAssets:$e.map(v=>C(v)),caveat:"StockVault metadata is read-only status for already-funded lines (36 on-chain assets including PT-USDG-25MAR2027; CLSK and RGTI have lineCap=0), not an enrollment workflow."},apiCheck:P,limitations:["Borrowing and repayment require an already-funded ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet); Oak does not perform root staking, sponsorship, or credit-line enrollment.","Loan debt is fixed principal + quoteFee origination fee; variable interest is never invented.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}};async function T(o){U(o);let I=C(o),a=e.clientFor(w),[i,c]=await Promise.all([a.readContract({address:n.pool,abi:g,functionName:"shares",args:[I]}),oe(e,I)]),p=[];if(i>0n){let s=await a.readContract({address:n.pool,abi:g,functionName:"convertToAssets",args:[i]});p.push({module:"priors",id:`priors:lender:${I.toLowerCase()}`,chainId:w,assets:[{token:z,amount:s.toString()}],description:`Priors CreditPoolV2 lender position (${i} shares = ${e.formatAmount(s.toString(),$)} USDG gross).`})}for(let s of c){let h=await a.readContract({address:n.pool,abi:g,functionName:"loansOf",args:[s]}),y=await Promise.all(h.map(async d=>{let S=await a.readContract({address:n.pool,abi:g,functionName:"getLoan",args:[d]});return H(d,S)}));for(let d of y)if(d.agentId===s&&d.status===1){let S=d.principal+d.fee;p.push({module:"priors",id:`priors:loan:${d.loanId.toString()}`,chainId:w,assets:[{token:z,amount:S.toString()}],description:`Priors CreditPoolV2 active loan ${d.loanId} for agent ${s} (fixed due ${e.formatAmount(S.toString(),$)} USDG = ${d.principal} principal + ${d.fee} fee).`})}}return p}return{tools:[t,r,l,b,k],positions:T}},Ve=Se,xe=e=>ie("priors",[Se(e)]),qe=xe;export{Pe as PRIORS_API_CHECK_URL,le as PRIORS_BPS_DENOMINATOR,n as PRIORS_CONTRACTS,de as PRIORS_EARLY_EXIT_FEE_BPS,ue as PRIORS_MAX_LOAN_USDG,pe as PRIORS_MAX_TERM_SECONDS,Q as PRIORS_MIN_HOLD_SECONDS,ce as PRIORS_MIN_LOAN_USDG,ee as PRIORS_MIN_TERM_SECONDS,z as PRIORS_USDG_TOKEN,xe as createModule,Se as createModulePart,qe as createPriorsModule,Ve as createPriorsPart,ke as recoverBorrowedLoanId};
1
+ import{b as se,o as ae}from"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import{c as re}from"../../../chunks/MK6L6TGI.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import{b as ie}from"../../../chunks/UCMNB2UP.js";import"../../../chunks/Z25UKUJF.js";import{a as U}from"../../../chunks/A5ITAEUQ.js";import{a as _}from"../../../chunks/I5CQ64EU.js";import"../../../chunks/NA7HV7BR.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import{a as S,d as $,i as G}from"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import{a as f}from"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";import{decodeEventLog as ye,decodeFunctionResult as Ce,encodeFunctionData as M,getAddress as C,parseAbi as j,parseAbiItem as ve}from"viem";var Pe="https://priors.trade/api/check",Q=604800n,de=50n,le=10000n,ce=5000000n,ue=500000000n,ee=86400n,pe=2592000n,$e="0x6982e39521a070a3c40782548bfbed6dc8f566ef",De=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],o={pool:C(G[4663].priors.pool.address),lens:C(G[4663].priors.lens.address),usdg:C(G[4663].priors.usdg.address),registry:C(G[4663].priors.registry.address),stockVault:C(G[4663].priors.stockVault.address)},z={address:o.usdg,symbol:"USDG",decimals:$,chainId:S},g=j(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool v1Checked, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 qualifiedRepaid, uint256 qualifiedVolume, uint256 lateRepayments, uint256 scorePoints)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),Re=j(["function available(uint256 agentId) view returns (uint256)"]),he=j(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),ge=j(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function te(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ke(e){return e.chainId===S&&e.address.toLowerCase()===o.usdg.toLowerCase()}function Le(e,t){let r=t.amount.trim(),c=r.startsWith("-"),m=c||r.startsWith("+")?r.slice(1):r,D=e.formatAmount(m,t.token.decimals),T=ke(t.token)?"USDG":t.token.address;return`${c?"-":"+"}${D} ${T}`}function W(e,t,r){if(!r.length)return t;let c=r.map(m=>Le(e,m)).join(", ");return`${t} Preview changes: ${c}.`}function fe(e,t,r,c){let m=e[t]===void 0?void 0:_(e[t]),D=e[r]===void 0?void 0:_(e[r]);if(m!==void 0)return m;if(D!==void 0)return D;throw new f(`Provide ${c} as an integer string in base units ("${t}" or "${r}").`)}async function oe(e,t,r){try{return C(await e.clientFor(S).readContract({address:o.registry,abi:he,functionName:"ownerOf",args:[t],blockNumber:r}))}catch{throw new f(`Could not read the owner of ERC-8004 agent ${t} from registry ${o.registry}. Check the agent ID and retry when the registry is available.`)}}function F(e,t){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let r=BigInt(e.trim());if(r>0n)return r}throw new f(`Provide a positive integer ${t}.`)}function Oe(e,t){let r=t!==void 0?F(t,"agentId"):void 0,c=[];for(let m of e)if(!(!m||typeof m.address!="string")&&m.address.toLowerCase()===o.pool.toLowerCase()&&!(!Array.isArray(m.topics)||m.topics.length===0))try{let D=ye({abi:g,eventName:"Borrowed",data:m.data,topics:m.topics});if(r!==void 0&&D.args.agentId!==r)continue;c.push(D.args.loanId)}catch{continue}return c.length===0?null:c[c.length-1].toString()}function me(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],v1Checked:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),qualifiedRepaid:BigInt(e[18]),qualifiedVolume:BigInt(e[19]),lateRepayments:BigInt(e[20]),scorePoints:BigInt(e[21])}}function H(e,t){return{loanId:e,agentId:BigInt(t[0]),sponsorId:BigInt(t[1]),principal:BigInt(t[2]),fee:BigInt(t[3]),sponsorCut:BigInt(t[4]),reserveCut:BigInt(t[5]),premium:BigInt(t[6]),owner:C(String(t[7])),issuedAt:BigInt(t[8]),dueAt:BigInt(t[9]),defaultableAt:BigInt(t[10]),minScoreTerm:BigInt(t[11]),closedAt:BigInt(t[12]),status:Number(t[13])}}async function ne(e,t){let r=e.clientFor(S),c=await r.getBlockNumber({cacheTime:0}),m=await r.readContract({address:o.registry,abi:he,functionName:"balanceOf",args:[t],blockNumber:c});if(m===0n)return[];if(typeof m!="bigint"||m<0n)throw new f("Registry balance is unavailable. Retry or provide an explicit agentId.");let D=[],T=new Set,n=c;for(;;){let w=n>9999999n?n-9999999n:0n,d=await r.getLogs({address:o.registry,event:ve("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:t},fromBlock:w,toBlock:n,strict:!0});for(let i of d){let a=i.args.tokenId;if(i.removed||T.has(a))continue;if(T.add(a),(await oe(e,a,c)).toLowerCase()===t.toLowerCase()&&D.push(a),BigInt(D.length)===m)return D.sort((s,h)=>s<h?-1:s>h?1:0)}if(w===0n)throw new f("Owned identities could not all be located. Retry or provide an explicit agentId.");n=w-1n}}async function be(e,t,r){if(t.agentId!==void 0&&t.agentId!==null&&String(t.agentId).trim()!=="")return F(t.agentId,"agentId");let c=await ne(e,r);if(c.length===0)throw new f("Priors borrowing requires an already-funded ERC-8004 credit line on CreditPoolV2; this wallet owns no ERC-8004 agent identity and Oak does not perform credit-line enrollment or sponsorship.");return c[0]}async function we(e,t,r){let c=e.clientFor(S),m=await oe(e,t),[D,T]=await Promise.all([c.readContract({address:o.pool,abi:g,functionName:"delegateOf",args:[t]}),c.readContract({address:o.pool,abi:g,functionName:"isController",args:[t,r]})]),n=C(D);if(!T)throw new f(`Wallet ${r} is not an on-chain controller for ERC-8004 agent ${t} (ownerOf=${m}, delegateOf=${n}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:m,delegate:n}}function Be(e,t){if(!t.enrolled||t.isRoot||t.sponsor===0n)throw new f(`ERC-8004 agent ${e} does not have an enrolled, sponsor-backed non-root credit line on CreditPoolV2 (enrolled=${t.enrolled}, sponsor=${t.sponsor}, isRoot=${t.isRoot}). Priors actions require an already-funded ERC-8004 credit line.`);if(t.defaulted||t.frozen)throw new f(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${t.defaulted}, frozen=${t.frozen}).`);let r=t.delegatedIn>t.principalOut?t.delegatedIn-t.principalOut:0n;if(r<=0n)throw new f(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${t.delegatedIn}, principalOut=${t.principalOut}).`);return r}function xe(e){let t=e.borrowReceiptLogs??(te(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(t))return[];let r=[];for(let c of t)te(c)&&(typeof c.address!="string"||!Array.isArray(c.topics)||typeof c.data!="string"||r.push({address:c.address,topics:c.topics,data:c.data}));return r}var Se=e=>{let t={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",pattern:"^[0-9]+$",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",pattern:"^[0-9]+$",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(n,w){U(w);let d=C(w),i=d;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==d.toLowerCase()))throw new f("Priors receiver must be the signing wallet.");let a=fe(n,"assets","amount","USDG deposit amount");if(a<=0n)throw new f("Deposit amount must be greater than zero.");let u=n.minShares===void 0?void 0:_(n.minShares),s=e.approval(o.usdg,o.pool,a.toString(),S);if(u===void 0){let p;try{let A=await e.clientFor(S).simulateCalls({account:d,calls:[{to:s.to,data:s.data},{to:o.pool,data:M({abi:g,functionName:"deposit",args:[a,i,0n]})}]}),[B,L]=A.results;if(B?.status!=="success"||L?.status!=="success")throw new f("Approval or deposit simulation failed.");p=Ce({abi:g,functionName:"deposit",data:L.data})}catch(A){throw new f(`Could not simulate Priors deposit shares: ${e.plainError(A)}`)}if(u=_(ae(p.toString(),n.slippageBps??se)),u===0n)throw new f("The simulated deposit cannot provide a positive minimum share amount.")}let h=e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"deposit",args:[a,i,u]}),value:"0",chainId:S,description:`Deposit ${a} USDG base units into Priors CreditPoolV2 (${o.pool}) for ${i}.`}),y=[s,h],l=await e.preview(y,d),O=`Approve ${e.formatAmount(a.toString(),$)} USDG and deposit into Priors CreditPoolV2 (${o.pool}) for ${i} (minShares=${u}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:y,summary:W(e,O,l.changes)}}},r={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",pattern:"^[0-9]+$",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(n,w){U(w);let d=C(w),i=d;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==d.toLowerCase()))throw new f("Priors receiver must be the signing wallet.");let a=e.clientFor(S),u=n.shares!==void 0?_(n.shares):await a.readContract({address:o.pool,abi:g,functionName:"shares",args:[d]});if(u<=0n)throw new f(`Wallet ${d} has no Priors CreditPoolV2 shares to withdraw.`);let[s,h,y]=await Promise.all([a.readContract({address:o.pool,abi:g,functionName:"convertToAssets",args:[u]}),a.readContract({address:o.pool,abi:g,functionName:"lastDepositAt",args:[d]}),a.getBlock()]),l=h>0n&&y.timestamp<h+Q,I=l?s*de/le:0n,O=s-I,A=[e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"withdraw",args:[u,i]}),value:"0",chainId:S,description:`Withdraw ${u} shares from Priors CreditPoolV2 (${o.pool}) to ${i}.`})],B=await e.preview(A,d),L=e.formatAmount(O.toString(),$),N=e.formatAmount(s.toString(),$),R=e.formatAmount(I.toString(),$),v=l?`inside 7-day MIN_HOLD: ${R} USDG (0.5%) early-exit fee stays in pool, net payout ${L} USDG from ${N} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${L} USDG`,P=`Withdraw ${u} shares from Priors CreditPoolV2 (${o.pool}) to ${i} (${v}).`;return{txs:A,summary:W(e,P,B.changes)}}},c={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",pattern:"^[0-9]+$",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400").'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional maximum origination fee in USDG base units (defaults to exact quoteFee result)."}}},async execute(n,w){U(w);let d=C(w),i=d;if(n.recipient!==void 0&&(typeof n.recipient!="string"||n.recipient.trim().toLowerCase()!==d.toLowerCase()))throw new f("Priors recipient must be the signing wallet.");let a=await be(e,n,d);await we(e,a,d);let u=e.clientFor(S),s=await u.readContract({address:o.pool,abi:g,functionName:"getAgent",args:[a]}),h=me(s),y=Be(a,h),l=fe(n,"principal","amount","USDG borrow principal");if(l<ce||l>ue)throw new f(`Borrow principal must be between ${ce} (5 USDG) and ${ue} (500 USDG) base units.`);if(l>y)throw new f(`Borrow principal ${l} exceeds available credit line capacity ${y} USDG base units for agent ${a}.`);let I=n.term!==void 0&&String(n.term).trim()!==""?F(n.term,"term"):ee;if(I<ee||I>pe)throw new f(`Loan term must be between ${ee} (1 day) and ${pe} (30 days) seconds.`);let O=await u.readContract({address:o.pool,abi:g,functionName:"quoteFee",args:[a,l,I]}),p=O[0],A=n.maxFee!==void 0?_(n.maxFee):p;if(A<p)throw new f(`Provided maxFee ${A} is below the quoted fixed origination fee ${p} USDG base units.`);let B=l+p,L=l+A,R=[e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"borrow",args:[a,l,I,i,A]}),value:"0",chainId:S,description:`Borrow ${l} USDG base units on Priors CreditPoolV2 for agent ${a} to ${i} (quoted fee ${p}, expected debt ${B}, maxFee ${A}, debt ceiling ${L}).`})],v=await e.preview(R,d),P=e.formatAmount(l.toString(),$),x=e.formatAmount(p.toString(),$),E=e.formatAmount(B.toString(),$),X=e.formatAmount(A.toString(),$),J=e.formatAmount(L.toString(),$),V=O[1]+O[3],q=O[2],Y=p-V-q,Z=`Borrow ${P} USDG for ERC-8004 agent ${a} to recipient ${i} on Priors CreditPoolV2 (${o.pool}) for ${I}s: expected fixed origination fee ${x} USDG (${p} base units), expected total repayment due ${E} USDG (${B} base units); fee ceiling ${X} USDG (${A} base units), debt ceiling ${J} USDG (${L} base units). Fee recipient on repayment: CreditPoolV2 (${o.pool}), allocating the quoted fee to sponsor ${h.sponsor} (${V} base units including premium), reserve (${q} base units), and lenders (${Y} base units).`;return{txs:R,summary:W(e,Z,v.changes)}}},m={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay (defaults to exact fixed principal + fee)."}}},async execute(n,w){U(w);let d=C(w),i=await be(e,n,d);await we(e,i,d);let a=e.clientFor(S),u;if(n.loanId!==void 0&&n.loanId!==null&&String(n.loanId).trim()!=="")u=F(n.loanId,"loanId");else{let R=xe(n);if(R.length>0){let v=Oe(R,i);v!==null&&(u=BigInt(v))}}let s;if(u!==void 0){let R=await a.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[u]}),v=H(u,R);if(v.agentId!==i)throw new f(`Loan ${u} belongs to agent ${v.agentId}, not agent ${i}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(v.status!==1)throw new f(`Loan ${u} for agent ${i} is not active (status=${v.status}).`);s=v}else{let R=await a.readContract({address:o.pool,abi:g,functionName:"loansOf",args:[i]});if(R.length===0)throw new f(`ERC-8004 agent ${i} has no recorded loans on Priors CreditPoolV2.`);let P=(await Promise.all(R.map(async x=>{let E=await a.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[x]});return H(x,E)}))).filter(x=>x.agentId===i&&x.status===1);if(P.length===0)throw new f(`ERC-8004 agent ${i} has no active loans to repay.`);s=P[P.length-1]}let h=s.principal+s.fee,y=n.maxDue!==void 0?_(n.maxDue):h;if(y<h)throw new f(`Provided maxDue ${y} is below the exact fixed loan debt ${h} USDG base units (principal ${s.principal} + fixed fee ${s.fee}).`);let l=e.approval(o.usdg,o.pool,h.toString(),S),I=e.unsignedTx({to:o.pool,data:M({abi:g,functionName:"repay",args:[s.loanId,i,y]}),value:"0",chainId:S,description:`Repay fixed debt ${h} USDG base units (principal ${s.principal} + fee ${s.fee}) for loan ${s.loanId} (agent ${i}).`}),O=[l,I],p=await e.preview(O,d),A=e.formatAmount(h.toString(),$),B=e.formatAmount(s.principal.toString(),$),L=e.formatAmount(s.fee.toString(),$),N=`Approve and repay ${A} USDG (${h} base units: ${B} USDG principal + ${L} USDG fixed fee) for Priors loan ${s.loanId} (agent ${i}).`;return{txs:O,summary:W(e,N,p.changes)}}},D={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(n,w){U(w);let d=C(w),i=e.clientFor(S),[a,u,s,h]=await Promise.all([i.readContract({address:o.pool,abi:g,functionName:"shares",args:[d]}),i.readContract({address:o.pool,abi:g,functionName:"lastDepositAt",args:[d]}),i.getBlock(),i.readContract({address:o.stockVault,abi:ge,functionName:"assetList"})]),y=a>0n?await i.readContract({address:o.pool,abi:g,functionName:"convertToAssets",args:[a]}):0n,l=a>0n&&u>0n&&s.timestamp<u+Q,I=l?y*de/le:0n,O=y-I,p=null;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")p=F(n.agentId,"agentId");else{let P=await ne(e,d);P.length>0&&(p=P[0])}let A=null,B=!1,L=[],N=null,R=null;if(p!==null){let[P,x,E,X,J,V]=await Promise.all([i.readContract({address:o.pool,abi:g,functionName:"getAgent",args:[p]}),i.readContract({address:o.pool,abi:g,functionName:"loansOf",args:[p]}),i.readContract({address:o.lens,abi:Re,functionName:"available",args:[p]}),i.readContract({address:o.stockVault,abi:ge,functionName:"borrowRoom",args:[p]}),i.readContract({address:o.pool,abi:g,functionName:"delegateOf",args:[p]}),i.readContract({address:o.pool,abi:g,functionName:"isController",args:[p,d]})]),q=await oe(e,p),Y=C(J),Z=V,b=me(P),Ie=b.delegatedIn>b.principalOut?b.delegatedIn-b.principalOut:0n;B=b.enrolled&&!b.isRoot&&!b.defaulted&&!b.frozen&&b.sponsor>0n&&b.delegatedIn>0n,N=E.toString(),R=X.toString();let Ae=await Promise.all(x.map(async k=>{let K=await i.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[k]});return H(k,K)}));for(let k of Ae)if(k.agentId===p&&k.status===1){let K=k.principal+k.fee;L.push({loanId:k.loanId.toString(),agentId:k.agentId.toString(),sponsorId:k.sponsorId.toString(),principal:k.principal.toString(),fee:k.fee.toString(),due:K.toString(),dueAt:k.dueAt.toString(),issuedAt:k.issuedAt.toString(),owner:k.owner,token:z})}A={agentId:p.toString(),owner:q,delegate:Y,isAuthorizedController:Z,enrolled:b.enrolled,isRoot:b.isRoot,defaulted:b.defaulted,frozen:b.frozen,sponsorId:b.sponsor.toString(),delegatedIn:b.delegatedIn.toString(),delegatedOut:b.delegatedOut.toString(),principalOut:b.principalOut.toString(),availableCapacity:Ie.toString(),activeLoansCount:b.activeLoans.toString(),loansRepaid:b.loansRepaid.toString(),volumeRepaid:b.volumeRepaid.toString(),feesPaid:b.feesPaid.toString(),scorePoints:b.scorePoints.toString()}}let v=null;if(n.includeApiCheck){let P=p!==null?`agent=${p.toString()}`:`address=${d}`;v={...await re(e.http,`${Pe}?${P}`,{method:"GET"},te),grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:S,blockNumber:s.number?.toString()??null,blockTimestamp:s.timestamp.toString(),wallet:d,token:z,contracts:o,lender:{shares:a.toString(),grossAssets:y.toString(),earlyExitFeeAssets:I.toString(),netWithdrawAssets:O.toString(),lastDepositAt:u.toString(),withinMinHoldWindow:l,minHoldSeconds:Q.toString()},hasFundedLine:B,agentId:p!==null?p.toString():null,agent:A,activeLoans:L,lens:{address:o.lens,available:N,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:o.stockVault,borrowRoom:R,onchainAssetCount:h.length,hostedMcpStockCount:35,extraNonStockAsset:C($e),zeroCapAssets:De.map(P=>C(P)),caveat:"StockVault metadata is read-only status for already-funded lines (36 on-chain assets including PT-USDG-25MAR2027; CLSK and RGTI have lineCap=0), not an enrollment workflow."},apiCheck:v,limitations:["Borrowing and repayment require an already-funded ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet); Oak does not perform root staking, sponsorship, or credit-line enrollment.","Loan debt is fixed principal + quoteFee origination fee; variable interest is never invented.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}};async function T(n){U(n);let w=C(n),d=e.clientFor(S),[i,a]=await Promise.all([d.readContract({address:o.pool,abi:g,functionName:"shares",args:[w]}),ne(e,w)]),u=[];if(i>0n){let s=await d.readContract({address:o.pool,abi:g,functionName:"convertToAssets",args:[i]});u.push({module:"priors",id:`priors:lender:${w.toLowerCase()}`,chainId:S,assets:[{token:z,amount:s.toString()}],description:`Priors CreditPoolV2 lender position (${i} shares = ${e.formatAmount(s.toString(),$)} USDG gross).`})}for(let s of a){let h=await d.readContract({address:o.pool,abi:g,functionName:"loansOf",args:[s]}),y=await Promise.all(h.map(async l=>{let I=await d.readContract({address:o.pool,abi:g,functionName:"getLoan",args:[l]});return H(l,I)}));for(let l of y)if(l.agentId===s&&l.status===1){let I=l.principal+l.fee;u.push({module:"priors",id:`priors:loan:${l.loanId.toString()}`,chainId:S,assets:[{token:z,amount:I.toString()}],description:`Priors CreditPoolV2 active loan ${l.loanId} for agent ${s} (fixed due ${e.formatAmount(I.toString(),$)} USDG = ${l.principal} principal + ${l.fee} fee).`})}}return u}return{tools:[t,r,c,m,D],positions:T}},qe=Se,Te=e=>ie("priors",[Se(e)]),ze=Te;export{Pe as PRIORS_API_CHECK_URL,le as PRIORS_BPS_DENOMINATOR,o as PRIORS_CONTRACTS,de as PRIORS_EARLY_EXIT_FEE_BPS,ue as PRIORS_MAX_LOAN_USDG,pe as PRIORS_MAX_TERM_SECONDS,Q as PRIORS_MIN_HOLD_SECONDS,ce as PRIORS_MIN_LOAN_USDG,ee as PRIORS_MIN_TERM_SECONDS,z as PRIORS_USDG_TOKEN,Te as createModule,Se as createModulePart,ze as createPriorsModule,qe as createPriorsPart,Oe as recoverBorrowedLoanId};
@@ -1,2 +1,4 @@
1
+ import { type Address } from 'viem';
1
2
  import type { CreateModulePart } from '../../types.js';
3
+ export declare function relayOriginDepository(chainId: number): Address | undefined;
2
4
  export declare const createModulePart: CreateModulePart;
@@ -1 +1 @@
1
- import{a}from"../../../chunks/FSSCJNAQ.js";import"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import"../../../chunks/64EN6Y7E.js";import"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import"../../../chunks/25EOXUBI.js";import"../../../chunks/B5RZYFQC.js";import"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";export{a as createModulePart};
1
+ import{a,b}from"../../../chunks/SPAKOCR7.js";import"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import"../../../chunks/A5ITAEUQ.js";import"../../../chunks/I5CQ64EU.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";export{b as createModulePart,a as relayOriginDepository};
@@ -1 +1 @@
1
- import{a as r}from"../../../chunks/FSSCJNAQ.js";import{a as t}from"../../../chunks/75D6Q7L3.js";import"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import{b as o}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import"../../../chunks/25EOXUBI.js";import"../../../chunks/B5RZYFQC.js";import"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";var d=e=>o("relay",[t(e),r(e)]);export{d as createModule};
1
+ import{b as r}from"../../../chunks/SPAKOCR7.js";import{a as t}from"../../../chunks/OWEUVFB6.js";import"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MK6L6TGI.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import{b as o}from"../../../chunks/UCMNB2UP.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/A5ITAEUQ.js";import"../../../chunks/I5CQ64EU.js";import"../../../chunks/NA7HV7BR.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";var d=e=>o("relay",[t(e),r(e)]);export{d as createModule};
@@ -1 +1 @@
1
- import{a}from"../../../chunks/75D6Q7L3.js";import"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import"../../../chunks/25EOXUBI.js";import"../../../chunks/B5RZYFQC.js";import"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";export{a as createOutboundStatus};
1
+ import{a}from"../../../chunks/OWEUVFB6.js";import"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MK6L6TGI.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import"../../../chunks/A5ITAEUQ.js";import"../../../chunks/I5CQ64EU.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";export{a as createOutboundStatus};
@@ -1 +1 @@
1
- import{b as P}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import{a as T}from"../../../chunks/VZWOWR6G.js";import{a as h,d as D,i as $,j as b}from"../../../chunks/25EOXUBI.js";import{a as R}from"../../../chunks/B5RZYFQC.js";import{a as p}from"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";import{encodeFunctionData as A,erc20Abi as _,parseAbi as I}from"viem";var f=$[h].vaults.spark.address,n={address:b,chainId:h,symbol:"USDG",decimals:D},c={address:f,chainId:h,symbol:"spUSDG",decimals:6},M=1000000000000n,C=(1n<<256n)-1n,k=I(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function balanceOf(address owner) view returns (uint256)","function maxDeposit(address receiver) view returns (uint256)","function maxWithdraw(address owner) view returns (uint256)","function maxRedeem(address owner) view returns (uint256)","function previewDeposit(uint256 assets) view returns (uint256)","function previewWithdraw(uint256 assets) view returns (uint256)","function previewRedeem(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),t=(i,l)=>({token:{...i},amount:l.toString()});function y(i,l,v=!1){if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(S=>!l||S!=="amount"))throw new p(l?"Provide only the amount for this Spark action.":"Spark listing takes no arguments.");if(!l)return 0n;if(v&&i.amount==="max")return"max";if(typeof i.amount!="string")throw new p("Amount must be a positive integer string in base units.");let s=R(i.amount);if(s===0n||s>C)throw new p("Amount must be positive and within the uint256 range.");return s}var G=i=>{async function l(a){try{return await a()}catch(e){throw new p(i.plainError(e))}}async function v(a){T(a);let e=i.clientFor(h);if(await e.getChainId()!==h)throw new p("Spark requires an endpoint on chain 4663.");let[r,d,o]=await Promise.all([e.readContract({address:f,abi:k,functionName:"asset"}),e.readContract({address:f,abi:k,functionName:"decimals"}),e.readContract({address:b,abi:_,functionName:"decimals"})]);if(typeof r!="string"||r.toLowerCase()!==b.toLowerCase())throw new p("Spark does not report the expected USDG asset on chain 4663.");if(d!==c.decimals||o!==n.decimals)throw new p("Spark shares and USDG must both have 6 decimals.");return async(m,x=[])=>{let u=await e.readContract({address:f,abi:k,functionName:m,args:x});if(typeof u!="bigint"||u<0n||u>C)throw new p(`Spark returned an invalid ${m} value.`);return u}}function s(a){let e=a.amount.startsWith("-"),r=e?a.amount.slice(1):a.amount;return`${e?"-":""}${i.formatAmount(r,a.token.decimals)} ${a.token.symbol}`}async function S(a,e,r,d){let o=await i.preview(a,e),m=o.changes.map(s).join(", ");return{txs:a,amounts:r,preview:o,summary:`${d} Preview values can change before execution. ${o.summary}${m?` Changes: ${m}.`:""}`}}return{positions:a=>l(async()=>{let e=await v(a),r=await e("balanceOf",[a]);if(r===0n)return[];let[d,o,m]=await Promise.all([e("previewRedeem",[r]),e("maxRedeem",[a]),e("maxWithdraw",[a])]);return[{module:"spark",id:`${h}:${f}`,chainId:h,assets:[t(c,r)],description:`${s(t(c,r))}; redeem preview ${s(t(n,d))} (rounded down). Current maximum redeem ${s(t(c,o))}; maximum withdrawal ${s(t(n,m))}.`}]}),tools:[{name:"spark_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:(a,e)=>l(async()=>{y(a,!1);let r=await v(e),d=await r("totalAssets");if(d<M)return[];let[o,m,x,u,w]=await Promise.all([r("balanceOf",[e]),r("maxDeposit",[e]),r("maxWithdraw",[e]),r("maxRedeem",[e]),r("previewDeposit",[1000000n])]),g=await r("previewRedeem",[o]);return[{chainId:h,address:f,name:"Spark Savings USDG",asset:{...n},shareToken:{...c},totalAssets:t(n,d),balance:t(c,o),maxDeposit:t(n,m),maxWithdraw:t(n,x),maxRedeem:t(c,u),previewDepositAssets:t(n,1000000n),previewDeposit:t(c,w),previewRedeemShares:t(c,o),previewRedeem:t(n,g),rounding:"Deposit shares and redeemed assets round down; exact-asset withdrawals round shares up. Previews can change before execution."}]})},{name:"spark_deposit",inputSchema:{type:"object",properties:{amount:{type:"string",pattern:"^[0-9]+$",description:"Positive USDG base-unit integer (6 decimals)."}},required:["amount"],additionalProperties:!1},execute:(a,e)=>l(async()=>{let r=y(a,!0),d=await v(e),[o,m]=await Promise.all([d("maxDeposit",[e]),d("previewDeposit",[r])]);if(r>o)throw new p("The deposit exceeds Spark\u2019s current maximum deposit.");if(m===0n)throw new p("This deposit would return zero Spark shares.");let x=[i.approval(b,f,r.toString(),h),i.unsignedTx({to:f,data:A({abi:k,functionName:"deposit",args:[r,e]}),value:"0",chainId:h,description:`Deposit ${s(t(n,r))} into Spark for this wallet.`})];return S(x,e,{assets:t(n,r),shares:t(c,m),maxDeposit:t(n,o)},`Approve exactly ${s(t(n,r))} for Spark ${f}, then deposit. Expected ${s(t(c,m))}, rounded down; current maximum deposit ${s(t(n,o))}.`)})},{name:"spark_withdraw",inputSchema:{type:"object",properties:{amount:{type:"string",anyOf:[{pattern:"^[0-9]+$"},{const:"max"}],description:"Positive USDG base-unit integer (6 decimals), or max to redeem all held shares."}},required:["amount"],additionalProperties:!1},execute:(a,e)=>l(async()=>{let r=y(a,!0,!0),d=await v(e),[o,m,x]=await Promise.all([d("balanceOf",[e]),d("maxWithdraw",[e]),d("maxRedeem",[e])]);if(o===0n)throw new p("This wallet has no Spark shares to withdraw.");let u,w,g;if(r==="max"){if(w=o,w>x)throw new p("The full share balance exceeds Spark\u2019s current maximum redeem. Request an asset amount within the current maximum withdrawal.");u=await d("previewRedeem",[w]),g=A({abi:k,functionName:"redeem",args:[w,e,e]})}else{if(u=r,u>m)throw new p("The withdrawal exceeds Spark\u2019s current maximum withdrawal.");if(w=await d("previewWithdraw",[u]),w>o)throw new p("This wallet has insufficient Spark shares for the withdrawal.");g=A({abi:k,functionName:"withdraw",args:[u,e,e]})}if(u===0n||w===0n)throw new p("Spark returned a zero asset or share preview for this withdrawal.");let W=r==="max"?`Redeem all ${s(t(c,w))} from Spark to this wallet.`:`Withdraw ${s(t(n,u))} from Spark to this wallet.`,U=[i.unsignedTx({to:f,data:g,value:"0",chainId:h,description:W})];return S(U,e,{assets:t(n,u),shares:t(c,w),maxWithdraw:t(n,m),maxRedeem:t(c,x)},r==="max"?`Redeem all ${s(t(c,w))} for an expected ${s(t(n,u))}, rounded down. Current maximum redeem ${s(t(c,x))}.`:`Withdraw ${s(t(n,u))} using an expected ${s(t(c,w))}, rounded up. Current maximum withdrawal ${s(t(n,m))}.`)})}]}};function q(i){return P("spark",[G(i)])}export{q as createModule,G as createModulePart};
1
+ import{b as P}from"../../../chunks/UCMNB2UP.js";import"../../../chunks/Z25UKUJF.js";import{a as T}from"../../../chunks/A5ITAEUQ.js";import{a as R}from"../../../chunks/I5CQ64EU.js";import"../../../chunks/NA7HV7BR.js";import{a as h,d as D,i as $,j as b}from"../../../chunks/ZUC6ILK2.js";import{a as p}from"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";import{encodeFunctionData as A,erc20Abi as _,parseAbi as I}from"viem";var f=$[h].vaults.spark.address,n={address:b,chainId:h,symbol:"USDG",decimals:D},c={address:f,chainId:h,symbol:"spUSDG",decimals:6},M=1000000000000n,C=(1n<<256n)-1n,k=I(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function balanceOf(address owner) view returns (uint256)","function maxDeposit(address receiver) view returns (uint256)","function maxWithdraw(address owner) view returns (uint256)","function maxRedeem(address owner) view returns (uint256)","function previewDeposit(uint256 assets) view returns (uint256)","function previewWithdraw(uint256 assets) view returns (uint256)","function previewRedeem(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),t=(i,l)=>({token:{...i},amount:l.toString()});function y(i,l,v=!1){if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(S=>!l||S!=="amount"))throw new p(l?"Provide only the amount for this Spark action.":"Spark listing takes no arguments.");if(!l)return 0n;if(v&&i.amount==="max")return"max";if(typeof i.amount!="string")throw new p("Amount must be a positive integer string in base units.");let s=R(i.amount);if(s===0n||s>C)throw new p("Amount must be positive and within the uint256 range.");return s}var G=i=>{async function l(a){try{return await a()}catch(e){throw new p(i.plainError(e))}}async function v(a){T(a);let e=i.clientFor(h);if(await e.getChainId()!==h)throw new p("Spark requires an endpoint on chain 4663.");let[r,d,o]=await Promise.all([e.readContract({address:f,abi:k,functionName:"asset"}),e.readContract({address:f,abi:k,functionName:"decimals"}),e.readContract({address:b,abi:_,functionName:"decimals"})]);if(typeof r!="string"||r.toLowerCase()!==b.toLowerCase())throw new p("Spark does not report the expected USDG asset on chain 4663.");if(d!==c.decimals||o!==n.decimals)throw new p("Spark shares and USDG must both have 6 decimals.");return async(m,x=[])=>{let u=await e.readContract({address:f,abi:k,functionName:m,args:x});if(typeof u!="bigint"||u<0n||u>C)throw new p(`Spark returned an invalid ${m} value.`);return u}}function s(a){let e=a.amount.startsWith("-"),r=e?a.amount.slice(1):a.amount;return`${e?"-":""}${i.formatAmount(r,a.token.decimals)} ${a.token.symbol}`}async function S(a,e,r,d){let o=await i.preview(a,e),m=o.changes.map(s).join(", ");return{txs:a,amounts:r,preview:o,summary:`${d} Preview values can change before execution. ${o.summary}${m?` Changes: ${m}.`:""}`}}return{positions:a=>l(async()=>{let e=await v(a),r=await e("balanceOf",[a]);if(r===0n)return[];let[d,o,m]=await Promise.all([e("previewRedeem",[r]),e("maxRedeem",[a]),e("maxWithdraw",[a])]);return[{module:"spark",id:`${h}:${f}`,chainId:h,assets:[t(c,r)],description:`${s(t(c,r))}; redeem preview ${s(t(n,d))} (rounded down). Current maximum redeem ${s(t(c,o))}; maximum withdrawal ${s(t(n,m))}.`}]}),tools:[{name:"spark_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:(a,e)=>l(async()=>{y(a,!1);let r=await v(e),d=await r("totalAssets");if(d<M)return[];let[o,m,x,u,w]=await Promise.all([r("balanceOf",[e]),r("maxDeposit",[e]),r("maxWithdraw",[e]),r("maxRedeem",[e]),r("previewDeposit",[1000000n])]),g=await r("previewRedeem",[o]);return[{chainId:h,address:f,name:"Spark Savings USDG",asset:{...n},shareToken:{...c},totalAssets:t(n,d),balance:t(c,o),maxDeposit:t(n,m),maxWithdraw:t(n,x),maxRedeem:t(c,u),previewDepositAssets:t(n,1000000n),previewDeposit:t(c,w),previewRedeemShares:t(c,o),previewRedeem:t(n,g),rounding:"Deposit shares and redeemed assets round down; exact-asset withdrawals round shares up. Previews can change before execution."}]})},{name:"spark_deposit",inputSchema:{type:"object",properties:{amount:{type:"string",pattern:"^[0-9]+$",description:"Positive USDG base-unit integer (6 decimals)."}},required:["amount"],additionalProperties:!1},execute:(a,e)=>l(async()=>{let r=y(a,!0),d=await v(e),[o,m]=await Promise.all([d("maxDeposit",[e]),d("previewDeposit",[r])]);if(r>o)throw new p("The deposit exceeds Spark\u2019s current maximum deposit.");if(m===0n)throw new p("This deposit would return zero Spark shares.");let x=[i.approval(b,f,r.toString(),h),i.unsignedTx({to:f,data:A({abi:k,functionName:"deposit",args:[r,e]}),value:"0",chainId:h,description:`Deposit ${s(t(n,r))} into Spark for this wallet.`})];return S(x,e,{assets:t(n,r),shares:t(c,m),maxDeposit:t(n,o)},`Approve exactly ${s(t(n,r))} for Spark ${f}, then deposit. Expected ${s(t(c,m))}, rounded down; current maximum deposit ${s(t(n,o))}.`)})},{name:"spark_withdraw",inputSchema:{type:"object",properties:{amount:{type:"string",anyOf:[{pattern:"^[0-9]+$"},{const:"max"}],description:"Positive USDG base-unit integer (6 decimals), or max to redeem all held shares."}},required:["amount"],additionalProperties:!1},execute:(a,e)=>l(async()=>{let r=y(a,!0,!0),d=await v(e),[o,m,x]=await Promise.all([d("balanceOf",[e]),d("maxWithdraw",[e]),d("maxRedeem",[e])]);if(o===0n)throw new p("This wallet has no Spark shares to withdraw.");let u,w,g;if(r==="max"){if(w=o,w>x)throw new p("The full share balance exceeds Spark\u2019s current maximum redeem. Request an asset amount within the current maximum withdrawal.");u=await d("previewRedeem",[w]),g=A({abi:k,functionName:"redeem",args:[w,e,e]})}else{if(u=r,u>m)throw new p("The withdrawal exceeds Spark\u2019s current maximum withdrawal.");if(w=await d("previewWithdraw",[u]),w>o)throw new p("This wallet has insufficient Spark shares for the withdrawal.");g=A({abi:k,functionName:"withdraw",args:[u,e,e]})}if(u===0n||w===0n)throw new p("Spark returned a zero asset or share preview for this withdrawal.");let W=r==="max"?`Redeem all ${s(t(c,w))} from Spark to this wallet.`:`Withdraw ${s(t(n,u))} from Spark to this wallet.`,U=[i.unsignedTx({to:f,data:g,value:"0",chainId:h,description:W})];return S(U,e,{assets:t(n,u),shares:t(c,w),maxWithdraw:t(n,m),maxRedeem:t(c,x)},r==="max"?`Redeem all ${s(t(c,w))} for an expected ${s(t(n,u))}, rounded down. Current maximum redeem ${s(t(c,x))}.`:`Withdraw ${s(t(n,u))} using an expected ${s(t(c,w))}, rounded up. Current maximum withdrawal ${s(t(n,m))}.`)})}]}};function q(i){return P("spark",[G(i)])}export{q as createModule,G as createModulePart};
@@ -1 +1 @@
1
- import{b as $}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import{a as b}from"../../../chunks/VZWOWR6G.js";import{a as r,d as T,i as D,j as p}from"../../../chunks/25EOXUBI.js";import{a as C}from"../../../chunks/B5RZYFQC.js";import{a as i}from"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";import{encodeFunctionData as S,erc20Abi as v,parseAbi as I}from"viem";var o=D[r].vaults.steakhouse.address,N=1000000000000n,G=(1n<<256n)-1n,h=I(["function asset() view returns (address)","function totalAssets() view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256 assets)","function previewWithdraw(uint256 assets) view returns (uint256 shares)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]);function g(e){if(typeof e!="bigint"||e<0n||e>G)throw new i("The vault returned an invalid base-unit amount.");return e}function U(e){if(typeof e!="string")throw new i("Amount must be an integer string in base units.");let c=C(e);if(c===0n)throw new i("Amount must be positive.");if(c>G)throw new i("Amount exceeds the uint256 range.");return c}function y(e,c){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(l=>!c||l!=="amount"))throw new i("Unexpected Steakhouse argument.")}var x=e=>{async function c(s){try{return await s()}catch(t){throw new i(e.plainError(t))}}async function l(){let s=e.clientFor(r);if(await s.getChainId()!==r)throw new i("Steakhouse requires chain 4663.");let t=await s.readContract({address:o,abi:h,functionName:"asset"});if(typeof t!="string"||t.toLowerCase()!==p.toLowerCase())throw new i("The Steakhouse vault asset does not match USDG on chain 4663.");let[a,n]=await Promise.all([s.readContract({address:p,abi:v,functionName:"decimals"}),s.readContract({address:o,abi:v,functionName:"decimals"})]);if(a!==T||!Number.isInteger(n)||n<0||n>255)throw new i("The vault returned invalid asset or share decimals.");return{client:s,asset:{address:p,symbol:"USDG",decimals:a,chainId:r},shares:{address:o,symbol:"steakUSDG",decimals:n,chainId:r}}}async function A(s,t){return g(await s.readContract({address:o,abi:v,functionName:"balanceOf",args:[t]}))}async function k(s,t,a){let n=await e.preview(s,t);if(n.changes.length===0)throw new i("The Steakhouse simulation returned no token balance changes.");let u=n.changes.map(({token:d,amount:m})=>{let f=m.startsWith("-"),w=e.formatAmount(f?m.slice(1):m,d.decimals);return`${f?"-":""}${w} ${d.symbol} (${d.address}, chain ${d.chainId}, decimals ${d.decimals})`});return{txs:s,summary:`${a} ${n.summary} Changes: ${u.join("; ")}.`}}return{tools:[{name:"steakhouse_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async s=>c(async()=>{y(s,!1);let{client:t,asset:a,shares:n}=await l(),u=g(await t.readContract({address:o,abi:h,functionName:"totalAssets"}));return u<N?[]:[{name:"Steakhouse USDG",vault:n,asset:a,totalAssets:{token:a,amount:u.toString()}}]})},{name:"steakhouse_deposit",inputSchema:P(!1),execute:async(s,t)=>c(async()=>{y(s,!0);let a=U(s.amount);b(t);let{asset:n}=await l(),u=[e.approval(n.address,o,a.toString(),r),e.unsignedTx({to:o,data:S({abi:h,functionName:"deposit",args:[a,t]}),value:"0",chainId:r,description:`Deposit ${e.formatAmount(a.toString(),n.decimals)} USDG into Steakhouse.`})];return k(u,t,"Approve the exact USDG amount, then deposit into Steakhouse.")})},{name:"steakhouse_withdraw",inputSchema:P(!0),execute:async(s,t)=>c(async()=>{y(s,!0);let a=s.amount==="max"?null:U(s.amount);b(t);let{client:n,asset:u,shares:d}=await l(),m=await A(n,t);if(m===0n)throw new i("The wallet has no Steakhouse shares to withdraw.");let f;if(a===null)f=e.unsignedTx({to:o,data:S({abi:h,functionName:"redeem",args:[m,t,t]}),value:"0",chainId:r,description:`Redeem all ${e.formatAmount(m.toString(),d.decimals)} steakUSDG shares.`});else{let w=g(await n.readContract({address:o,abi:h,functionName:"previewWithdraw",args:[a]}));if(w===0n||w>m)throw new i("The withdrawal exceeds the available share balance or has an invalid share quote.");f=e.unsignedTx({to:o,data:S({abi:h,functionName:"withdraw",args:[a,t,t]}),value:"0",chainId:r,description:`Withdraw ${e.formatAmount(a.toString(),u.decimals)} USDG from Steakhouse.`})}return k([f],t,a===null?"Redeem the current full share balance from Steakhouse.":"Withdraw the requested USDG amount from Steakhouse.")})}],positions:s=>c(async()=>{b(s);let{client:t,asset:a,shares:n}=await l(),u=await A(t,s);if(u===0n)return[];let d=g(await t.readContract({address:o,abi:h,functionName:"convertToAssets",args:[u]}));return[{module:"steakhouse",id:`${r}:${o.toLowerCase()}`,chainId:r,assets:[{token:a,amount:d.toString()}],description:`${e.formatAmount(u.toString(),n.decimals)} steakUSDG shares (${o}, chain ${r}, decimals ${n.decimals}); USDG conversion is indicative, not guaranteed exit liquidity.`}]})}};function P(e){return{type:"object",additionalProperties:!1,required:["amount"],properties:{amount:{type:"string",pattern:e?"^(?:[0-9]+|max)$":"^[0-9]+$",description:`USDG base-unit integer string (6 decimals)${e?", or max to redeem every share":""}.`}}}}var L=e=>$("steakhouse",[x(e)]);export{L as createModule,x as createModulePart};
1
+ import{b as $}from"../../../chunks/UCMNB2UP.js";import"../../../chunks/Z25UKUJF.js";import{a as b}from"../../../chunks/A5ITAEUQ.js";import{a as C}from"../../../chunks/I5CQ64EU.js";import"../../../chunks/NA7HV7BR.js";import{a as r,d as T,i as D,j as p}from"../../../chunks/ZUC6ILK2.js";import{a as i}from"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";import{encodeFunctionData as S,erc20Abi as v,parseAbi as I}from"viem";var o=D[r].vaults.steakhouse.address,N=1000000000000n,G=(1n<<256n)-1n,h=I(["function asset() view returns (address)","function totalAssets() view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256 assets)","function previewWithdraw(uint256 assets) view returns (uint256 shares)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]);function g(e){if(typeof e!="bigint"||e<0n||e>G)throw new i("The vault returned an invalid base-unit amount.");return e}function U(e){if(typeof e!="string")throw new i("Amount must be an integer string in base units.");let c=C(e);if(c===0n)throw new i("Amount must be positive.");if(c>G)throw new i("Amount exceeds the uint256 range.");return c}function y(e,c){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(l=>!c||l!=="amount"))throw new i("Unexpected Steakhouse argument.")}var x=e=>{async function c(s){try{return await s()}catch(t){throw new i(e.plainError(t))}}async function l(){let s=e.clientFor(r);if(await s.getChainId()!==r)throw new i("Steakhouse requires chain 4663.");let t=await s.readContract({address:o,abi:h,functionName:"asset"});if(typeof t!="string"||t.toLowerCase()!==p.toLowerCase())throw new i("The Steakhouse vault asset does not match USDG on chain 4663.");let[a,n]=await Promise.all([s.readContract({address:p,abi:v,functionName:"decimals"}),s.readContract({address:o,abi:v,functionName:"decimals"})]);if(a!==T||!Number.isInteger(n)||n<0||n>255)throw new i("The vault returned invalid asset or share decimals.");return{client:s,asset:{address:p,symbol:"USDG",decimals:a,chainId:r},shares:{address:o,symbol:"steakUSDG",decimals:n,chainId:r}}}async function A(s,t){return g(await s.readContract({address:o,abi:v,functionName:"balanceOf",args:[t]}))}async function k(s,t,a){let n=await e.preview(s,t);if(n.changes.length===0)throw new i("The Steakhouse simulation returned no token balance changes.");let u=n.changes.map(({token:d,amount:m})=>{let f=m.startsWith("-"),w=e.formatAmount(f?m.slice(1):m,d.decimals);return`${f?"-":""}${w} ${d.symbol} (${d.address}, chain ${d.chainId}, decimals ${d.decimals})`});return{txs:s,summary:`${a} ${n.summary} Changes: ${u.join("; ")}.`}}return{tools:[{name:"steakhouse_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async s=>c(async()=>{y(s,!1);let{client:t,asset:a,shares:n}=await l(),u=g(await t.readContract({address:o,abi:h,functionName:"totalAssets"}));return u<N?[]:[{name:"Steakhouse USDG",vault:n,asset:a,totalAssets:{token:a,amount:u.toString()}}]})},{name:"steakhouse_deposit",inputSchema:P(!1),execute:async(s,t)=>c(async()=>{y(s,!0);let a=U(s.amount);b(t);let{asset:n}=await l(),u=[e.approval(n.address,o,a.toString(),r),e.unsignedTx({to:o,data:S({abi:h,functionName:"deposit",args:[a,t]}),value:"0",chainId:r,description:`Deposit ${e.formatAmount(a.toString(),n.decimals)} USDG into Steakhouse.`})];return k(u,t,"Approve the exact USDG amount, then deposit into Steakhouse.")})},{name:"steakhouse_withdraw",inputSchema:P(!0),execute:async(s,t)=>c(async()=>{y(s,!0);let a=s.amount==="max"?null:U(s.amount);b(t);let{client:n,asset:u,shares:d}=await l(),m=await A(n,t);if(m===0n)throw new i("The wallet has no Steakhouse shares to withdraw.");let f;if(a===null)f=e.unsignedTx({to:o,data:S({abi:h,functionName:"redeem",args:[m,t,t]}),value:"0",chainId:r,description:`Redeem all ${e.formatAmount(m.toString(),d.decimals)} steakUSDG shares.`});else{let w=g(await n.readContract({address:o,abi:h,functionName:"previewWithdraw",args:[a]}));if(w===0n||w>m)throw new i("The withdrawal exceeds the available share balance or has an invalid share quote.");f=e.unsignedTx({to:o,data:S({abi:h,functionName:"withdraw",args:[a,t,t]}),value:"0",chainId:r,description:`Withdraw ${e.formatAmount(a.toString(),u.decimals)} USDG from Steakhouse.`})}return k([f],t,a===null?"Redeem the current full share balance from Steakhouse.":"Withdraw the requested USDG amount from Steakhouse.")})}],positions:s=>c(async()=>{b(s);let{client:t,asset:a,shares:n}=await l(),u=await A(t,s);if(u===0n)return[];let d=g(await t.readContract({address:o,abi:h,functionName:"convertToAssets",args:[u]}));return[{module:"steakhouse",id:`${r}:${o.toLowerCase()}`,chainId:r,assets:[{token:a,amount:d.toString()}],description:`${e.formatAmount(u.toString(),n.decimals)} steakUSDG shares (${o}, chain ${r}, decimals ${n.decimals}); USDG conversion is indicative, not guaranteed exit liquidity.`}]})}};function P(e){return{type:"object",additionalProperties:!1,required:["amount"],properties:{amount:{type:"string",pattern:e?"^(?:[0-9]+|max)$":"^[0-9]+$",description:`USDG base-unit integer string (6 decimals)${e?", or max to redeem every share":""}.`}}}}var L=e=>$("steakhouse",[x(e)]);export{L as createModule,x as createModulePart};
@@ -1 +1 @@
1
- import{i as oe}from"../../../chunks/VZPFBWVH.js";import"../../../chunks/MGEJPRXP.js";import"../../../chunks/ZKOMJGNH.js";import"../../../chunks/YTHDLCHL.js";import"../../../chunks/KFMNCJXJ.js";import"../../../chunks/6YU3JLQQ.js";import"../../../chunks/D45AODDL.js";import"../../../chunks/24JYIH53.js";import{o as M}from"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import{c as re}from"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import{b as ie}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import{a as _}from"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import{a as w,d as P,i as V}from"../../../chunks/25EOXUBI.js";import{a as te,b as E}from"../../../chunks/B5RZYFQC.js";import{a as m}from"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";import{decodeFunctionData as ye,encodeFunctionData as j,erc20Abi as be,getAddress as Ae,parseAbi as Ie}from"viem";var Be="https://api.tickerspring.com",C=V[w].tickerSpring.limitOrderHook.address,S={address:Ae(V[w].tokens.USDG.address),symbol:"USDG",decimals:P,chainId:w},se=10000000n,ae="(bytes32 pool,int24 lower,bool sell0,address inputToken,uint128 maximumInput,uint128 maximumCorrectionInput,uint256 minimumFullOutput,uint16 maximumFeeBps,uint64 deadline)",U=Ie([`function create(${ae} params)`,`function createMarketOrder(${ae} params,address token,uint160 initialPrice,uint160 minimumPrice,uint160 maximumPrice)`,"function cancel(uint256 id,uint256 min0,uint256 min1,uint64 deadline,uint8 deliveryMask)","function claimBoth(uint256 id)"]),F={type:"string",pattern:"^\\d+$"},Te={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"};function k(e){return(!e||typeof e!="object"||Array.isArray(e))&&c(),e}function c(){throw new m("TickerSpring returned an incomplete or inconsistent response.")}function b(e){return(typeof e!="string"||!e.trim())&&c(),e}function R(e){if(typeof e!="string")throw new m("Provide a valid token or wallet address.");return _(e),e}function f(e,n){return typeof e=="string"&&e.toLowerCase()===n.toLowerCase()}function A(e){if(typeof e!="string")throw new m("Amount must be a non-negative integer string in base units.");return te(e),e}function O(e){let n=A(e);if(BigInt(n)<=0n)throw new m("The amount must be positive.");return n}function de(e){let n=typeof e=="number"&&Number.isFinite(e)?String(e):e;if(typeof n!="string"||!/^\d+(\.\d+)?$/.test(n)||!/[1-9]/.test(n))throw new m("TickerSpring requires a positive decimal price in USDG per token.");return n}function me(e){let n=k(e);return(typeof n.decimals!="number"||!Number.isInteger(n.decimals)||n.decimals<0||n.decimals>255||n.chainId!==void 0&&n.chainId!==w)&&c(),{address:R(n.address),symbol:b(n.symbol),decimals:n.decimals,chainId:w}}function Q(e){let n=O(e);if(BigInt(n)<=BigInt(Math.floor(Date.now()/1e3)))throw new m("The prepared TickerSpring order has expired. Prepare it again.");return n}function J(e,n){if(Object.keys(e).some(i=>!n.includes(i)))throw new m("Provide only the documented TickerSpring inputs.")}async function N(e,n,i){let r=await re(e.http,`${Be}${n}`,{method:i?"POST":"GET",headers:{"Content-Type":"application/json","User-Agent":"Oak-TickerSpring/1.0"},...i?{body:JSON.stringify(i)}:{}},t=>!!t&&typeof t=="object"&&!Array.isArray(t));return k(r.data)}function le(e,n,i,r){let t=k(n.bundle),o=k(n.walletSendCalls);(t.kind!==r||t.chainId!==w||!f(t.owner,i)||o.chainId!=="0x1237"||!f(o.from,i)||!Array.isArray(t.steps)||!t.steps.length||!Array.isArray(o.calls)||o.calls.length!==t.steps.length)&&c();let u=b(t.expiresAt);if(!Number.isFinite(Date.parse(u))||Date.parse(u)<=Date.now())throw new m("The prepared TickerSpring bundle has expired. Prepare it again.");let s=t.steps.map((h,l)=>{let a=k(h),d=k(o.calls[l]);return(a.n!==l+1||a.kind!=="approve"&&a.kind!=="call"||a.from!==void 0&&!f(a.from,i)||a.chainId!==void 0&&a.chainId!==w||!f(d.to,b(a.to))||d.data!==a.data||a.value!=="0"||d.value!=="0x0")&&c(),e.unsignedTx({to:R(a.to),data:b(a.data),value:A(a.value),chainId:w,description:b(a.label)})});return{bundle:t,txs:s,expiresAt:u}}async function H(e,n,i,r={}){let{bundle:t,txs:o,expiresAt:u}=n,s=await e.preview(o,i);if(Date.parse(u)<=Date.now())throw new m("The prepared TickerSpring bundle expired during preview. Prepare it again.");r.deadline!==void 0&&Q(r.deadline);let h=s.changes.map(({token:d,amount:I})=>{let y=I.startsWith("-");return`${y?"-":""}${e.formatAmount(y?I.slice(1):I,d.decimals)} ${d.symbol} (${d.address}, chain ${d.chainId})`});(!Array.isArray(t.warnings)||!t.warnings.every(d=>typeof d=="string"))&&c();let l=t.simulation===void 0?void 0:k(t.simulation),a=l?.ok===!1?`API simulation: ${b(l.error)}.`:"";return{txs:o,from:i,expiresAt:u,...r,preview:s,summary:[b(t.summary),"Protocol minimum: 10 USDG. Fill fee: 2.5% of received tokens; no placement or unfilled cancellation fee.","Filled proceeds require tickerspring_claim (claimBoth). No transaction has been sent.",...t.warnings,a,s.summary,...h].filter(Boolean).join(" ")}}async function Se(e,n,i){J(n,["token","side","amount","price","slippageBps","minAmountOut"]);let r=R(n.token),t=O(n.amount),o=de(b(n.price)),u=n.slippageBps===void 0?500:n.slippageBps;M("1",u);let s=n.minAmountOut===void 0?0n:BigInt(O(n.minAmountOut));if(n.minAmountOut!==void 0&&s<=1n)throw new m("The minimum output amount must be greater than 1 base unit.");if(n.side!=="buy"&&n.side!=="sell")throw new m("Choose buy or sell for the limit order.");if(n.side==="buy"&&BigInt(t)<se)throw new m("TickerSpring orders require at least 10 USDG.");let h=await N(e,"/v1/tokens");Array.isArray(h.tokens)||c();let l=h.tokens.map(k).filter(g=>f(g.address,r)&&(g.chainId===void 0||g.chainId===w));if(l.length!==1)throw new m("TickerSpring did not return a unique token for that address on chain 4663.");let a=l[0],d=me(a);if(f(d.address,S.address))throw new m("Choose the order token paired with USDG.");let I=k(a.markets);typeof I.limitOrders!="boolean"&&c();let y=n.side==="buy"?S:d,D=n.side==="buy"?d:S;if(n.side==="sell"){let g=BigInt(E(o,18,"floor"));if(BigInt(t)*g*10n**BigInt(P)/(10n**BigInt(d.decimals)*10n**18n)<se)throw new m("TickerSpring orders require at least 10 USDG at the limit price.")}let pe=await N(e,"/v1/agent/prepare/limit-order",{owner:i,token:r,side:n.side,price:o,amount:e.formatAmount(t,y.decimals),...I.limitOrders?{}:{startingPrice:de(a.priceUsd)}}),x=le(e,pe,i,"limit-order"),T=k(x.bundle.params),p=k(T.create),W=Q(p.deadline),$=O(p.minimumFullOutput);(!f(T.hook,C)||!f(p.inputToken,y.address)||A(p.maximumInput)!==t||p.maximumFeeBps!==250||typeof p.sell0!="boolean"||typeof p.lower!="number"||!Number.isInteger(p.lower)||typeof p.pool!="string"||!/^0x[0-9a-fA-F]{64}$/.test(p.pool)||BigInt(A(p.maximumCorrectionInput))>BigInt(t))&&c();let fe=BigInt(y.address)<BigInt(D.address);p.sell0!==fe&&c();let v=BigInt(t)*9750n/10000n,q=BigInt(E(o,18,"floor")),ge=n.side==="buy"?q>0n?v*10n**BigInt(d.decimals)*10n**18n/(10n**BigInt(P)*q):0n:v*q*10n**BigInt(P)/(10n**BigInt(d.decimals)*10n**18n),z=BigInt(M(ge.toString(),u)),K=oe(p.lower),G=K*K,X=1n<<192n,ke=G>0n?p.sell0?v*G/X:v*X/G:0n,he=d.decimals===18?BigInt(M(ke.toString(),u)):z,we=[s,z,he].reduce((g,B)=>g>B?g:B,0n);if(BigInt($)<=1n||BigInt($)<we)throw new m("TickerSpring minimum output is below the quoted slippage minimum.");let Y={pool:p.pool,lower:p.lower,sell0:p.sell0,inputToken:y.address,maximumInput:BigInt(t),maximumCorrectionInput:BigInt(A(p.maximumCorrectionInput)),minimumFullOutput:BigInt($),maximumFeeBps:250,deadline:BigInt(W)},L;if(I.limitOrders)L=j({abi:U,functionName:"create",args:[Y]});else{let g=k(T.market);f(g.token,d.address)||c();let B=BigInt(O(g.initialPrice)),ee=BigInt(O(g.minimumPrice)),ne=BigInt(O(g.maximumPrice));(B<ee||B>ne)&&c(),L=j({abi:U,functionName:"createMarketOrder",args:[Y,d.address,B,ee,ne]})}if((!Array.isArray(T.approvals)||T.approvals.length>1||x.txs.length!==T.approvals.length+1)&&c(),T.approvals.length){let g=k(T.approvals[0]),B=j({abi:be,functionName:"approve",args:[C,BigInt(t)]});(!f(g.token,y.address)||!f(g.spender,C)||A(g.amount)!==t||!f(x.txs[0].to,y.address)||x.txs[0].data.toLowerCase()!==B.toLowerCase())&&c()}let Z=x.txs.at(-1);return(!f(Z.to,C)||Z.data.toLowerCase()!==L.toLowerCase())&&c(),H(e,x,i,{input:{token:y,amount:t},minimumOutput:{token:D,amount:$},deadline:W})}async function ue(e,n,i,r){J(n,["id"]);let t=A(n.id),o=await N(e,"/v1/agent/prepare/order-action",{owner:i,id:t,action:r}),u=le(e,o,i,"order-action");(u.txs.length!==1||!f(u.txs[0].to,C))&&c();let s=ye({abi:U,data:u.txs[0].data});if((s.functionName!==r||s.args[0]!==BigInt(t))&&c(),s.functionName==="cancel"){let[,h,l,a,d]=s.args;if(Q(a.toString()),h+l===0n||d!==3)throw new m("TickerSpring returned a cancellation without protected amounts or both token deliveries. Prepare it again.");return H(e,u,i,{id:t,deadline:a.toString()})}return u.txs[0].data.toLowerCase()!==j({abi:U,functionName:"claimBoth",args:[BigInt(t)]}).toLowerCase()&&c(),H(e,u,i,{id:t})}async function ce(e,n){let i=await N(e,`/v1/agent/accounts/${n}`);if(!f(i.owner,n)||i.limitOrdersComplete!==!0||!Array.isArray(i.limitOrders)||!Array.isArray(i.unavailable)||i.unavailable.length)throw new m("TickerSpring could not return the complete order list for this wallet.");let r=b(i.asOf);Number.isFinite(Date.parse(r))||c();let t=new Set,o=i.limitOrders.map(u=>{let s=k(u),h=k(s.order),l=me(s.token);(!f(s.hook,C)||!f(h.owner,n)||s.side!=="buy"&&s.side!=="sell"||f(l.address,S.address)||s.feeBps!==250)&&c();let a=A(s.id);t.has(a)&&c(),t.add(a);let d=BigInt(l.address)<BigInt(S.address)?[l,S]:[S,l],I=k(s.claimable);return{id:a,status:b(s.status),side:s.side,chainId:w,feeBps:250,input:{token:s.side==="buy"?S:l,amount:A(h.debit)},claimable:d.map((y,D)=>({token:y,amount:A(I[D===0?"net0":"net1"])}))}});return{owner:n,chainId:w,asOf:r,orders:o}}var Oe=e=>{let n=r=>async t=>{try{return _(t),await r(t)}catch(o){throw new m(e.plainError(o))}},i=(r,t,o,u)=>({name:`tickerspring_${r}`,inputSchema:{type:"object",properties:t,required:o,additionalProperties:!1},execute:(s,h)=>n(l=>u(s,l))(h)});return{tools:[i("create",{token:Te,side:{type:"string",enum:["buy","sell"]},amount:{...F,description:"Base units of USDG for buys, or the selected token for sells."},price:{type:"string",pattern:"^\\d+(\\.\\d+)?$",description:"Limit price in USDG per whole token."},slippageBps:{type:"integer",minimum:0,maximum:9999},minAmountOut:{...F,description:"Optional caller minimum output in base units."}},["token","side","amount","price"],(r,t)=>Se(e,r,t)),i("cancel",{id:F},["id"],(r,t)=>ue(e,r,t,"cancel")),i("claim",{id:F},["id"],(r,t)=>ue(e,r,t,"claimBoth")),i("orders",{},[],(r,t)=>(J(r,[]),ce(e,t)))],positions:n(async r=>(await ce(e,r)).orders.map(o=>({module:"tickerspring",id:o.id,chainId:w,assets:o.claimable,description:`${o.side} order ${o.id}: ${o.status}; assets are claimable amounts only. Original input: ${e.formatAmount(o.input.amount,o.input.token.decimals)} ${o.input.token.symbol} (${o.input.token.address}). Fill fee 2.5%; use tickerspring_claim for proceeds.`})))}},Ue=e=>ie("tickerspring",[Oe(e)]);export{Ue as createModule,Oe as createModulePart};
1
+ import{i as oe}from"../../../chunks/SJ7HDRI4.js";import"../../../chunks/6SYTB6FB.js";import"../../../chunks/52TGAWSI.js";import"../../../chunks/3PA2XT75.js";import"../../../chunks/MOVRI5IV.js";import"../../../chunks/YX4NVVSX.js";import"../../../chunks/BHR46XNW.js";import"../../../chunks/73EABRFC.js";import{o as M}from"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import{c as re}from"../../../chunks/MK6L6TGI.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import{b as ie}from"../../../chunks/UCMNB2UP.js";import"../../../chunks/Z25UKUJF.js";import{a as _}from"../../../chunks/A5ITAEUQ.js";import{a as te,b as E}from"../../../chunks/I5CQ64EU.js";import"../../../chunks/NA7HV7BR.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import{a as w,d as P,i as V}from"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import{a as m}from"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";import{decodeFunctionData as ye,encodeFunctionData as j,erc20Abi as be,getAddress as Ae,parseAbi as Ie}from"viem";var Be="https://api.tickerspring.com",C=V[w].tickerSpring.limitOrderHook.address,S={address:Ae(V[w].tokens.USDG.address),symbol:"USDG",decimals:P,chainId:w},se=10000000n,ae="(bytes32 pool,int24 lower,bool sell0,address inputToken,uint128 maximumInput,uint128 maximumCorrectionInput,uint256 minimumFullOutput,uint16 maximumFeeBps,uint64 deadline)",U=Ie([`function create(${ae} params)`,`function createMarketOrder(${ae} params,address token,uint160 initialPrice,uint160 minimumPrice,uint160 maximumPrice)`,"function cancel(uint256 id,uint256 min0,uint256 min1,uint64 deadline,uint8 deliveryMask)","function claimBoth(uint256 id)"]),F={type:"string",pattern:"^\\d+$"},Te={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"};function k(e){return(!e||typeof e!="object"||Array.isArray(e))&&c(),e}function c(){throw new m("TickerSpring returned an incomplete or inconsistent response.")}function b(e){return(typeof e!="string"||!e.trim())&&c(),e}function R(e){if(typeof e!="string")throw new m("Provide a valid token or wallet address.");return _(e),e}function f(e,n){return typeof e=="string"&&e.toLowerCase()===n.toLowerCase()}function A(e){if(typeof e!="string")throw new m("Amount must be a non-negative integer string in base units.");return te(e),e}function O(e){let n=A(e);if(BigInt(n)<=0n)throw new m("The amount must be positive.");return n}function de(e){let n=typeof e=="number"&&Number.isFinite(e)?String(e):e;if(typeof n!="string"||!/^\d+(\.\d+)?$/.test(n)||!/[1-9]/.test(n))throw new m("TickerSpring requires a positive decimal price in USDG per token.");return n}function me(e){let n=k(e);return(typeof n.decimals!="number"||!Number.isInteger(n.decimals)||n.decimals<0||n.decimals>255||n.chainId!==void 0&&n.chainId!==w)&&c(),{address:R(n.address),symbol:b(n.symbol),decimals:n.decimals,chainId:w}}function Q(e){let n=O(e);if(BigInt(n)<=BigInt(Math.floor(Date.now()/1e3)))throw new m("The prepared TickerSpring order has expired. Prepare it again.");return n}function J(e,n){if(Object.keys(e).some(i=>!n.includes(i)))throw new m("Provide only the documented TickerSpring inputs.")}async function N(e,n,i){let r=await re(e.http,`${Be}${n}`,{method:i?"POST":"GET",headers:{"Content-Type":"application/json","User-Agent":"Oak-TickerSpring/1.0"},...i?{body:JSON.stringify(i)}:{}},t=>!!t&&typeof t=="object"&&!Array.isArray(t));return k(r.data)}function le(e,n,i,r){let t=k(n.bundle),o=k(n.walletSendCalls);(t.kind!==r||t.chainId!==w||!f(t.owner,i)||o.chainId!=="0x1237"||!f(o.from,i)||!Array.isArray(t.steps)||!t.steps.length||!Array.isArray(o.calls)||o.calls.length!==t.steps.length)&&c();let u=b(t.expiresAt);if(!Number.isFinite(Date.parse(u))||Date.parse(u)<=Date.now())throw new m("The prepared TickerSpring bundle has expired. Prepare it again.");let s=t.steps.map((h,l)=>{let a=k(h),d=k(o.calls[l]);return(a.n!==l+1||a.kind!=="approve"&&a.kind!=="call"||a.from!==void 0&&!f(a.from,i)||a.chainId!==void 0&&a.chainId!==w||!f(d.to,b(a.to))||d.data!==a.data||a.value!=="0"||d.value!=="0x0")&&c(),e.unsignedTx({to:R(a.to),data:b(a.data),value:A(a.value),chainId:w,description:b(a.label)})});return{bundle:t,txs:s,expiresAt:u}}async function H(e,n,i,r={}){let{bundle:t,txs:o,expiresAt:u}=n,s=await e.preview(o,i);if(Date.parse(u)<=Date.now())throw new m("The prepared TickerSpring bundle expired during preview. Prepare it again.");r.deadline!==void 0&&Q(r.deadline);let h=s.changes.map(({token:d,amount:I})=>{let y=I.startsWith("-");return`${y?"-":""}${e.formatAmount(y?I.slice(1):I,d.decimals)} ${d.symbol} (${d.address}, chain ${d.chainId})`});(!Array.isArray(t.warnings)||!t.warnings.every(d=>typeof d=="string"))&&c();let l=t.simulation===void 0?void 0:k(t.simulation),a=l?.ok===!1?`API simulation: ${b(l.error)}.`:"";return{txs:o,from:i,expiresAt:u,...r,preview:s,summary:[b(t.summary),"Protocol minimum: 10 USDG. Fill fee: 2.5% of received tokens; no placement or unfilled cancellation fee.","Filled proceeds require tickerspring_claim (claimBoth). No transaction has been sent.",...t.warnings,a,s.summary,...h].filter(Boolean).join(" ")}}async function Se(e,n,i){J(n,["token","side","amount","price","slippageBps","minAmountOut"]);let r=R(n.token),t=O(n.amount),o=de(b(n.price)),u=n.slippageBps===void 0?500:n.slippageBps;M("1",u);let s=n.minAmountOut===void 0?0n:BigInt(O(n.minAmountOut));if(n.minAmountOut!==void 0&&s<=1n)throw new m("The minimum output amount must be greater than 1 base unit.");if(n.side!=="buy"&&n.side!=="sell")throw new m("Choose buy or sell for the limit order.");if(n.side==="buy"&&BigInt(t)<se)throw new m("TickerSpring orders require at least 10 USDG.");let h=await N(e,"/v1/tokens");Array.isArray(h.tokens)||c();let l=h.tokens.map(k).filter(g=>f(g.address,r)&&(g.chainId===void 0||g.chainId===w));if(l.length!==1)throw new m("TickerSpring did not return a unique token for that address on chain 4663.");let a=l[0],d=me(a);if(f(d.address,S.address))throw new m("Choose the order token paired with USDG.");let I=k(a.markets);typeof I.limitOrders!="boolean"&&c();let y=n.side==="buy"?S:d,D=n.side==="buy"?d:S;if(n.side==="sell"){let g=BigInt(E(o,18,"floor"));if(BigInt(t)*g*10n**BigInt(P)/(10n**BigInt(d.decimals)*10n**18n)<se)throw new m("TickerSpring orders require at least 10 USDG at the limit price.")}let pe=await N(e,"/v1/agent/prepare/limit-order",{owner:i,token:r,side:n.side,price:o,amount:e.formatAmount(t,y.decimals),...I.limitOrders?{}:{startingPrice:de(a.priceUsd)}}),x=le(e,pe,i,"limit-order"),T=k(x.bundle.params),p=k(T.create),W=Q(p.deadline),$=O(p.minimumFullOutput);(!f(T.hook,C)||!f(p.inputToken,y.address)||A(p.maximumInput)!==t||p.maximumFeeBps!==250||typeof p.sell0!="boolean"||typeof p.lower!="number"||!Number.isInteger(p.lower)||typeof p.pool!="string"||!/^0x[0-9a-fA-F]{64}$/.test(p.pool)||BigInt(A(p.maximumCorrectionInput))>BigInt(t))&&c();let fe=BigInt(y.address)<BigInt(D.address);p.sell0!==fe&&c();let v=BigInt(t)*9750n/10000n,q=BigInt(E(o,18,"floor")),ge=n.side==="buy"?q>0n?v*10n**BigInt(d.decimals)*10n**18n/(10n**BigInt(P)*q):0n:v*q*10n**BigInt(P)/(10n**BigInt(d.decimals)*10n**18n),z=BigInt(M(ge.toString(),u)),K=oe(p.lower),G=K*K,X=1n<<192n,ke=G>0n?p.sell0?v*G/X:v*X/G:0n,he=d.decimals===18?BigInt(M(ke.toString(),u)):z,we=[s,z,he].reduce((g,B)=>g>B?g:B,0n);if(BigInt($)<=1n||BigInt($)<we)throw new m("TickerSpring minimum output is below the quoted slippage minimum.");let Y={pool:p.pool,lower:p.lower,sell0:p.sell0,inputToken:y.address,maximumInput:BigInt(t),maximumCorrectionInput:BigInt(A(p.maximumCorrectionInput)),minimumFullOutput:BigInt($),maximumFeeBps:250,deadline:BigInt(W)},L;if(I.limitOrders)L=j({abi:U,functionName:"create",args:[Y]});else{let g=k(T.market);f(g.token,d.address)||c();let B=BigInt(O(g.initialPrice)),ee=BigInt(O(g.minimumPrice)),ne=BigInt(O(g.maximumPrice));(B<ee||B>ne)&&c(),L=j({abi:U,functionName:"createMarketOrder",args:[Y,d.address,B,ee,ne]})}if((!Array.isArray(T.approvals)||T.approvals.length>1||x.txs.length!==T.approvals.length+1)&&c(),T.approvals.length){let g=k(T.approvals[0]),B=j({abi:be,functionName:"approve",args:[C,BigInt(t)]});(!f(g.token,y.address)||!f(g.spender,C)||A(g.amount)!==t||!f(x.txs[0].to,y.address)||x.txs[0].data.toLowerCase()!==B.toLowerCase())&&c()}let Z=x.txs.at(-1);return(!f(Z.to,C)||Z.data.toLowerCase()!==L.toLowerCase())&&c(),H(e,x,i,{input:{token:y,amount:t},minimumOutput:{token:D,amount:$},deadline:W})}async function ue(e,n,i,r){J(n,["id"]);let t=A(n.id),o=await N(e,"/v1/agent/prepare/order-action",{owner:i,id:t,action:r}),u=le(e,o,i,"order-action");(u.txs.length!==1||!f(u.txs[0].to,C))&&c();let s=ye({abi:U,data:u.txs[0].data});if((s.functionName!==r||s.args[0]!==BigInt(t))&&c(),s.functionName==="cancel"){let[,h,l,a,d]=s.args;if(Q(a.toString()),h+l===0n||d!==3)throw new m("TickerSpring returned a cancellation without protected amounts or both token deliveries. Prepare it again.");return H(e,u,i,{id:t,deadline:a.toString()})}return u.txs[0].data.toLowerCase()!==j({abi:U,functionName:"claimBoth",args:[BigInt(t)]}).toLowerCase()&&c(),H(e,u,i,{id:t})}async function ce(e,n){let i=await N(e,`/v1/agent/accounts/${n}`);if(!f(i.owner,n)||i.limitOrdersComplete!==!0||!Array.isArray(i.limitOrders)||!Array.isArray(i.unavailable)||i.unavailable.length)throw new m("TickerSpring could not return the complete order list for this wallet.");let r=b(i.asOf);Number.isFinite(Date.parse(r))||c();let t=new Set,o=i.limitOrders.map(u=>{let s=k(u),h=k(s.order),l=me(s.token);(!f(s.hook,C)||!f(h.owner,n)||s.side!=="buy"&&s.side!=="sell"||f(l.address,S.address)||s.feeBps!==250)&&c();let a=A(s.id);t.has(a)&&c(),t.add(a);let d=BigInt(l.address)<BigInt(S.address)?[l,S]:[S,l],I=k(s.claimable);return{id:a,status:b(s.status),side:s.side,chainId:w,feeBps:250,input:{token:s.side==="buy"?S:l,amount:A(h.debit)},claimable:d.map((y,D)=>({token:y,amount:A(I[D===0?"net0":"net1"])}))}});return{owner:n,chainId:w,asOf:r,orders:o}}var Oe=e=>{let n=r=>async t=>{try{return _(t),await r(t)}catch(o){throw new m(e.plainError(o))}},i=(r,t,o,u)=>({name:`tickerspring_${r}`,inputSchema:{type:"object",properties:t,required:o,additionalProperties:!1},execute:(s,h)=>n(l=>u(s,l))(h)});return{tools:[i("create",{token:Te,side:{type:"string",enum:["buy","sell"]},amount:{...F,description:"Base units of USDG for buys, or the selected token for sells."},price:{type:"string",pattern:"^\\d+(\\.\\d+)?$",description:"Limit price in USDG per whole token."},slippageBps:{type:"integer",minimum:0,maximum:9999},minAmountOut:{...F,description:"Optional caller minimum output in base units."}},["token","side","amount","price"],(r,t)=>Se(e,r,t)),i("cancel",{id:F},["id"],(r,t)=>ue(e,r,t,"cancel")),i("claim",{id:F},["id"],(r,t)=>ue(e,r,t,"claimBoth")),i("orders",{},[],(r,t)=>(J(r,[]),ce(e,t)))],positions:n(async r=>(await ce(e,r)).orders.map(o=>({module:"tickerspring",id:o.id,chainId:w,assets:o.claimable,description:`${o.side} order ${o.id}: ${o.status}; assets are claimable amounts only. Original input: ${e.formatAmount(o.input.amount,o.input.token.decimals)} ${o.input.token.symbol} (${o.input.token.address}). Fill fee 2.5%; use tickerspring_claim for proceeds.`})))}},Ue=e=>ie("tickerspring",[Oe(e)]);export{Ue as createModule,Oe as createModulePart};
@@ -1 +1 @@
1
- import{y as _}from"../../../chunks/CUBRTOMA.js";import{A as se,B as pe,C as ue,D as de,E as w,F as M,G as k,H as A,I as ae,J as ce,K as T,L as ve,a as V,b as I,c as U,d as O,e as L,f as H,g as $,h as F,i as q,j as B,k as K,l as z,m as G,n as J,o as Q,p as W,q as X,r as Y,s as Z,t as N,u as ee,v as ne,w as oe,x as ie,y as te,z as re}from"../../../chunks/ZERWRK6X.js";import"../../../chunks/VZPFBWVH.js";import"../../../chunks/MGEJPRXP.js";import"../../../chunks/ZKOMJGNH.js";import"../../../chunks/YTHDLCHL.js";import"../../../chunks/KFMNCJXJ.js";import"../../../chunks/6YU3JLQQ.js";import"../../../chunks/D45AODDL.js";import"../../../chunks/24JYIH53.js";import"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import{b as m}from"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import{a as v}from"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import"../../../chunks/25EOXUBI.js";import"../../../chunks/B5RZYFQC.js";import{a as d}from"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";var E={uniswap_add:{token0:{type:"string",description:"Sorted token0 ERC-20 address (v3)."},token1:{type:"string",description:"Sorted token1 ERC-20 address (v3)."},fee:{type:"number",description:"Pool fee tier in hundredths of a bip."},tickLower:{type:"number"},tickUpper:{type:"number"},amount0Desired:{type:"string"},amount1Desired:{type:"string"},amount0Min:{type:"string"},amount1Min:{type:"string"},recipient:{type:"string"},deadline:{type:"string"}},uniswap_collect:{tokenId:{type:"string"},recipient:{type:"string"},amount0Max:{type:"string"},amount1Max:{type:"string"}},uniswap_remove:{tokenId:{type:"string"},liquidity:{type:"string"},amount0Min:{type:"string"},amount1Min:{type:"string"},deadline:{type:"string"},burn:{type:"boolean"}},uniswap_list_positions:{tokenIds:{type:"array",items:{type:"string"}}}};function g(n,e){if(n)return typeof n=="function"?n(e):n}function R(n,e,t){let o=e.properties&&typeof e.properties=="object"?e.properties:{},s=t?.tools.find(i=>i.name===n||i.name===n.replace("uniswap_","uniswap_v3_")),a=s?.inputSchema?.properties&&typeof s.inputSchema.properties=="object"?s.inputSchema.properties:{};return{type:"object",properties:{...E[n]??{},...a,...o,version:{type:"string",enum:["v3","v4"],description:'Uniswap protocol version ("v3" or "v4").'}}}}function j(n,e){if(e.version!==void 0){if(e.version==="v3"||e.version==="v4")return e.version;throw new d(`Unsupported Uniswap version "${String(e.version)}". Choose "v3" or "v4".`)}if(n==="uniswap_collect"||n==="uniswap_remove"||e.tokenId!==void 0)throw new d('Provide version "v3" or "v4" for a Uniswap position operation; token IDs overlap between managers.');return e.poolId!==void 0||e.poolKey!==void 0||e.hooks!==void 0||e.currency0!==void 0||e.currency1!==void 0||e.permit2Expiration!==void 0?"v4":e.amount0Desired!==void 0||e.amount1Desired!==void 0||n==="uniswap_collect"&&(e.amount0Max!==void 0||e.amount1Max!==void 0)||e.token0!==void 0&&e.token1!==void 0&&e.tickSpacing===void 0?"v3":"v4"}function f(n,e){let t=n.tools.find(o=>o.name===e||o.name===e.replace("uniswap_","uniswap_v3_")||o.name===e.replace("uniswap_","uniswap_v4_"));if(!t)throw new d(`Tool ${e} is not available on the selected Uniswap part.`);return t}function h(n,e){let t=g(e?.v4,n)??T(n),o=g(e?.v3,n)??_(n),s=(i,c)=>({name:i,inputSchema:R(i,c,o),async execute(p,u){if(v(u),i==="uniswap_list_positions"&&p.version===void 0){let C=f(t,"uniswap_list_positions"),[S,l]=await Promise.all([(async()=>{let y=o.tools.find(r=>r.name==="uniswap_list_positions"||r.name==="uniswap_v3_list_positions");if(y){let r=await y.execute({...p,version:"v3"},u);if(Array.isArray(r))return r;if(r&&typeof r=="object"&&Array.isArray(r.positions))return r.positions}return o.positions?o.positions(u):[]})(),C.execute({...p,version:"v4"},u)]),x=Array.isArray(l?.positions)?l.positions:[],P=[...S,...x];return{positions:P,summary:`Found ${P.length} active Uniswap position(s) across v3 and v4 for ${u}.`}}return j(i,p)==="v3"?f(o,i).execute(p,u):f(t,i).execute({...p,version:"v4"},u)}}),a=[s("uniswap_add",w),s("uniswap_collect",M),s("uniswap_remove",k),s("uniswap_list_positions",A)];return m("uniswap",[{tools:a,positions:async i=>{v(i);let[c,p]=await Promise.all([o.positions?o.positions(i):Promise.resolve([]),t.positions?t.positions(i):Promise.resolve([])]);return[...c,...p]}}])}var _e=h;export{z as DEEPEST_V4_POOL_ID,K as MAX_TICK,J as MEASURED_V4_POOLS,B as MIN_TICK,O as PERMIT2_ADDRESS,$ as USDG_ADDRESS,G as V4_ACTIONS,w as V4_ADD_SCHEMA,M as V4_COLLECT_SCHEMA,q as V4_DYNAMIC_FEE_FLAG,A as V4_LIST_POSITIONS_SCHEMA,V as V4_POOL_MANAGER,I as V4_POSITION_MANAGER,k as V4_REMOVE_SCHEMA,U as V4_STATE_VIEW,L as V4_UNIVERSAL_ROUTER,H as WETH_ADDRESS,F as ZERO_ADDRESS,re as amountsForLiquidity,W as computePoolId,h as createModule,T as createModulePart,ce as createPart,_e as createUniswapModule,ve as createUniswapV4Part,ae as createV4Part,te as decodePackedPositionInfo,Y as describeV4FeeBehavior,ie as encodePackedPositionInfo,ne as encodePermit2Approve,oe as encodeV4UniversalRouterFeeSwap,pe as formatSignedPreviewChanges,N as fullRangeTicks,X as isDynamicFeePool,Q as isNativeV4Currency,se as liquidityForAmounts,de as readV4Positions,ue as tokenForCurrency,ee as validateTickRange,Z as validateV4PoolKey};
1
+ import{y as M}from"../../../chunks/GN4QZ4JA.js";import{A as uo,B as po,C as ao,D as co,E as y,F as k,G as A,H as b,I as fo,J as lo,K as T,L as vo,a as U,b as O,c as L,d as $,e as g,f as H,g as F,h as q,i as B,j as K,k as z,l as G,m as J,n as Q,o as W,p as X,q as Y,r as Z,s as N,t as oo,u as eo,v as no,w as io,x as to,y as ro,z as so}from"../../../chunks/T6O2L6HF.js";import"../../../chunks/SJ7HDRI4.js";import"../../../chunks/6SYTB6FB.js";import"../../../chunks/52TGAWSI.js";import"../../../chunks/3PA2XT75.js";import"../../../chunks/MOVRI5IV.js";import"../../../chunks/YX4NVVSX.js";import"../../../chunks/BHR46XNW.js";import"../../../chunks/73EABRFC.js";import"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MK6L6TGI.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import{b as w}from"../../../chunks/UCMNB2UP.js";import"../../../chunks/Z25UKUJF.js";import{a as l}from"../../../chunks/A5ITAEUQ.js";import"../../../chunks/I5CQ64EU.js";import{a as n}from"../../../chunks/NA7HV7BR.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import{a}from"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";var h={uniswap_add:{token0:{type:"string",description:"Sorted token0 ERC-20 address (v3)."},token1:{type:"string",description:"Sorted token1 ERC-20 address (v3)."},fee:{type:"number",description:"Pool fee tier in hundredths of a bip."},tickLower:{type:"number"},tickUpper:{type:"number"},amount0Desired:n(),amount1Desired:n(),amount0Min:n(),amount1Min:n(),recipient:{type:"string"},deadline:n()},uniswap_collect:{tokenId:n(),recipient:{type:"string"},amount0Max:n(),amount1Max:n()},uniswap_remove:{tokenId:n(),liquidity:{type:"string",pattern:"^(?:[0-9]+|all)$",description:"Positive base-unit liquidity amount, or all for a full burn."},amount0Min:n(),amount1Min:n(),deadline:n(),burn:{type:"boolean"}},uniswap_list_positions:{tokenIds:{type:"array",items:n()}}};function S(e,o){if(e)return typeof e=="function"?e(o):e}function j(e,o,r){let i=o.properties&&typeof o.properties=="object"?o.properties:{},u=r?.tools.find(t=>t.name===e||t.name===e.replace("uniswap_","uniswap_v3_")),c=u?.inputSchema?.properties&&typeof u.inputSchema.properties=="object"?u.inputSchema.properties:{};return{type:"object",properties:{...h[e]??{},...c,...i,version:{type:"string",enum:["v3","v4"],description:'Uniswap protocol version ("v3" or "v4").'}}}}function D(e,o){if(o.version!==void 0){if(o.version==="v3"||o.version==="v4")return o.version;throw new a(`Unsupported Uniswap version "${String(o.version)}". Choose "v3" or "v4".`)}if(e==="uniswap_collect"||e==="uniswap_remove"||o.tokenId!==void 0)throw new a('Provide version "v3" or "v4" for a Uniswap position operation; token IDs overlap between managers.');return o.poolId!==void 0||o.poolKey!==void 0||o.hooks!==void 0||o.currency0!==void 0||o.currency1!==void 0||o.permit2Expiration!==void 0?"v4":o.amount0Desired!==void 0||o.amount1Desired!==void 0||e==="uniswap_collect"&&(o.amount0Max!==void 0||o.amount1Max!==void 0)||o.token0!==void 0&&o.token1!==void 0&&o.tickSpacing===void 0?"v3":"v4"}function v(e,o){let r=e.tools.find(i=>i.name===o||i.name===o.replace("uniswap_","uniswap_v3_")||i.name===o.replace("uniswap_","uniswap_v4_"));if(!r)throw new a(`Tool ${o} is not available on the selected Uniswap part.`);return r}function V(e,o){let r=S(o?.v4,e)??T(e),i=S(o?.v3,e)??M(e),u=(t,f)=>({name:t,inputSchema:j(t,f,i),async execute(p,d){if(l(d),t==="uniswap_list_positions"&&p.version===void 0){let x=v(r,"uniswap_list_positions"),[E,P]=await Promise.all([(async()=>{let _=i.tools.find(s=>s.name==="uniswap_list_positions"||s.name==="uniswap_v3_list_positions");if(_){let s=await _.execute({...p,version:"v3"},d);if(Array.isArray(s))return s;if(s&&typeof s=="object"&&Array.isArray(s.positions))return s.positions}return i.positions?i.positions(d):[]})(),x.execute({...p,version:"v4"},d)]),R=Array.isArray(P?.positions)?P.positions:[],m=[...E,...R];return{positions:m,summary:`Found ${m.length} active Uniswap position(s) across v3 and v4 for ${d}.`}}return D(t,p)==="v3"?v(i,t).execute(p,d):v(r,t).execute({...p,version:"v4"},d)}}),c=[u("uniswap_add",y),u("uniswap_collect",k),u("uniswap_remove",A),u("uniswap_list_positions",b)];return w("uniswap",[{tools:c,positions:async t=>{l(t);let[f,p]=await Promise.all([i.positions?i.positions(t):Promise.resolve([]),r.positions?r.positions(t):Promise.resolve([])]);return[...f,...p]}}])}var ko=V;export{G as DEEPEST_V4_POOL_ID,z as MAX_TICK,Q as MEASURED_V4_POOLS,K as MIN_TICK,$ as PERMIT2_ADDRESS,F as USDG_ADDRESS,J as V4_ACTIONS,y as V4_ADD_SCHEMA,k as V4_COLLECT_SCHEMA,B as V4_DYNAMIC_FEE_FLAG,b as V4_LIST_POSITIONS_SCHEMA,U as V4_POOL_MANAGER,O as V4_POSITION_MANAGER,A as V4_REMOVE_SCHEMA,L as V4_STATE_VIEW,g as V4_UNIVERSAL_ROUTER,H as WETH_ADDRESS,q as ZERO_ADDRESS,so as amountsForLiquidity,X as computePoolId,V as createModule,T as createModulePart,lo as createPart,ko as createUniswapModule,vo as createUniswapV4Part,fo as createV4Part,ro as decodePackedPositionInfo,Z as describeV4FeeBehavior,to as encodePackedPositionInfo,no as encodePermit2Approve,io as encodeV4UniversalRouterFeeSwap,po as formatSignedPreviewChanges,oo as fullRangeTicks,Y as isDynamicFeePool,W as isNativeV4Currency,uo as liquidityForAmounts,co as readV4Positions,ao as tokenForCurrency,eo as validateTickRange,N as validateV4PoolKey};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../../../chunks/CUBRTOMA.js";import"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import"../../../chunks/64EN6Y7E.js";import"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import"../../../chunks/25EOXUBI.js";import"../../../chunks/B5RZYFQC.js";import"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";export{b as MAX_TICK,c as MAX_UINT128,a as MIN_TICK,j as UNISWAP_SWAP_ROUTER02_ABI,d as UNISWAP_V3_ADDRESSES,h as UNISWAP_V3_FACTORY_ABI,e as UNISWAP_V3_FEE_TICK_SPACING,f as UNISWAP_V3_MEASURED_POOLS,i as UNISWAP_V3_POOL_ABI,g as UNISWAP_V3_POSITION_MANAGER_ABI,y as createModulePart,x as createPart,v as createUniswapV3Part,u as createUniswapV3Tools,w as createV3Part,m as decodeV3PositionTuple,z as default,o as encodeSwapRouter02ExactInputSingle,n as extractV3TokenIdsFromReceipt,l as formatPreviewDelta,s as readUniswapV3Positions,p as uniswapAddV3,q as uniswapCollectV3,t as uniswapListPositionsV3,r as uniswapRemoveV3,k as validateV3TickRange};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../../../chunks/GN4QZ4JA.js";import"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import"../../../chunks/A5ITAEUQ.js";import"../../../chunks/I5CQ64EU.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";export{b as MAX_TICK,c as MAX_UINT128,a as MIN_TICK,j as UNISWAP_SWAP_ROUTER02_ABI,d as UNISWAP_V3_ADDRESSES,h as UNISWAP_V3_FACTORY_ABI,e as UNISWAP_V3_FEE_TICK_SPACING,f as UNISWAP_V3_MEASURED_POOLS,i as UNISWAP_V3_POOL_ABI,g as UNISWAP_V3_POSITION_MANAGER_ABI,y as createModulePart,x as createPart,v as createUniswapV3Part,u as createUniswapV3Tools,w as createV3Part,m as decodeV3PositionTuple,z as default,o as encodeSwapRouter02ExactInputSingle,n as extractV3TokenIdsFromReceipt,l as formatPreviewDelta,s as readUniswapV3Positions,p as uniswapAddV3,q as uniswapCollectV3,t as uniswapListPositionsV3,r as uniswapRemoveV3,k as validateV3TickRange};
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,H,I,J,K,L,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../../../chunks/ZERWRK6X.js";import"../../../chunks/VZPFBWVH.js";import"../../../chunks/MGEJPRXP.js";import"../../../chunks/ZKOMJGNH.js";import"../../../chunks/YTHDLCHL.js";import"../../../chunks/KFMNCJXJ.js";import"../../../chunks/6YU3JLQQ.js";import"../../../chunks/D45AODDL.js";import"../../../chunks/24JYIH53.js";import"../../../chunks/VBV366XQ.js";import"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/P7Q6MJZH.js";import"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import"../../../chunks/SGDWO7XI.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import"../../../chunks/25EOXUBI.js";import"../../../chunks/B5RZYFQC.js";import"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";export{l as DEEPEST_V4_POOL_ID,k as MAX_TICK,n as MEASURED_V4_POOLS,j as MIN_TICK,d as PERMIT2_ADDRESS,g as USDG_ADDRESS,m as V4_ACTIONS,E as V4_ADD_SCHEMA,F as V4_COLLECT_SCHEMA,i as V4_DYNAMIC_FEE_FLAG,H as V4_LIST_POSITIONS_SCHEMA,a as V4_POOL_MANAGER,b as V4_POSITION_MANAGER,G as V4_REMOVE_SCHEMA,c as V4_STATE_VIEW,e as V4_UNIVERSAL_ROUTER,f as WETH_ADDRESS,h as ZERO_ADDRESS,z as amountsForLiquidity,p as computePoolId,K as createModulePart,J as createPart,L as createUniswapV4Part,I as createV4Part,y as decodePackedPositionInfo,r as describeV4FeeBehavior,x as encodePackedPositionInfo,v as encodePermit2Approve,w as encodeV4UniversalRouterFeeSwap,B as formatSignedPreviewChanges,t as fullRangeTicks,q as isDynamicFeePool,o as isNativeV4Currency,A as liquidityForAmounts,D as readV4Positions,C as tokenForCurrency,u as validateTickRange,s as validateV4PoolKey};
1
+ import{A,B,C,D,E,F,G,H,I,J,K,L,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../../../chunks/T6O2L6HF.js";import"../../../chunks/SJ7HDRI4.js";import"../../../chunks/6SYTB6FB.js";import"../../../chunks/52TGAWSI.js";import"../../../chunks/3PA2XT75.js";import"../../../chunks/MOVRI5IV.js";import"../../../chunks/YX4NVVSX.js";import"../../../chunks/BHR46XNW.js";import"../../../chunks/73EABRFC.js";import"../../../chunks/2IRORNOH.js";import"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import"../../../chunks/MK6L6TGI.js";import"../../../chunks/Y3P6SUNL.js";import"../../../chunks/GIBF3YJO.js";import"../../../chunks/UCMNB2UP.js";import"../../../chunks/Z25UKUJF.js";import"../../../chunks/A5ITAEUQ.js";import"../../../chunks/I5CQ64EU.js";import"../../../chunks/NA7HV7BR.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";export{l as DEEPEST_V4_POOL_ID,k as MAX_TICK,n as MEASURED_V4_POOLS,j as MIN_TICK,d as PERMIT2_ADDRESS,g as USDG_ADDRESS,m as V4_ACTIONS,E as V4_ADD_SCHEMA,F as V4_COLLECT_SCHEMA,i as V4_DYNAMIC_FEE_FLAG,H as V4_LIST_POSITIONS_SCHEMA,a as V4_POOL_MANAGER,b as V4_POSITION_MANAGER,G as V4_REMOVE_SCHEMA,c as V4_STATE_VIEW,e as V4_UNIVERSAL_ROUTER,f as WETH_ADDRESS,h as ZERO_ADDRESS,z as amountsForLiquidity,p as computePoolId,K as createModulePart,J as createPart,L as createUniswapV4Part,I as createV4Part,y as decodePackedPositionInfo,r as describeV4FeeBehavior,x as encodePackedPositionInfo,v as encodePermit2Approve,w as encodeV4UniversalRouterFeeSwap,B as formatSignedPreviewChanges,t as fullRangeTicks,q as isDynamicFeePool,o as isNativeV4Currency,A as liquidityForAmounts,D as readV4Positions,C as tokenForCurrency,u as validateTickRange,s as validateV4PoolKey};
@@ -1 +1 @@
1
- import{a as le}from"../../../chunks/JMPOXXNJ.js";import{a as re,b as J,e as T,h as se,i as ae,m as L,n as ie,o as G,p as ue,q as de,t as ce,v as me,w as pe}from"../../../chunks/VBV366XQ.js";import{b as H}from"../../../chunks/S3YSJ7XH.js";import"../../../chunks/LIUXNOLP.js";import{a as z}from"../../../chunks/P7Q6MJZH.js";import{c as ne}from"../../../chunks/ZUAXW2ZD.js";import"../../../chunks/64EN6Y7E.js";import{a as _}from"../../../chunks/VZWOWR6G.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/UL2L7NHO.js";import{a as m,i as oe}from"../../../chunks/25EOXUBI.js";import{a as j}from"../../../chunks/B5RZYFQC.js";import{a as t}from"../../../chunks/T5E4OJEU.js";import"../../../chunks/XN4WDN3O.js";import{randomUUID as ve}from"node:crypto";import{decodeFunctionData as Ie,erc20Abi as Se,parseAbi as Te}from"viem";var O=oe[m].routes.velora.address,be="https://api.velora.xyz/prices",xe="https://api.velora.xyz/transactions/4663?ignoreChecks=true",ge=(1n<<256n)-1n,Pe=new Set(["from","to","amountIn","slippageBps"]),Ve=Te(["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)"]);function V(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function x(e){if(typeof e!="string")throw new t("Provide a token or wallet address.");if(_(e),/^0x0{40}$/i.test(e))throw new t("Use the native ETH token address, not the zero address.");return e}function we(e){if(typeof e!="string")throw new t("Provide a token address.");return _(e),H(e)}function Q(e){return ie(e)?T:e}function k(e,n,p){if(x(e).toLowerCase()!==n.toLowerCase())throw new t(`Velora ${p} does not match the requested swap.`)}function P(e){if(typeof e!="string")throw new t("Amount must be an integer string in base units.");let n=j(e);if(n>ge)throw new t("Amount exceeds the uint256 range.");return n.toString()}function fe(e){if(!V(e))throw new t("Swap arguments must be an object.");for(let q of Object.keys(e))if(!Pe.has(q))throw new t(`Unsupported Velora quote argument: ${q}.`);let n=we(e.from),p=we(e.to);if(n.toLowerCase()===p.toLowerCase())throw new t("Choose two different token addresses.");let g=P(e.amountIn);if(g==="0")throw new t("Swap amountIn must be greater than zero.");let A=e.slippageBps??J;if(typeof A!="number")throw new t("Slippage must be an integer number of bps.");return G(g,A),{from:n,to:p,amountIn:g,slippageBps:A}}function qe(e){if(!V(e))throw new t("Swap arguments must be an object.");for(let n of Object.keys(e))if(n!=="quoteId")throw new t(`Unsupported Velora swap argument: ${n}.`);if(typeof e.quoteId!="string"||!e.quoteId.trim())throw new t("Provide a Velora quoteId.");return e.quoteId}function he(e,n){me(e,n);let p=Ie({abi:Ve,data:e.data}),[,g,,A]=p.args;if(g.toAmount.toString()!==n.calldataMinAmountOut)throw new t("Velora calldata minimum output does not match the accepted quote.");if(g.quotedAmount.toString()!==n.grossAmountOut)throw new t("Velora calldata quotedAmount does not match the quoted gross output.");if(A!=="0x")throw new t("Velora calldata must not include a permit payload.")}var Ce={type:"object",additionalProperties:!1,required:["from","to","amountIn"],properties:{from:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},to:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},amountIn:{type:"string",pattern:"^[0-9]+$",description:"Positive integer amount in input-token base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:J}}};function $e(e){let n=new Map;async function p(o){try{return await o()}catch(s){throw new t(e.plainError(s))}}async function g(){let o=e.clientFor(m);if(await o.getChainId()!==m)throw new t("Velora requires an RPC on chain 4663.");return o}async function A(o,s){if(o.toLowerCase()===T.toLowerCase())return{address:o,symbol:"ETH",decimals:18,chainId:m};let[a,r]=await Promise.all([z(s,m,o,"symbol"),z(s,m,o,"decimals")]);if(typeof a!="string"||!a.trim()||!Number.isInteger(r)||r<0||r>255)throw new t("The token returned invalid symbol or decimals metadata.");return{address:o,symbol:a,decimals:r,chainId:m}}async function q(o,s,a,r){if(o.toLowerCase()===T.toLowerCase())return 0n;let d=await r.readContract({address:o,abi:Se,functionName:"allowance",args:[s,a]});if(typeof d!="bigint"||d<0n||d>ge)throw new t("The token returned an invalid allowance.");return d}function Ae(){let o=BigInt(L());for(let[s,a]of n)o>=BigInt(a.quote.expiresAt)&&n.delete(s)}function y(o){if(BigInt(L())>=BigInt(o.expiresAt))throw n.delete(o.quoteId),new se}async function D(o,s,a=!1){return p(async()=>{let r=fe(o),d=x(s),u=String(L()+re),C=await g(),[c,l]=await Promise.all([A(r.from,C),A(r.to,C)]),$=new URLSearchParams({network:String(m),srcToken:Q(c.address),srcDecimals:String(c.decimals),destToken:Q(l.address),destDecimals:String(l.decimals),amount:r.amountIn,side:"SELL"}),I=await le(e.http,`${be}?${$}`,V),i=I.value.priceRoute;if(!V(i))throw new t("Velora returned no usable price route.");k(i.srcToken,c.address,"input token"),k(i.destToken,l.address,"output token"),k(i.contractAddress,O,"router"),k(i.tokenTransferProxy,O,"token transfer proxy");let f=x(i.tokenTransferProxy);if(i.network!==m||i.srcDecimals!==c.decimals||i.destDecimals!==l.decimals||P(i.srcAmount)!==r.amountIn||i.side!=="SELL"||i.contractMethod!=="swapExactAmountIn"||i.version!=="6.2")throw new t("Velora returned a route that does not match the requested swap.");if(i.maxImpactReached===!0)throw new t("Velora reports that this route exceeds its price impact limit.");if(i.partner!=="anon"||i.partnerFee!==.01)throw new t("Velora returned an unsupported venue fee. Request a fresh quote.");if(i.destAmountAfterFee===void 0)throw new t("Velora price route is missing destAmountAfterFee.");let w=P(i.destAmount),b=BigInt(P(i.destAmountAfterFee)),R=BigInt(w)*9999n/10000n,ye=(BigInt(w)*9999n+9999n)/10000n;if(b<R||b>ye)throw new t("Velora output after fees does not match its disclosed 1 bp venue fee.");let S=(BigInt(w)-BigInt(w)/10000n-1n).toString();if(BigInt(S)<=0n)throw new t("Velora returned no positive swap output.");let B=G(S,r.slippageBps);if(B==="0")throw new t("Velora minimum output must be positive.");let F=ue(B).toString();if(BigInt(F)>BigInt(w))throw new t("Velora output is too small to cover router dust.");let U=(BigInt(w)-BigInt(S)).toString(),Y=de({provider:"velora",venueFee:U,venueFeeBps:1,oakFee:"0"}),Z=B,h={quoteId:`velora:${ve()}`,router:O,expiresAt:String(Math.min(Number(u),I.expiresAt)),amountOut:S,minAmountOut:Z,calldataMinAmountOut:F,provider:"velora",from:c.address,to:l.address,amountIn:r.amountIn,wallet:d,chainId:m,slippageBps:r.slippageBps,spender:f,value:c.address.toLowerCase()===T.toLowerCase()?r.amountIn:"0",grossAmountOut:w,destAmountAfterFee:S,venueFee:U,venueFeeBps:1,oakFee:"0",feeDisclosure:Y,input:{token:c,amount:r.amountIn},output:{token:l,amount:S},minimumOutput:{token:l,amount:Z},fee:{token:l,amount:U}},E={quote:h,wallet:d,spender:f,prepare:async()=>{if(y(h),E.tx)return structuredClone(h);let v=await ne(e.http,xe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({srcToken:Q(c.address),destToken:Q(l.address),srcAmount:r.amountIn,destAmount:F,priceRoute:i,userAddress:d,receiver:d,srcDecimals:c.decimals,destDecimals:l.decimals})},V);if(k(v.from,d,"transaction sender"),v.chainId!==m)throw new t("Velora built a transaction for a different chain.");if(typeof v.data!="string"||!/^0x(?:[a-fA-F0-9]{2})+$/.test(v.data))throw new t("Velora returned invalid swap calldata.");let te=v.data,ke=P(v.value);if(ce(te).toString()!==F)throw new t("Velora calldata minimum does not match the net output and slippage.");let N=e.unsignedTx({to:x(v.to),data:te,value:ke,chainId:m,description:`Swap ${r.amountIn} base units of ${c.address} for at least ${B} base units of ${l.address} via velora (${O}). ${Y}`});return he(N,h),h.data=N.data,y(h),E.tx=N,structuredClone(h)}};for(y(h),Ae();n.size>=ae;)n.delete(n.keys().next().value);if(n.set(h.quoteId,E),a)return structuredClone(h);let ee=await E.prepare();return{...ee,...pe(ee)}})}async function K(o,s){return p(async()=>{let a=n.get(o);if(!a)throw new t("Quote is unknown or expired. Request a fresh Velora quote.");return k(s,a.wallet,"wallet"),a.prepare()})}async function W(o,s){return p(async()=>{let a=n.get(o);if(!a)throw new t("Quote is unknown or expired. Request a fresh Velora quote.");k(s,a.wallet,"wallet"),y(a.quote);let r=await g(),d=await q(a.quote.input.token.address,s,a.spender,r);return y(a.quote),d.toString()})}async function X(o,s,a={}){return p(async()=>{if(typeof o!="string"||!o.trim())throw new t("Provide a Velora quoteId.");let r=x(s),d=n.get(o);if(!d)throw new t("Quote is unknown or expired. Request a fresh Velora quote.");let{quote:u,spender:C}=d;y(u),k(r,d.wallet,"wallet"),await K(o,r);let c=[],l=j(a.allowance??await W(o,r));u.input.token.address.toLowerCase()!==T.toLowerCase()&&l<BigInt(u.input.amount)&&c.push(e.approval(u.input.token.address,C,u.input.amount,m));let $={...d.tx};he($,u),c.push($),y(u);let I=await e.preview(c,r);y(u);let M=0n,i=I.changes.map(({token:f,amount:w})=>{if(f={...f,address:H(f.address)},!/^-?\d+$/.test(w))throw new t("Preview returned an invalid token amount.");f.address.toLowerCase()===u.output.token.address.toLowerCase()&&(M+=BigInt(w));let b=w.startsWith("-"),R=e.formatAmount(b?w.slice(1):w,f.decimals);return`${b?"-":"+"}${R} ${f.symbol} (${f.address}, chain ${f.chainId}, ${f.decimals} decimals)`});if(M<BigInt(u.minimumOutput.amount))throw new t("Preview retained output is below the accepted minimum.");return{txs:c,preview:I,summary:`Unsigned Velora swap. Minimum output: ${u.minimumOutput.amount} base units of ${u.output.token.address} (${u.output.token.decimals} decimals, chain ${m}). ${u.feeDisclosure} Fee token: ${u.fee.token.address} (${u.fee.token.decimals} decimals). ${I.summary} ${i.join("; ")}`}})}return{name:"velora",swapProvider:{name:"velora",quote:D,build:X,prepareQuote:K,readAllowance:W,quotePrices:(o,s)=>D(o,s,!0)},tools:[{name:"velora_quote",inputSchema:Ce,execute:(o,s)=>p(()=>D(fe(o),s))},{name:"velora_swap",inputSchema:{type:"object",additionalProperties:!1,required:["quoteId"],properties:{quoteId:{type:"string",minLength:1}}},execute:(o,s)=>p(()=>X(qe(o),s))}]}}var ze=e=>({tools:$e(e).tools});export{$e as createModule,ze as createModulePart};
1
+ import{a as we}from"../../../chunks/B4FOHEBE.js";import{a as re,b as J,e as b,h as se,i as ae,m as O,n as ie,o as G,q as ue,r as de,t as ce,w as me,y as pe,z as le}from"../../../chunks/2IRORNOH.js";import{b as H}from"../../../chunks/GDP4JSAX.js";import"../../../chunks/LIUXNOLP.js";import{c as ne}from"../../../chunks/MK6L6TGI.js";import"../../../chunks/Y3P6SUNL.js";import{a as z}from"../../../chunks/GIBF3YJO.js";import{a as _}from"../../../chunks/A5ITAEUQ.js";import{a as j}from"../../../chunks/I5CQ64EU.js";import"../../../chunks/5HCXZWUH.js";import"../../../chunks/M6JGTQRY.js";import{a as m,i as oe}from"../../../chunks/ZUC6ILK2.js";import"../../../chunks/B4MLWDPM.js";import{a as t}from"../../../chunks/NGAI6GTU.js";import"../../../chunks/JXOEJPJ4.js";import{randomUUID as Se}from"node:crypto";import{decodeFunctionData as Te,erc20Abi as be,parseAbi as xe}from"viem";var Q=oe[m].routes.velora.address,Pe="https://api.velora.xyz/prices",Ve="https://api.velora.xyz/transactions/4663?ignoreChecks=true",Ae=(1n<<256n)-1n,qe=new Set(["from","to","amountIn","slippageBps"]),Ce=xe(["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)"]);function V(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function x(e){if(typeof e!="string")throw new t("Provide a token or wallet address.");if(_(e),/^0x0{40}$/i.test(e))throw new t("Use the native ETH token address, not the zero address.");return e}function fe(e){if(typeof e!="string")throw new t("Provide a token address.");return _(e),H(e)}function D(e){return ie(e)?b:e}function v(e,n,p){if(x(e).toLowerCase()!==n.toLowerCase())throw new t(`Velora ${p} does not match the requested swap.`)}function P(e){if(typeof e!="string")throw new t("Amount must be an integer string in base units.");let n=j(e);if(n>Ae)throw new t("Amount exceeds the uint256 range.");return n.toString()}function he(e){if(!V(e))throw new t("Swap arguments must be an object.");for(let q of Object.keys(e))if(!qe.has(q))throw new t(`Unsupported Velora quote argument: ${q}.`);let n=fe(e.from),p=fe(e.to);if(n.toLowerCase()===p.toLowerCase())throw new t("Choose two different token addresses.");let A=P(e.amountIn);if(A==="0")throw new t("Swap amountIn must be greater than zero.");let y=e.slippageBps??J;if(typeof y!="number")throw new t("Slippage must be an integer number of bps.");return G(A,y),{from:n,to:p,amountIn:A,slippageBps:y}}function Be(e){if(!V(e))throw new t("Swap arguments must be an object.");for(let n of Object.keys(e))if(n!=="quoteId")throw new t(`Unsupported Velora swap argument: ${n}.`);if(typeof e.quoteId!="string"||!e.quoteId.trim())throw new t("Provide a Velora quoteId.");return e.quoteId}function ge(e,n){pe(e,n);let p=Te({abi:Ce,data:e.data}),[,A,,y]=p.args;if(A.toAmount.toString()!==n.calldataMinAmountOut)throw new t("Velora calldata minimum output does not match the accepted quote.");if(A.quotedAmount.toString()!==n.grossAmountOut)throw new t("Velora calldata quotedAmount does not match the quoted gross output.");if(y!=="0x")throw new t("Velora calldata must not include a permit payload.")}var $e={type:"object",additionalProperties:!1,required:["from","to","amountIn"],properties:{from:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},to:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},amountIn:{type:"string",pattern:"^[0-9]+$",description:"Positive integer amount in input-token base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:J}}};function Fe(e){let n=new Map;async function p(o){try{return await o()}catch(s){throw new t(e.plainError(s))}}async function A(){let o=e.clientFor(m);if(await o.getChainId()!==m)throw new t("Velora requires an RPC on chain 4663.");return o}async function y(o,s){if(o.toLowerCase()===b.toLowerCase())return{address:o,symbol:"ETH",decimals:18,chainId:m};let[a,r]=await Promise.all([z(s,m,o,"symbol"),z(s,m,o,"decimals")]);if(typeof a!="string"||!a.trim()||!Number.isInteger(r)||r<0||r>255)throw new t("The token returned invalid symbol or decimals metadata.");return{address:o,symbol:a,decimals:r,chainId:m}}async function q(o,s,a,r){if(o.toLowerCase()===b.toLowerCase())return 0n;let d=await r.readContract({address:o,abi:be,functionName:"allowance",args:[s,a]});if(typeof d!="bigint"||d<0n||d>Ae)throw new t("The token returned an invalid allowance.");return d}function ye(){let o=BigInt(O());for(let[s,a]of n)o>=BigInt(a.quote.expiresAt)&&n.delete(s)}function I(o){if(BigInt(O())>=BigInt(o.expiresAt))throw n.delete(o.quoteId),new se}async function M(o,s,a=!1){return p(async()=>{let r=he(o),d=x(s),u=String(O()+re),C=await A(),[c,l]=await Promise.all([y(r.from,C),y(r.to,C)]),B=new URLSearchParams({network:String(m),srcToken:D(c.address),srcDecimals:String(c.decimals),destToken:D(l.address),destDecimals:String(l.decimals),amount:r.amountIn,side:"SELL"}),S=await we(e.http,`${Pe}?${B}`,V),i=S.value.priceRoute;if(!V(i))throw new t("Velora returned no usable price route.");v(i.srcToken,c.address,"input token"),v(i.destToken,l.address,"output token"),v(i.contractAddress,Q,"router"),v(i.tokenTransferProxy,Q,"token transfer proxy");let f=x(i.tokenTransferProxy);if(i.network!==m||i.srcDecimals!==c.decimals||i.destDecimals!==l.decimals||P(i.srcAmount)!==r.amountIn||i.side!=="SELL"||i.contractMethod!=="swapExactAmountIn"||i.version!=="6.2")throw new t("Velora returned a route that does not match the requested swap.");if(i.maxImpactReached===!0)throw new t("Velora reports that this route exceeds its price impact limit.");if(i.partner!=="anon")throw new t("Velora returned an unsupported venue fee. Request a fresh quote.");let w=ue(i.partnerFee);if(i.destAmountAfterFee===void 0&&w!==0)throw new t("Velora price route is missing destAmountAfterFee.");let h=P(i.destAmount),$=BigInt(P(i.destAmountAfterFee??h)),Ie=BigInt(h)*BigInt(1e4-w)/10000n,ve=(BigInt(h)*BigInt(1e4-w)+9999n)/10000n;if($<Ie||$>ve)throw new t("Velora output after fees does not match its disclosed venue fee.");let T=(BigInt(h)-BigInt(h)*BigInt(w)/10000n-1n).toString();if(BigInt(T)<=0n)throw new t("Velora returned no positive swap output.");let F=G(T,r.slippageBps);if(F==="0")throw new t("Velora minimum output must be positive.");let E=de(F,w).toString();if(BigInt(E)>BigInt(h))throw new t("Velora output is too small to cover router dust.");let U=(BigInt(h)-BigInt(T)).toString(),Y=ce({provider:"velora",venueFee:U,venueFeeBps:w,oakFee:"0"}),Z=F,g={quoteId:`velora:${Se()}`,router:Q,expiresAt:String(Math.min(Number(u),S.expiresAt)),amountOut:T,minAmountOut:Z,calldataMinAmountOut:E,provider:"velora",from:c.address,to:l.address,amountIn:r.amountIn,wallet:d,chainId:m,slippageBps:r.slippageBps,spender:f,value:c.address.toLowerCase()===b.toLowerCase()?r.amountIn:"0",grossAmountOut:h,destAmountAfterFee:T,venueFee:U,venueFeeBps:w,oakFee:"0",feeDisclosure:Y,input:{token:c,amount:r.amountIn},output:{token:l,amount:T},minimumOutput:{token:l,amount:Z},fee:{token:l,amount:U}},L={quote:g,wallet:d,spender:f,prepare:async()=>{if(I(g),L.tx)return structuredClone(g);let k=await ne(e.http,Ve,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({srcToken:D(c.address),destToken:D(l.address),srcAmount:r.amountIn,destAmount:E,priceRoute:i,userAddress:d,receiver:d,srcDecimals:c.decimals,destDecimals:l.decimals})},V);if(v(k.from,d,"transaction sender"),k.chainId!==m)throw new t("Velora built a transaction for a different chain.");if(typeof k.data!="string"||!/^0x(?:[a-fA-F0-9]{2})+$/.test(k.data))throw new t("Velora returned invalid swap calldata.");let te=k.data,ke=P(k.value);if(me(te).toString()!==E)throw new t("Velora calldata minimum does not match the net output and slippage.");let N=e.unsignedTx({to:x(k.to),data:te,value:ke,chainId:m,description:`Swap ${r.amountIn} base units of ${c.address} for at least ${F} base units of ${l.address} via velora (${Q}). ${Y}`});return ge(N,g),g.data=N.data,I(g),L.tx=N,structuredClone(g)}};for(I(g),ye();n.size>=ae;)n.delete(n.keys().next().value);if(n.set(g.quoteId,L),a)return structuredClone(g);let ee=await L.prepare();return{...ee,...le(ee)}})}async function K(o,s){return p(async()=>{let a=n.get(o);if(!a)throw new t("Quote is unknown or expired. Request a fresh Velora quote.");return v(s,a.wallet,"wallet"),a.prepare()})}async function W(o,s){return p(async()=>{let a=n.get(o);if(!a)throw new t("Quote is unknown or expired. Request a fresh Velora quote.");v(s,a.wallet,"wallet"),I(a.quote);let r=await A(),d=await q(a.quote.input.token.address,s,a.spender,r);return I(a.quote),d.toString()})}async function X(o,s,a={}){return p(async()=>{if(typeof o!="string"||!o.trim())throw new t("Provide a Velora quoteId.");let r=x(s),d=n.get(o);if(!d)throw new t("Quote is unknown or expired. Request a fresh Velora quote.");let{quote:u,spender:C}=d;I(u),v(r,d.wallet,"wallet"),await K(o,r);let c=[],l=j(a.allowance??await W(o,r));u.input.token.address.toLowerCase()!==b.toLowerCase()&&l<BigInt(u.input.amount)&&c.push(e.approval(u.input.token.address,C,u.input.amount,m));let B={...d.tx};ge(B,u),c.push(B),I(u);let S=await e.preview(c,r);I(u);let R=0n,i=S.changes.map(({token:f,amount:w})=>{if(f={...f,address:H(f.address)},!/^-?\d+$/.test(w))throw new t("Preview returned an invalid token amount.");f.address.toLowerCase()===u.output.token.address.toLowerCase()&&(R+=BigInt(w));let h=w.startsWith("-"),$=e.formatAmount(h?w.slice(1):w,f.decimals);return`${h?"-":"+"}${$} ${f.symbol} (${f.address}, chain ${f.chainId}, ${f.decimals} decimals)`});if(R<BigInt(u.minimumOutput.amount))throw new t("Preview retained output is below the accepted minimum.");return{txs:c,preview:S,summary:`Unsigned Velora swap. Minimum output: ${u.minimumOutput.amount} base units of ${u.output.token.address} (${u.output.token.decimals} decimals, chain ${m}). ${u.feeDisclosure} Fee token: ${u.fee.token.address} (${u.fee.token.decimals} decimals). ${S.summary} ${i.join("; ")}`}})}return{name:"velora",swapProvider:{name:"velora",quote:M,build:X,prepareQuote:K,readAllowance:W,quotePrices:(o,s)=>M(o,s,!0)},tools:[{name:"velora_quote",inputSchema:$e,execute:(o,s)=>p(()=>M(he(o),s))},{name:"velora_swap",inputSchema:{type:"object",additionalProperties:!1,required:["quoteId"],properties:{quoteId:{type:"string",minLength:1}}},execute:(o,s)=>p(()=>X(Be(o),s))}]}}var Je=e=>({tools:Fe(e).tools});export{Fe as createModule,Je as createModulePart};
@@ -1 +1 @@
1
- import{a as P}from"../chunks/VZWOWR6G.js";import{a as p}from"../chunks/25EOXUBI.js";import{a as f}from"../chunks/B5RZYFQC.js";import{a as m,c as u}from"../chunks/T5E4OJEU.js";import"../chunks/XN4WDN3O.js";import{getAddress as h}from"viem";function y(i){let n=Array.isArray(i)?i.map((o,e)=>[void 0,o,e]):Object.entries(i).map(([o,e],s)=>[o,e,s]),t=[];for(let[o,e,s]of n){if(typeof e=="function"){let a=o||e.name||`module_${s}`;t.push({name:a,read:e});continue}if(e&&typeof e=="object"){let a=o||e.name||("module"in e?e.module:void 0)||`module_${s}`;typeof e.positions=="function"?t.push({name:a,read:e.positions.bind(e)}):"read"in e&&typeof e.read=="function"&&t.push({name:a,read:e.read.bind(e)})}}return t}function w(i,n){if(!i||typeof i!="object")throw new m(`Module ${n} returned an invalid position.`);if(typeof i.id!="string"||!i.id.trim())throw new m(`Module ${n} returned a position without an id.`);if(!Number.isSafeInteger(i.chainId)||i.chainId<=0)throw new m(`Module ${n} returned a position with an invalid chainId.`);if(!Array.isArray(i.assets))throw new m(`Module ${n} returned a position with invalid assets.`);let t=i.assets.map(o=>({token:{address:o.token.address,symbol:o.token.symbol,decimals:o.token.decimals,chainId:o.token.chainId},amount:f(o.amount).toString()}));return{module:i.module||n,id:i.id,chainId:i.chainId,assets:t,description:i.description}}async function $(i,n=[],t={}){P(i);let o=h(i),e=t.chainId??p,s=y(n),a=await Promise.allSettled(s.map(async r=>{let d=await r.read(o);if(!Array.isArray(d))throw new m(`Module ${r.name} did not return a position list.`);return d.map(c=>w(c,r.name))})),l=[];for(let r=0;r<a.length;r++){let d=a[r],c=s[r];d.status==="fulfilled"?l.push(...d.value):l.push({module:c.name,id:"error",chainId:e,assets:[],description:`${c.name}: ${u(d.reason)}`})}return l}export{$ as getPositions};
1
+ import{a as P}from"../chunks/A5ITAEUQ.js";import{a as f}from"../chunks/I5CQ64EU.js";import{a as p}from"../chunks/ZUC6ILK2.js";import{a as m,d as u}from"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";import{getAddress as h}from"viem";function y(i){let n=Array.isArray(i)?i.map((o,e)=>[void 0,o,e]):Object.entries(i).map(([o,e],s)=>[o,e,s]),t=[];for(let[o,e,s]of n){if(typeof e=="function"){let a=o||e.name||`module_${s}`;t.push({name:a,read:e});continue}if(e&&typeof e=="object"){let a=o||e.name||("module"in e?e.module:void 0)||`module_${s}`;typeof e.positions=="function"?t.push({name:a,read:e.positions.bind(e)}):"read"in e&&typeof e.read=="function"&&t.push({name:a,read:e.read.bind(e)})}}return t}function w(i,n){if(!i||typeof i!="object")throw new m(`Module ${n} returned an invalid position.`);if(typeof i.id!="string"||!i.id.trim())throw new m(`Module ${n} returned a position without an id.`);if(!Number.isSafeInteger(i.chainId)||i.chainId<=0)throw new m(`Module ${n} returned a position with an invalid chainId.`);if(!Array.isArray(i.assets))throw new m(`Module ${n} returned a position with invalid assets.`);let t=i.assets.map(o=>({token:{address:o.token.address,symbol:o.token.symbol,decimals:o.token.decimals,chainId:o.token.chainId},amount:f(o.amount).toString()}));return{module:i.module||n,id:i.id,chainId:i.chainId,assets:t,description:i.description}}async function $(i,n=[],t={}){P(i);let o=h(i),e=t.chainId??p,s=y(n),a=await Promise.allSettled(s.map(async r=>{let d=await r.read(o);if(!Array.isArray(d))throw new m(`Module ${r.name} did not return a position list.`);return d.map(c=>w(c,r.name))})),l=[];for(let r=0;r<a.length;r++){let d=a[r],c=s[r];d.status==="fulfilled"?l.push(...d.value):l.push({module:c.name,id:"error",chainId:e,assets:[],description:`${c.name}: ${u(d.reason)}`})}return l}export{$ as getPositions};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o}from"../chunks/ZKOMJGNH.js";import"../chunks/25EOXUBI.js";import"../chunks/B5RZYFQC.js";import"../chunks/T5E4OJEU.js";import"../chunks/XN4WDN3O.js";export{d as BURNER_NOTE_WALLET,c as NOTE_TTL,a as PRICE_NOTE_NAME,e as PRICE_NOTE_TYPEHASH,b as PRICE_NOTE_VERSION,f as eip712DomainSeparator,m as isWithinNoteGuard,j as noteDigest,g as priceNoteDomain,h as priceNoteDomainSeparator,i as priceNoteStructHash,l as recoverNoteSigner,k as signNote,o as verifyNote,n as verifyNoteOffchain};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o}from"../chunks/6SYTB6FB.js";import"../chunks/I5CQ64EU.js";import"../chunks/ZUC6ILK2.js";import"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";export{d as BURNER_NOTE_WALLET,c as NOTE_TTL,a as PRICE_NOTE_NAME,e as PRICE_NOTE_TYPEHASH,b as PRICE_NOTE_VERSION,f as eip712DomainSeparator,m as isWithinNoteGuard,j as noteDigest,g as priceNoteDomain,h as priceNoteDomainSeparator,i as priceNoteStructHash,l as recoverNoteSigner,k as signNote,o as verifyNote,n as verifyNoteOffchain};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j}from"../chunks/VZPFBWVH.js";import"../chunks/MGEJPRXP.js";import"../chunks/ZKOMJGNH.js";import"../chunks/YTHDLCHL.js";import"../chunks/KFMNCJXJ.js";import"../chunks/6YU3JLQQ.js";import"../chunks/D45AODDL.js";import"../chunks/24JYIH53.js";import"../chunks/VBV366XQ.js";import"../chunks/S3YSJ7XH.js";import"../chunks/LIUXNOLP.js";import"../chunks/P7Q6MJZH.js";import"../chunks/ZUAXW2ZD.js";import"../chunks/64EN6Y7E.js";import"../chunks/SGDWO7XI.js";import"../chunks/Z25UKUJF.js";import"../chunks/VZWOWR6G.js";import"../chunks/5HCXZWUH.js";import"../chunks/UL2L7NHO.js";import"../chunks/25EOXUBI.js";import"../chunks/B5RZYFQC.js";import"../chunks/T5E4OJEU.js";import"../chunks/XN4WDN3O.js";export{a as MAX_PRICE_AGE_SECONDS,b as USD_PARITY_E18,h as assertFreshPrice,j as getPrice,f as isCanonicalEthOrWeth,d as isCanonicalNativeEth,c as isCanonicalUsdg,e as isCanonicalWeth,g as isPriceFresh,i as sqrtRatioAtTick};
1
+ import{a,b,c,d,e,f,g,h,i,j}from"../chunks/SJ7HDRI4.js";import"../chunks/6SYTB6FB.js";import"../chunks/52TGAWSI.js";import"../chunks/3PA2XT75.js";import"../chunks/MOVRI5IV.js";import"../chunks/YX4NVVSX.js";import"../chunks/BHR46XNW.js";import"../chunks/73EABRFC.js";import"../chunks/2IRORNOH.js";import"../chunks/GDP4JSAX.js";import"../chunks/LIUXNOLP.js";import"../chunks/MK6L6TGI.js";import"../chunks/Y3P6SUNL.js";import"../chunks/GIBF3YJO.js";import"../chunks/UCMNB2UP.js";import"../chunks/Z25UKUJF.js";import"../chunks/A5ITAEUQ.js";import"../chunks/I5CQ64EU.js";import"../chunks/NA7HV7BR.js";import"../chunks/5HCXZWUH.js";import"../chunks/M6JGTQRY.js";import"../chunks/ZUC6ILK2.js";import"../chunks/B4MLWDPM.js";import"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";export{a as MAX_PRICE_AGE_SECONDS,b as USD_PARITY_E18,h as assertFreshPrice,j as getPrice,f as isCanonicalEthOrWeth,d as isCanonicalNativeEth,c as isCanonicalUsdg,e as isCanonicalWeth,g as isPriceFresh,i as sqrtRatioAtTick};
@@ -5,6 +5,9 @@ export declare const ENTRY_FLOOR_USD_E18: DecimalString;
5
5
  export declare const ENTRY_CAP_USD_E18: DecimalString;
6
6
  export declare const CONTINUITY_BREAKPOINTS_USD_E18: readonly DecimalString[];
7
7
  export declare const ORACLE_WINDOW_SECONDS = 1800;
8
+ export declare const MIN_BURNER_FLOOR_BPS = 9000n;
9
+ export declare const MAX_BURNER_FLOOR_BPS = 9607n;
10
+ export declare const BURNER_IMPACT_ALLOWANCE_BPS = 150n;
8
11
  export type SwapTradeInput = SwapTrade | {
9
12
  blockNumber?: DecimalString | bigint;
10
13
  logIndex?: number;
@@ -30,7 +33,8 @@ export declare function signupTrackedCount(count: DecimalString | bigint): Decim
30
33
  export declare function oakUsdE18(ethUsdE18: DecimalString | bigint, oakPerEthE18: DecimalString | bigint): DecimalString;
31
34
  export declare function requiredCount(entryE18: DecimalString | bigint, oakUsdE18Value: DecimalString | bigint, oakDecimals?: number | DecimalString): DecimalString;
32
35
  export declare function marketCapUsdE18(supplyNet: DecimalString | bigint, oakUsdE18Value: DecimalString | bigint, oakDecimals?: number | DecimalString): DecimalString;
33
- export declare function burnerMinOut(usdgIn: DecimalString | bigint, oakPerEthE18: DecimalString | bigint, ethUsdE18: DecimalString | bigint, oakDecimals?: number | DecimalString): DecimalString;
36
+ export declare function burnerFloorBps(hookFeeBps: DecimalString | bigint, creatorTaxBps: DecimalString | bigint): DecimalString;
37
+ export declare function burnerMinOut(usdgIn: DecimalString | bigint, oakPerEthE18: DecimalString | bigint, ethUsdE18: DecimalString | bigint, oakDecimals: number | DecimalString, floorBps: DecimalString | bigint): DecimalString;
34
38
  export declare function meanTickFromCumulatives(tickCumulative0: DecimalString | bigint, tickCumulative1: DecimalString | bigint, seconds?: number | DecimalString | bigint): number;
35
39
  export declare function decodeObserveTickCumulatives(callSuccess: boolean, returnData: Hex): readonly [DecimalString, DecimalString];
36
40
  export declare function ethUsdFromSqrtRatioX96(sqrtRatioX96: DecimalString | bigint): DecimalString;
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w}from"../chunks/MGEJPRXP.js";import"../chunks/25EOXUBI.js";import"../chunks/B5RZYFQC.js";import"../chunks/T5E4OJEU.js";import"../chunks/XN4WDN3O.js";export{e as CONTINUITY_BREAKPOINTS_USD_E18,d as ENTRY_CAP_USD_E18,c as ENTRY_FLOOR_USD_E18,b as HOLDER_PRICE_BASE,a as NOHOLD_FLOOR,f as ORACLE_WINDOW_SECONDS,t as averageOakEth30m,u as averageWindowOakEth30m,o as burnerMinOut,v as checkMaxCount,w as checkMaxPrice,q as decodeObserveTickCumulatives,g as entryUsdE18,r as ethUsdFromSqrtRatioX96,n as marketCapUsdE18,p as meanTickFromCumulatives,h as noHoldPriceBase,l as oakUsdE18,m as requiredCount,j as signupBurn,k as signupTrackedCount,i as splitBurn,s as spotOakPerEthFromSqrtPriceX96};
1
+ import{A,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunks/52TGAWSI.js";import"../chunks/I5CQ64EU.js";import"../chunks/ZUC6ILK2.js";import"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";export{i as BURNER_IMPACT_ALLOWANCE_BPS,e as CONTINUITY_BREAKPOINTS_USD_E18,d as ENTRY_CAP_USD_E18,c as ENTRY_FLOOR_USD_E18,b as HOLDER_PRICE_BASE,h as MAX_BURNER_FLOOR_BPS,g as MIN_BURNER_FLOOR_BPS,a as NOHOLD_FLOOR,f as ORACLE_WINDOW_SECONDS,x as averageOakEth30m,y as averageWindowOakEth30m,r as burnerFloorBps,s as burnerMinOut,z as checkMaxCount,A as checkMaxPrice,u as decodeObserveTickCumulatives,j as entryUsdE18,v as ethUsdFromSqrtRatioX96,q as marketCapUsdE18,t as meanTickFromCumulatives,k as noHoldPriceBase,o as oakUsdE18,p as requiredCount,m as signupBurn,n as signupTrackedCount,l as splitBurn,w as spotOakPerEthFromSqrtPriceX96};
@@ -1 +1 @@
1
- import{a}from"../chunks/JMPOXXNJ.js";import"../chunks/ZUAXW2ZD.js";import"../chunks/64EN6Y7E.js";import"../chunks/5HCXZWUH.js";import"../chunks/T5E4OJEU.js";import"../chunks/XN4WDN3O.js";export{a as sharedRoute};
1
+ import{a}from"../chunks/B4FOHEBE.js";import"../chunks/MK6L6TGI.js";import"../chunks/Y3P6SUNL.js";import"../chunks/5HCXZWUH.js";import"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";export{a as sharedRoute};
@@ -1 +1 @@
1
- import{a as o}from"../chunks/T5E4OJEU.js";import"../chunks/XN4WDN3O.js";function p(n,i=[]){let a=[{value:n,path:""}];for(;a.length;){let e=a.pop();if(!(!e.value||typeof e.value!="object"))for(let[t,s]of Object.entries(e.value)){let r=e.path?`${e.path}.${t}`:t,c=t.replace(/[^a-z0-9]/gi,"").toLowerCase();if(/^(?:(?:private|secret|wallet)keys?|mnemonic(?:phrase|words)?|seed(?:phrase|words|hex)?|recovery(?:phrase|words)|passphrase|password|signatures?|(?:raw)?signed(?:tx|transaction)s?|raw(?:tx|transaction)s?|serialized(?:tx|transaction)s?)$/.test(c)&&!(t==="signature"&&i.includes(r)))throw new o("Wallet secrets and signed payloads are not accepted. Sign locally.");s&&typeof s=="object"&&a.push({value:s,path:r})}}}export{p as rejectWalletSecrets};
1
+ import{a as o}from"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";function p(n,i=[]){let a=[{value:n,path:""}];for(;a.length;){let e=a.pop();if(!(!e.value||typeof e.value!="object"))for(let[t,s]of Object.entries(e.value)){let r=e.path?`${e.path}.${t}`:t,c=t.replace(/[^a-z0-9]/gi,"").toLowerCase();if(/^(?:(?:private|secret|wallet)keys?|mnemonic(?:phrase|words)?|seed(?:phrase|words|hex)?|recovery(?:phrase|words)|passphrase|password|signatures?|(?:raw)?signed(?:tx|transaction)s?|raw(?:tx|transaction)s?|serialized(?:tx|transaction)s?)$/.test(c)&&!(t==="signature"&&i.includes(r)))throw new o("Wallet secrets and signed payloads are not accepted. Sign locally.");s&&typeof s=="object"&&a.push({value:s,path:r})}}}export{p as rejectWalletSecrets};
@@ -0,0 +1,45 @@
1
+ import { type PublicClient } from 'viem';
2
+ import type { Address, Token, ToolArgs, UnsignedTx } from './types.js';
3
+ export type SendClient = Pick<PublicClient, 'getChainId' | 'getBalance' | 'getCode' | 'readContract'>;
4
+ export interface SendTerms {
5
+ token: Token;
6
+ amount: string;
7
+ to: Address;
8
+ contractRecipient: boolean;
9
+ }
10
+ export declare const SEND_TOOL: {
11
+ name: string;
12
+ description: string;
13
+ inputSchema: {
14
+ type: "object";
15
+ additionalProperties: boolean;
16
+ required: string[];
17
+ properties: {
18
+ token: {
19
+ type: string;
20
+ description: string;
21
+ };
22
+ amount: {
23
+ type: string;
24
+ description: string;
25
+ };
26
+ to: {
27
+ type: string;
28
+ description: string;
29
+ };
30
+ confirmContract: {
31
+ type: string;
32
+ description: string;
33
+ };
34
+ };
35
+ };
36
+ };
37
+ export declare function sendToken(value: unknown, chainId?: number, oakTokenAddress?: Address): Token;
38
+ export declare function sendTerms(args: ToolArgs, wallet: Address, chainId?: number, oakTokenAddress?: Address): SendTerms;
39
+ export declare function sendDescription(terms: SendTerms): string;
40
+ export declare function sendTransaction(terms: SendTerms): UnsignedTx;
41
+ export declare function prepareSend(args: ToolArgs, wallet: Address, client: SendClient, chainId?: number, oakTokenAddress?: Address): Promise<{
42
+ terms: SendTerms;
43
+ args: ToolArgs;
44
+ txs: UnsignedTx[];
45
+ }>;
@@ -0,0 +1 @@
1
+ import{a as u}from"../chunks/GDP4JSAX.js";import"../chunks/LIUXNOLP.js";import"../chunks/GIBF3YJO.js";import{b as f}from"../chunks/A5ITAEUQ.js";import"../chunks/I5CQ64EU.js";import"../chunks/5HCXZWUH.js";import"../chunks/M6JGTQRY.js";import{i as l,t as c}from"../chunks/ZUC6ILK2.js";import"../chunks/B4MLWDPM.js";import"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";import{encodeFunctionData as E,erc20Abi as b,formatUnits as T,getAddress as d,isAddress as k,zeroAddress as y}from"viem";var U={name:"send",description:"Send ETH or a pinned token from the local wallet. Requires human confirmation, verified identity and subscription. Full recipient and fee shown before signing. ETH all is refused.",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount","to"],properties:{token:{type:"string",description:"ETH, USDG, WETH, USDe, configured OAK, or their pinned token address."},amount:{type:"string",description:"Positive decimal base-unit integer; all is allowed only for ERC-20 tokens."},to:{type:"string",description:"Full EIP-55 checksummed recipient address."},confirmContract:{type:"boolean",description:"Set true only when the user explicitly intends a contract recipient; the human must still approve the full transfer."}}}};function h(e,t=4663,s){let o=t===4663?c.mainnet:t===46630?c.testnet:void 0;if(!o)throw new Error("Send requires an Oak network.");let r=[{address:d(u),symbol:"ETH",decimals:18,chainId:t},{address:d(o.usdg),symbol:"USDG",decimals:6,chainId:t},{address:d(o.weth),symbol:"WETH",decimals:18,chainId:t},...t===4663?[{address:d(l[4663].meridian.CollateralToken_USDe.address),symbol:"USDe",decimals:18,chainId:t}]:[],...s?[{address:d(s),symbol:"OAK",decimals:18,chainId:t}]:[]],n=typeof e=="string"&&r.find(i=>i.address.toLowerCase()===e.toLowerCase()||i.symbol.toUpperCase()===e.replace(/^\$/,"").toUpperCase());if(!n)throw new Error("Send supports only ETH and pinned USDG, WETH, USDe or configured OAK tokens. Unknown tokens are refused.");return n}function w(e,t,s=4663,o){if(Object.keys(e).some(i=>!["token","amount","to","confirmContract"].includes(i))||e.confirmContract!==void 0&&typeof e.confirmContract!="boolean")throw new Error("Provide only token, amount, to and optional confirmContract.");if(typeof e.to!="string"||!k(e.to,{strict:!1})||d(e.to)!==e.to)throw new Error("Provide the full EIP-55 checksummed recipient address.");let r=d(e.to);if(r===y)throw new Error("Cannot send to the zero address.");if(r.toLowerCase()===t.toLowerCase())throw new Error("Cannot send to this wallet itself.");let n=h(e.token,s,o);if(e.amount==="all"&&n.symbol==="ETH")throw new Error("ETH all is refused. Specify base units and leave ETH for network fees.");if(typeof e.amount!="string"||e.amount.length>78||!/^[0-9]+$/.test(e.amount)||BigInt(e.amount)<=0n||BigInt(e.amount)>=2n**256n)throw new Error("Provide a positive decimal base-unit amount string.");return{token:n,amount:BigInt(e.amount).toString(),to:r,contractRecipient:e.confirmContract===!0}}function g(e){return`Send ${T(BigInt(e.amount),e.token.decimals)} ${e.token.symbol} to ${e.to}. Token: ${e.token.address} (${e.token.symbol}, decimals ${e.token.decimals}); amount: ${e.amount} base units; chain ${e.token.chainId}.${e.contractRecipient?" Contract recipient intended: approve this transfer to the full address shown.":""}`}function C(e){let t=e.token.symbol==="ETH";return f({to:t?e.to:e.token.address,data:t?"0x":E({abi:b,functionName:"transfer",args:[e.to,BigInt(e.amount)]}),value:t?e.amount:"0",chainId:e.token.chainId,description:g(e)})}function S(e,t,s){let o=[],r=n=>{typeof n=="string"&&k(n,{strict:!1})?o.push(n.toLowerCase()):n&&typeof n=="object"&&Object.values(n).forEach(r)};return r(t===4663?l[4663]:l[46630]),r(t===4663?c.mainnet:c.testnet),s&&o.push(s.toLowerCase()),o.push(u.toLowerCase()),o.includes(e.toLowerCase())||BigInt(e)<=0x100n}async function $(e,t,s,o=4663,r){let n=structuredClone(e),i=h(n.token,o,r);if(n.amount==="all"&&i.symbol==="ETH")throw new Error("ETH all is refused. Specify base units and leave ETH for network fees.");if(w({...n,amount:n.amount==="all"?"1":n.amount},t,o,r),await s.getChainId()!==o)throw new Error("RPC chain does not match the send network.");let m=i.symbol==="ETH"?await s.getBalance({address:t,blockTag:"pending"}):await s.readContract({address:i.address,abi:b,functionName:"balanceOf",args:[t],blockTag:"pending"});n.amount==="all"&&(n.amount=m.toString());let a=w(n,t,o,r);if(BigInt(a.amount)>m)throw new Error(`Send amount exceeds the ${i.symbol} balance.`);let p=await s.getCode({address:a.to,blockTag:"pending"})??"0x";if(!/^0x(?:[0-9a-fA-F]{2})*$/.test(p))throw new Error("Recipient code is unavailable; retry with a code-capable RPC.");if((p!=="0x"||S(a.to,o,r))&&!a.contractRecipient)throw new Error(`Recipient ${a.to} is a contract or known protocol address. Ask the user to confirm this is intended, then set confirmContract true.`);return{terms:a,args:{...n,token:i.address,amount:a.amount},txs:[C(a)]}}export{U as SEND_TOOL,$ as prepareSend,g as sendDescription,w as sendTerms,h as sendToken,C as sendTransaction};
@@ -1 +1 @@
1
- import{a,b,c}from"../chunks/S3YSJ7XH.js";import"../chunks/LIUXNOLP.js";import"../chunks/P7Q6MJZH.js";import"../chunks/VZWOWR6G.js";import"../chunks/5HCXZWUH.js";import"../chunks/UL2L7NHO.js";import"../chunks/25EOXUBI.js";import"../chunks/B5RZYFQC.js";import"../chunks/T5E4OJEU.js";import"../chunks/XN4WDN3O.js";export{a as NATIVE_TOKEN_ADDRESS,c as createPreview,b as normalizeNativeTokenAddress};
1
+ import{a,b,c}from"../chunks/GDP4JSAX.js";import"../chunks/LIUXNOLP.js";import"../chunks/GIBF3YJO.js";import"../chunks/A5ITAEUQ.js";import"../chunks/I5CQ64EU.js";import"../chunks/5HCXZWUH.js";import"../chunks/M6JGTQRY.js";import"../chunks/ZUC6ILK2.js";import"../chunks/B4MLWDPM.js";import"../chunks/NGAI6GTU.js";import"../chunks/JXOEJPJ4.js";export{a as NATIVE_TOKEN_ADDRESS,c as createPreview,b as normalizeNativeTokenAddress};