@oakagentkit/core 0.2.6 → 0.2.7

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 (651) hide show
  1. package/build/dist/api/abort-scope.d.ts +2 -0
  2. package/build/dist/api/abort-scope.js +1 -0
  3. package/build/dist/api/chain.js +1 -1
  4. package/build/dist/api/history.js +1 -1
  5. package/build/dist/api/http.js +1 -1
  6. package/build/dist/api/metadata.js +1 -1
  7. package/build/dist/api/modules/beefy/boosts.js +1 -1
  8. package/build/dist/api/modules/beefy/clm.js +1 -1
  9. package/build/dist/api/modules/beefy/guard.js +1 -1
  10. package/build/dist/api/modules/beefy/index.js +1 -1
  11. package/build/dist/api/modules/beefy/liquidity.js +1 -1
  12. package/build/dist/api/modules/beefy/management.js +1 -1
  13. package/build/dist/api/modules/beefy/vaults.js +1 -1
  14. package/build/dist/api/modules/borro/actions.js +1 -1
  15. package/build/dist/api/modules/borro/checks.js +1 -1
  16. package/build/dist/api/modules/borro/copy.d.ts +15 -10
  17. package/build/dist/api/modules/borro/copy.js +1 -1
  18. package/build/dist/api/modules/borro/index.js +1 -1
  19. package/build/dist/api/modules/borro/liquidity.js +1 -1
  20. package/build/dist/api/modules/borro/positions.js +1 -1
  21. package/build/dist/api/modules/borro/reader.js +1 -1
  22. package/build/dist/api/modules/chop/abi.d.ts +31 -0
  23. package/build/dist/api/modules/chop/abi.js +1 -1
  24. package/build/dist/api/modules/chop/actions.js +1 -1
  25. package/build/dist/api/modules/chop/checks.d.ts +13 -5
  26. package/build/dist/api/modules/chop/checks.js +1 -1
  27. package/build/dist/api/modules/chop/copy.d.ts +11 -1
  28. package/build/dist/api/modules/chop/copy.js +1 -1
  29. package/build/dist/api/modules/chop/guard.js +1 -1
  30. package/build/dist/api/modules/chop/index.js +1 -1
  31. package/build/dist/api/modules/chop/positions.js +1 -1
  32. package/build/dist/api/modules/chop/reader.d.ts +132 -7
  33. package/build/dist/api/modules/chop/reader.js +1 -1
  34. package/build/dist/api/modules/chop/types.d.ts +12 -0
  35. package/build/dist/api/modules/clanker/extensions.d.ts +9 -0
  36. package/build/dist/api/modules/clanker/extensions.js +1 -1
  37. package/build/dist/api/modules/clanker/index.js +1 -1
  38. package/build/dist/api/modules/clanker/manage.js +1 -1
  39. package/build/dist/api/modules/clanker/pool-config.d.ts +15 -0
  40. package/build/dist/api/modules/clanker/pool-config.js +1 -1
  41. package/build/dist/api/modules/clanker/protocol.js +1 -1
  42. package/build/dist/api/modules/earn/copy.d.ts +32 -10
  43. package/build/dist/api/modules/earn/copy.js +1 -1
  44. package/build/dist/api/modules/earn/cost.d.ts +11 -1
  45. package/build/dist/api/modules/earn/cost.js +1 -1
  46. package/build/dist/api/modules/earn/index.js +1 -1
  47. package/build/dist/api/modules/earn/lp.d.ts +14 -1
  48. package/build/dist/api/modules/earn/lp.js +1 -1
  49. package/build/dist/api/modules/earn/options.d.ts +6 -4
  50. package/build/dist/api/modules/earn/options.js +1 -1
  51. package/build/dist/api/modules/erc8004/common.d.ts +1 -1
  52. package/build/dist/api/modules/erc8004/common.js +1 -1
  53. package/build/dist/api/modules/erc8004/domain.js +1 -1
  54. package/build/dist/api/modules/erc8004/index.js +1 -1
  55. package/build/dist/api/modules/erc8004/management.js +1 -1
  56. package/build/dist/api/modules/erc8004/reputation.js +1 -1
  57. package/build/dist/api/modules/erc8004/services.js +1 -1
  58. package/build/dist/api/modules/erc8004/validation.js +1 -1
  59. package/build/dist/api/modules/factor/abi.d.ts +642 -0
  60. package/build/dist/api/modules/factor/abi.js +1 -0
  61. package/build/dist/api/modules/factor/actions.d.ts +15 -0
  62. package/build/dist/api/modules/factor/actions.js +1 -0
  63. package/build/dist/api/modules/factor/api.d.ts +7 -0
  64. package/build/dist/api/modules/factor/api.js +1 -0
  65. package/build/dist/api/modules/factor/checks.d.ts +11 -0
  66. package/build/dist/api/modules/factor/checks.js +1 -0
  67. package/build/dist/api/modules/factor/copy.d.ts +33 -0
  68. package/build/dist/api/modules/factor/copy.js +1 -0
  69. package/build/dist/api/modules/factor/guard.d.ts +12 -0
  70. package/build/dist/api/modules/factor/guard.js +1 -0
  71. package/build/dist/api/modules/factor/index.d.ts +16 -0
  72. package/build/dist/api/modules/factor/index.js +8 -0
  73. package/build/dist/api/modules/factor/messages.d.ts +46 -0
  74. package/build/dist/api/modules/factor/messages.js +1 -0
  75. package/build/dist/api/modules/factor/pins.d.ts +64 -0
  76. package/build/dist/api/modules/factor/pins.js +1 -0
  77. package/build/dist/api/modules/factor/reader.d.ts +17 -0
  78. package/build/dist/api/modules/factor/reader.js +1 -0
  79. package/build/dist/api/modules/factor/types.d.ts +18 -0
  80. package/build/dist/api/modules/factor/types.js +0 -0
  81. package/build/dist/api/modules/gloam/copy.d.ts +4 -3
  82. package/build/dist/api/modules/gloam/copy.js +2 -2
  83. package/build/dist/api/modules/gloam/index.js +1 -1
  84. package/build/dist/api/modules/grove/index.js +1 -1
  85. package/build/dist/api/modules/heyresearch/builder-feed.js +1 -1
  86. package/build/dist/api/modules/heyresearch/index.js +1 -1
  87. package/build/dist/api/modules/heyresearch/public-reads.d.ts +29 -1
  88. package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
  89. package/build/dist/api/modules/heyresearch/scan.js +1 -1
  90. package/build/dist/api/modules/heyresearch/status-labels.d.ts +2 -0
  91. package/build/dist/api/modules/heyresearch/status-labels.js +1 -1
  92. package/build/dist/api/modules/heyresearch/token-facts.js +1 -1
  93. package/build/dist/api/modules/hoodag/chain-reads.js +1 -1
  94. package/build/dist/api/modules/hoodag/index.js +1 -1
  95. package/build/dist/api/modules/hoodag/management.js +1 -1
  96. package/build/dist/api/modules/hoodag/public-reads.js +1 -1
  97. package/build/dist/api/modules/hoodag/reconstruct.js +1 -1
  98. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  99. package/build/dist/api/modules/hoodlock/commerce.js +1 -1
  100. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  101. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  102. package/build/dist/api/modules/hoodlock/index.js +1 -1
  103. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  104. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  105. package/build/dist/api/modules/hoodlock/public.js +1 -1
  106. package/build/dist/api/modules/hookr/actions.js +1 -1
  107. package/build/dist/api/modules/hookr/addons.js +1 -1
  108. package/build/dist/api/modules/hookr/agent-gate.js +1 -1
  109. package/build/dist/api/modules/hookr/contracts.d.ts +2 -1
  110. package/build/dist/api/modules/hookr/contracts.js +1 -1
  111. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  112. package/build/dist/api/modules/hookr/discovery.js +1 -1
  113. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  114. package/build/dist/api/modules/hookr/index.js +1 -1
  115. package/build/dist/api/modules/hookr/launch-options.js +1 -1
  116. package/build/dist/api/modules/hookr/launch-receipt.js +1 -1
  117. package/build/dist/api/modules/hookr/launch.js +1 -1
  118. package/build/dist/api/modules/hookr/liquidity.js +1 -1
  119. package/build/dist/api/modules/hookr/lp-positions.js +1 -1
  120. package/build/dist/api/modules/hookr/lp-reads.d.ts +2 -0
  121. package/build/dist/api/modules/hookr/lp-reads.js +1 -1
  122. package/build/dist/api/modules/hookr/lp-receipt.js +1 -1
  123. package/build/dist/api/modules/hookr/lp-state.js +1 -1
  124. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  125. package/build/dist/api/modules/hookr/read-utils.js +1 -1
  126. package/build/dist/api/modules/hookr/relay.js +1 -1
  127. package/build/dist/api/modules/hookr/revenue.js +1 -1
  128. package/build/dist/api/modules/kyberswap/index.js +1 -1
  129. package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
  130. package/build/dist/api/modules/layerbank/actions.js +1 -1
  131. package/build/dist/api/modules/layerbank/index.js +1 -1
  132. package/build/dist/api/modules/layerbank/merkl.js +1 -1
  133. package/build/dist/api/modules/layerbank/reader.js +1 -1
  134. package/build/dist/api/modules/lighter/index.js +1 -1
  135. package/build/dist/api/modules/longbow/administration.js +1 -1
  136. package/build/dist/api/modules/longbow/fixed.js +1 -1
  137. package/build/dist/api/modules/longbow/index.js +1 -1
  138. package/build/dist/api/modules/longbow/nft.js +1 -1
  139. package/build/dist/api/modules/longbow/rebates.js +1 -1
  140. package/build/dist/api/modules/longbow/staking.js +1 -1
  141. package/build/dist/api/modules/meridian/index.js +1 -1
  142. package/build/dist/api/modules/meridian/markets.js +1 -1
  143. package/build/dist/api/modules/meridian/perps-batch.js +1 -1
  144. package/build/dist/api/modules/meridian/perps-stream.js +1 -1
  145. package/build/dist/api/modules/meridian/perps.js +1 -1
  146. package/build/dist/api/modules/meridian/predict-read.js +1 -1
  147. package/build/dist/api/modules/meridian/rfq.js +1 -1
  148. package/build/dist/api/modules/merkl/discovery.js +1 -1
  149. package/build/dist/api/modules/merkl/index.js +1 -1
  150. package/build/dist/api/modules/merkl/manage.js +1 -1
  151. package/build/dist/api/modules/merkl/protocol.js +1 -1
  152. package/build/dist/api/modules/morpho/allocator.js +1 -1
  153. package/build/dist/api/modules/morpho/bundles.js +1 -1
  154. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  155. package/build/dist/api/modules/morpho/index.js +1 -1
  156. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  157. package/build/dist/api/modules/morpho/midnight.js +1 -1
  158. package/build/dist/api/modules/morpho/protocol.js +1 -1
  159. package/build/dist/api/modules/morpho/vault-management.js +1 -1
  160. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  161. package/build/dist/api/modules/morpho/vault-v2.d.ts +2 -0
  162. package/build/dist/api/modules/morpho/vault-v2.js +1 -1
  163. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  164. package/build/dist/api/modules/netnet/card-read.js +1 -1
  165. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  166. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  167. package/build/dist/api/modules/netnet/desk-read.js +1 -1
  168. package/build/dist/api/modules/netnet/financial.js +1 -1
  169. package/build/dist/api/modules/netnet/index.js +1 -1
  170. package/build/dist/api/modules/netnet/staking.js +1 -1
  171. package/build/dist/api/modules/orbio/gateway.js +1 -1
  172. package/build/dist/api/modules/orbio/index.js +1 -1
  173. package/build/dist/api/modules/pendle/convert.js +1 -1
  174. package/build/dist/api/modules/pendle/costs.js +1 -1
  175. package/build/dist/api/modules/pendle/index.js +1 -1
  176. package/build/dist/api/modules/pendle/markets.js +1 -1
  177. package/build/dist/api/modules/pendle/positions.js +1 -1
  178. package/build/dist/api/modules/pendle/pricecheck.js +1 -1
  179. package/build/dist/api/modules/pendle/reader.js +1 -1
  180. package/build/dist/api/modules/pendle/redeem.js +1 -1
  181. package/build/dist/api/modules/pendle/trade.js +1 -1
  182. package/build/dist/api/modules/pendle/validate.js +1 -1
  183. package/build/dist/api/modules/pons/claim.js +1 -1
  184. package/build/dist/api/modules/pons/holder-directory.js +1 -1
  185. package/build/dist/api/modules/pons/index.js +1 -1
  186. package/build/dist/api/modules/pons/launch-status.js +1 -1
  187. package/build/dist/api/modules/pons/reads.js +1 -1
  188. package/build/dist/api/modules/pons/trade.d.ts +3 -2
  189. package/build/dist/api/modules/pons/trade.js +1 -1
  190. package/build/dist/api/modules/poolstrade/index.js +1 -1
  191. package/build/dist/api/modules/priors/coverage.js +1 -1
  192. package/build/dist/api/modules/priors/discovery.js +1 -1
  193. package/build/dist/api/modules/priors/features.js +1 -1
  194. package/build/dist/api/modules/priors/holdings.js +1 -1
  195. package/build/dist/api/modules/priors/index.js +1 -1
  196. package/build/dist/api/modules/priors/integration.d.ts +1 -0
  197. package/build/dist/api/modules/priors/integration.js +1 -1
  198. package/build/dist/api/modules/priors/market.js +1 -1
  199. package/build/dist/api/modules/priors/pt.js +1 -1
  200. package/build/dist/api/modules/priors/savings-exit.js +1 -1
  201. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  202. package/build/dist/api/modules/raeto/authorization.d.ts +30 -0
  203. package/build/dist/api/modules/raeto/authorization.js +1 -0
  204. package/build/dist/api/modules/raeto/copy.d.ts +46 -0
  205. package/build/dist/api/modules/raeto/copy.js +1 -0
  206. package/build/dist/api/modules/raeto/errors.d.ts +4 -0
  207. package/build/dist/api/modules/raeto/errors.js +1 -0
  208. package/build/dist/api/modules/raeto/estimate.d.ts +2 -0
  209. package/build/dist/api/modules/raeto/estimate.js +1 -0
  210. package/build/dist/api/modules/raeto/index.d.ts +16 -0
  211. package/build/dist/api/modules/raeto/index.js +1 -0
  212. package/build/dist/api/modules/raeto/pairing.d.ts +40 -0
  213. package/build/dist/api/modules/raeto/pairing.js +1 -0
  214. package/build/dist/api/modules/raeto/pins.d.ts +24 -0
  215. package/build/dist/api/modules/raeto/pins.js +1 -0
  216. package/build/dist/api/modules/raeto/templates.d.ts +22 -0
  217. package/build/dist/api/modules/raeto/templates.js +1 -0
  218. package/build/dist/api/modules/raeto/terms.d.ts +8 -0
  219. package/build/dist/api/modules/raeto/terms.js +1 -0
  220. package/build/dist/api/modules/raeto/types.d.ts +64 -0
  221. package/build/dist/api/modules/raeto/types.js +0 -0
  222. package/build/dist/api/modules/relay/api.d.ts +16 -0
  223. package/build/dist/api/modules/relay/api.js +1 -1
  224. package/build/dist/api/modules/relay/discovery.js +1 -1
  225. package/build/dist/api/modules/relay/inbound.js +1 -1
  226. package/build/dist/api/modules/relay/index.d.ts +1 -0
  227. package/build/dist/api/modules/relay/index.js +1 -1
  228. package/build/dist/api/modules/relay/order.js +1 -1
  229. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  230. package/build/dist/api/modules/relay/readiness.d.ts +1 -0
  231. package/build/dist/api/modules/relay/readiness.js +1 -1
  232. package/build/dist/api/modules/relay/reads.js +1 -1
  233. package/build/dist/api/modules/relay/vaults.js +1 -1
  234. package/build/dist/api/modules/spark/actions.js +1 -1
  235. package/build/dist/api/modules/spark/index.js +1 -1
  236. package/build/dist/api/modules/spark/management.js +1 -1
  237. package/build/dist/api/modules/steakhouse/analytics.js +1 -1
  238. package/build/dist/api/modules/steakhouse/erc4626.js +1 -1
  239. package/build/dist/api/modules/steakhouse/index.js +1 -1
  240. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  241. package/build/dist/api/modules/steakhouse/management.js +1 -1
  242. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  243. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  244. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  245. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  246. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  247. package/build/dist/api/modules/tickerspring/index.js +1 -1
  248. package/build/dist/api/modules/tickerspring/journeys.d.ts +1 -0
  249. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  250. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  251. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  252. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  253. package/build/dist/api/modules/tickerspring/research.js +1 -1
  254. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  255. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  256. package/build/dist/api/modules/uniswap/auction.js +1 -1
  257. package/build/dist/api/modules/uniswap/batch.js +1 -1
  258. package/build/dist/api/modules/uniswap/common.js +1 -1
  259. package/build/dist/api/modules/uniswap/fee-percent.d.ts +4 -0
  260. package/build/dist/api/modules/uniswap/fee-percent.js +1 -0
  261. package/build/dist/api/modules/uniswap/fees.js +1 -1
  262. package/build/dist/api/modules/uniswap/index.js +1 -1
  263. package/build/dist/api/modules/uniswap/local-guard.d.ts +2 -0
  264. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  265. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  266. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  267. package/build/dist/api/modules/uniswap/pools.d.ts +2 -0
  268. package/build/dist/api/modules/uniswap/pools.js +1 -1
  269. package/build/dist/api/modules/uniswap/position.js +1 -1
  270. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  271. package/build/dist/api/modules/uniswap/quote-guard.d.ts +38 -0
  272. package/build/dist/api/modules/uniswap/quote-guard.js +1 -0
  273. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  274. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  275. package/build/dist/api/modules/uniswap/trade.d.ts +10 -3
  276. package/build/dist/api/modules/uniswap/trade.js +1 -1
  277. package/build/dist/api/modules/uniswap/v2.js +1 -1
  278. package/build/dist/api/modules/uniswap/v3.js +1 -1
  279. package/build/dist/api/modules/uniswap/v4.d.ts +6 -0
  280. package/build/dist/api/modules/uniswap/v4.js +1 -1
  281. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  282. package/build/dist/api/modules/velora/claims.js +1 -1
  283. package/build/dist/api/modules/velora/delta-reads.js +1 -1
  284. package/build/dist/api/modules/velora/index.js +1 -1
  285. package/build/dist/api/modules/wormhole/index.js +1 -1
  286. package/build/dist/api/modules/wormhole/scan-text.js +1 -1
  287. package/build/dist/api/modules/wormhole/swap-token-verdict.js +1 -1
  288. package/build/dist/api/modules/wormhole/third-party-text.d.ts +14 -3
  289. package/build/dist/api/modules/wormhole/third-party-text.js +1 -1
  290. package/build/dist/api/modules/wormhole/token-check.js +1 -1
  291. package/build/dist/api/modules/wormhole/x402-client.js +1 -1
  292. package/build/dist/api/oak-fee.d.ts +12 -0
  293. package/build/dist/api/oak-fee.js +1 -0
  294. package/build/dist/api/param-text.d.ts +22 -0
  295. package/build/dist/api/param-text.js +1 -0
  296. package/build/dist/api/position-economics.d.ts +70 -0
  297. package/build/dist/api/position-economics.js +1 -0
  298. package/build/dist/api/positions.d.ts +8 -5
  299. package/build/dist/api/positions.js +1 -1
  300. package/build/dist/api/prices.d.ts +3 -0
  301. package/build/dist/api/prices.js +1 -1
  302. package/build/dist/api/progress.d.ts +7 -0
  303. package/build/dist/api/progress.js +1 -0
  304. package/build/dist/api/read-budgets.d.ts +4 -0
  305. package/build/dist/api/read-budgets.js +1 -0
  306. package/build/dist/api/read-shape.d.ts +45 -0
  307. package/build/dist/api/read-shape.js +1 -0
  308. package/build/dist/api/revert.d.ts +23 -0
  309. package/build/dist/api/revert.js +1 -0
  310. package/build/dist/api/routes.js +1 -1
  311. package/build/dist/api/rpc.d.ts +1 -0
  312. package/build/dist/api/rpc.js +1 -1
  313. package/build/dist/api/secret-fields.js +1 -1
  314. package/build/dist/api/send.js +1 -1
  315. package/build/dist/api/signing-registry.d.ts +8 -0
  316. package/build/dist/api/signing-registry.js +1 -1
  317. package/build/dist/api/simulate.js +1 -1
  318. package/build/dist/api/swap.d.ts +4 -0
  319. package/build/dist/api/swap.js +1 -1
  320. package/build/dist/api/tokens.d.ts +1 -0
  321. package/build/dist/api/tokens.js +1 -1
  322. package/build/dist/api/tool-policy.js +1 -1
  323. package/build/dist/api/types.d.ts +3 -0
  324. package/build/dist/api/untrusted-unwrap.d.ts +1 -0
  325. package/build/dist/api/untrusted-unwrap.js +1 -0
  326. package/build/dist/api/usd-estimate.d.ts +23 -0
  327. package/build/dist/api/usd-estimate.js +1 -0
  328. package/build/dist/api/vendor-limits.js +1 -1
  329. package/build/dist/chunks/{T7TFUH5K.js → 2E4I7CJ7.js} +1 -1
  330. package/build/dist/chunks/2FHELZ7Y.js +1 -0
  331. package/build/dist/chunks/2GXHYI23.js +1 -0
  332. package/build/dist/chunks/2LWBN35N.js +1 -0
  333. package/build/dist/chunks/{4HG6FRVH.js → 2OKYXT25.js} +1 -1
  334. package/build/dist/chunks/2SUHQWND.js +1 -0
  335. package/build/dist/chunks/2ZWKIBJT.js +1 -0
  336. package/build/dist/chunks/32RXFUOH.js +1 -0
  337. package/build/dist/chunks/3CH2IPQL.js +1 -0
  338. package/build/dist/chunks/3DNJTJ2X.js +1 -0
  339. package/build/dist/chunks/3K2N5VFH.js +1 -0
  340. package/build/dist/chunks/3VBIRLU3.js +1 -0
  341. package/build/dist/chunks/3ZABD6ZF.js +2 -0
  342. package/build/dist/chunks/44MB6SA6.js +1 -0
  343. package/build/dist/chunks/4D4ZRZUW.js +1 -0
  344. package/build/dist/chunks/{IPN6Z4JM.js → 4FPV4CRC.js} +1 -1
  345. package/build/dist/chunks/4GNUXN4K.js +1 -0
  346. package/build/dist/chunks/{K4DHHQBI.js → 4JRXEN7C.js} +2 -2
  347. package/build/dist/chunks/4JTTA3BX.js +1 -0
  348. package/build/dist/chunks/4OVIMYNH.js +2 -0
  349. package/build/dist/chunks/{7QIO77VE.js → 4Q2ZBZXM.js} +1 -1
  350. package/build/dist/chunks/4RQAOOO2.js +1 -0
  351. package/build/dist/chunks/4TTDAF4B.js +1 -0
  352. package/build/dist/chunks/523ZIR3J.js +1 -0
  353. package/build/dist/chunks/5DPJQCKJ.js +68 -0
  354. package/build/dist/chunks/5HIHUYA4.js +1 -0
  355. package/build/dist/chunks/5PI57UC2.js +1 -0
  356. package/build/dist/chunks/5RXALTDT.js +1 -0
  357. package/build/dist/chunks/5TUXSOMI.js +1 -0
  358. package/build/dist/chunks/5UAXLWJ2.js +1 -0
  359. package/build/dist/chunks/5XAXJEWM.js +5 -0
  360. package/build/dist/chunks/67BWOVET.js +1 -0
  361. package/build/dist/chunks/6NUNCD5J.js +1 -0
  362. package/build/dist/chunks/{FJ4S4GHY.js → 6PZGDVHV.js} +1 -1
  363. package/build/dist/chunks/{RTAHNWHN.js → 6UVGQYZ3.js} +1 -1
  364. package/build/dist/chunks/753HZZTY.js +1 -0
  365. package/build/dist/chunks/7D73A6KS.js +1 -0
  366. package/build/dist/chunks/7MBVTNLU.js +1 -0
  367. package/build/dist/chunks/7QKYDNF6.js +18 -0
  368. package/build/dist/chunks/7VC53B5X.js +70 -0
  369. package/build/dist/chunks/7VNO46LV.js +1 -0
  370. package/build/dist/chunks/ACH4BSME.js +3 -0
  371. package/build/dist/chunks/AHUCYDBC.js +1 -0
  372. package/build/dist/chunks/AI3VAPA3.js +1 -0
  373. package/build/dist/chunks/AMTRDPVO.js +1 -0
  374. package/build/dist/chunks/APHNOGNS.js +1 -0
  375. package/build/dist/chunks/{BND2UFVW.js → ARI72OYT.js} +1 -1
  376. package/build/dist/chunks/ARLGF5MU.js +1 -0
  377. package/build/dist/chunks/BAIY32AV.js +1 -0
  378. package/build/dist/chunks/BB765L75.js +3 -0
  379. package/build/dist/chunks/BE3A7677.js +1 -0
  380. package/build/dist/chunks/{PAY5PD4H.js → BX46C5ZP.js} +1 -1
  381. package/build/dist/chunks/{XL3LLGIR.js → BZ34ZR65.js} +1 -1
  382. package/build/dist/chunks/C3WBHFLX.js +1 -0
  383. package/build/dist/chunks/C75MT5SD.js +1 -0
  384. package/build/dist/chunks/CAWTAR5V.js +1 -0
  385. package/build/dist/chunks/CNLL4NCR.js +1 -0
  386. package/build/dist/chunks/CO4GCF4L.js +1 -0
  387. package/build/dist/chunks/{P5PYFK7L.js → CQ5WRWV4.js} +1 -1
  388. package/build/dist/chunks/{SJJR4ZBZ.js → CSDN4MYP.js} +1 -1
  389. package/build/dist/chunks/CSOO4SW7.js +1 -0
  390. package/build/dist/chunks/CZL6T2ZQ.js +1 -0
  391. package/build/dist/chunks/D742AYEV.js +1 -0
  392. package/build/dist/chunks/DGCJZ3HO.js +1 -0
  393. package/build/dist/chunks/DNNFKDZR.js +1 -0
  394. package/build/dist/chunks/DPE7SPW7.js +1 -0
  395. package/build/dist/chunks/DSTMEY5F.js +1 -0
  396. package/build/dist/chunks/{FUDAXV5X.js → DYYEA5HB.js} +1 -1
  397. package/build/dist/chunks/EFESPGA2.js +1 -0
  398. package/build/dist/chunks/EGZREEG2.js +1 -0
  399. package/build/dist/chunks/EH5G4O3U.js +1 -0
  400. package/build/dist/chunks/EI6GGPDS.js +20 -0
  401. package/build/dist/chunks/EVBHQQQG.js +1 -0
  402. package/build/dist/chunks/EZZM2GQT.js +2 -0
  403. package/build/dist/chunks/F3VDVTMS.js +1 -0
  404. package/build/dist/chunks/F4UQEPJT.js +1 -0
  405. package/build/dist/chunks/FHTNMGFR.js +1 -0
  406. package/build/dist/chunks/FJLJ7ZQ5.js +1 -0
  407. package/build/dist/chunks/{WP6RHXGN.js → FL5SSHUL.js} +1 -1
  408. package/build/dist/chunks/FNGIJKMZ.js +1 -0
  409. package/build/dist/chunks/{KIFZ5ZSK.js → FOD34G2H.js} +1 -1
  410. package/build/dist/chunks/{WV3A3OUU.js → FOKEFXGP.js} +1 -1
  411. package/build/dist/chunks/FV4WZOTD.js +1 -0
  412. package/build/dist/chunks/FWIFTPSE.js +2 -0
  413. package/build/dist/chunks/FZ6IJZZM.js +1 -0
  414. package/build/dist/chunks/G2LAO23N.js +1 -0
  415. package/build/dist/chunks/GDRQ2ANN.js +1 -0
  416. package/build/dist/chunks/GG24LO2R.js +1 -0
  417. package/build/dist/chunks/GLF7WEY2.js +1 -0
  418. package/build/dist/chunks/GQ3XZFRL.js +1 -0
  419. package/build/dist/chunks/{QU5XKRGK.js → GQYV4TFO.js} +1 -1
  420. package/build/dist/chunks/GRSXWQWD.js +1 -0
  421. package/build/dist/chunks/{DL6AEWEM.js → GSFHM5L3.js} +1 -1
  422. package/build/dist/chunks/{QHBS3PVU.js → H5DY7CNB.js} +1 -1
  423. package/build/dist/chunks/HCBX4NFM.js +1 -0
  424. package/build/dist/chunks/HHO5ISMM.js +1 -0
  425. package/build/dist/chunks/HIX5N25Z.js +1 -0
  426. package/build/dist/chunks/HKVQ646Q.js +1 -0
  427. package/build/dist/chunks/IEG6GLFR.js +1 -0
  428. package/build/dist/chunks/INOYMBWE.js +1 -0
  429. package/build/dist/chunks/IV4K7FMD.js +1 -0
  430. package/build/dist/chunks/{PIIHOXWF.js → J73ATSEQ.js} +1 -1
  431. package/build/dist/chunks/JBTOZ6IH.js +1 -0
  432. package/build/dist/chunks/JESMX2UC.js +1 -0
  433. package/build/dist/chunks/JJGZ7W3V.js +1 -0
  434. package/build/dist/chunks/JKRBGAX2.js +1 -0
  435. package/build/dist/chunks/JLRHM2DQ.js +1 -0
  436. package/build/dist/chunks/JOKL5L6X.js +1 -0
  437. package/build/dist/chunks/JS53DQVT.js +1 -0
  438. package/build/dist/chunks/{WIRBCS4W.js → JWR5XVP2.js} +1 -1
  439. package/build/dist/chunks/{JFYBH3DX.js → K6D6SDIG.js} +1 -1
  440. package/build/dist/chunks/K7HTDKAT.js +1 -0
  441. package/build/dist/chunks/{2VXLVXIB.js → KDGSYNOP.js} +1 -1
  442. package/build/dist/chunks/KKPMOAVI.js +1 -0
  443. package/build/dist/chunks/KREBNL2D.js +1 -0
  444. package/build/dist/chunks/L646YWDP.js +1 -0
  445. package/build/dist/chunks/{GSBIERZD.js → LR4XTZ37.js} +1 -1
  446. package/build/dist/chunks/LVFI74ST.js +1 -0
  447. package/build/dist/chunks/{QBIY6FQN.js → M7ZXDLKM.js} +1 -1
  448. package/build/dist/chunks/MVD3KWPP.js +1 -0
  449. package/build/dist/chunks/N245WC5R.js +1 -0
  450. package/build/dist/chunks/{WTXC3XKW.js → N4XNNXOJ.js} +1 -1
  451. package/build/dist/chunks/N6GIC7HJ.js +1 -0
  452. package/build/dist/chunks/{RUC7KH7A.js → NA424YAL.js} +1 -1
  453. package/build/dist/chunks/NUFZUKYS.js +1 -0
  454. package/build/dist/chunks/{XD6X3KTC.js → O3JWCJIF.js} +1 -1
  455. package/build/dist/chunks/OARVU3RC.js +1 -0
  456. package/build/dist/chunks/OEZ7FCLF.js +1 -0
  457. package/build/dist/chunks/{H43RNCX2.js → OUROA7XR.js} +1 -1
  458. package/build/dist/chunks/{2MT3G7YZ.js → OYJFXEDU.js} +1 -1
  459. package/build/dist/chunks/OYPAVXGQ.js +1 -0
  460. package/build/dist/chunks/{SMYWWIE6.js → OZ5MDUD2.js} +1 -1
  461. package/build/dist/chunks/P6OMKZMR.js +3 -0
  462. package/build/dist/chunks/PV4AK32X.js +1 -0
  463. package/build/dist/chunks/{HKEMQBFA.js → PXVREXCS.js} +1 -1
  464. package/build/dist/chunks/PZEF5LBL.js +2 -0
  465. package/build/dist/chunks/Q2ACLVWR.js +1 -0
  466. package/build/dist/chunks/QFSBDPLN.js +1 -0
  467. package/build/dist/chunks/QJNLLI6N.js +1 -0
  468. package/build/dist/chunks/QMZEGT5B.js +1 -0
  469. package/build/dist/chunks/{PNA6UIE5.js → REWXG6X6.js} +1 -1
  470. package/build/dist/chunks/{ALLLYOUG.js → RLI4JDOL.js} +1 -1
  471. package/build/dist/chunks/{UD2XMNIT.js → RLMVA575.js} +1 -1
  472. package/build/dist/chunks/RPB46QAC.js +1 -0
  473. package/build/dist/chunks/{Q42YI3EP.js → RT7IU6TI.js} +1 -1
  474. package/build/dist/chunks/{ER47KGRM.js → SBY4RJ7I.js} +1 -1
  475. package/build/dist/chunks/SCG5HWMN.js +1 -0
  476. package/build/dist/chunks/{XQA5LCL6.js → SENOU5JR.js} +1 -1
  477. package/build/dist/chunks/SKEKXEUU.js +1 -0
  478. package/build/dist/chunks/SOTYQGPT.js +1 -0
  479. package/build/dist/chunks/SZ466I5X.js +1 -0
  480. package/build/dist/chunks/{GNC6RXLT.js → TDZTC5WR.js} +1 -1
  481. package/build/dist/chunks/TE6D3OIX.js +1 -0
  482. package/build/dist/chunks/TID4C2KC.js +1 -0
  483. package/build/dist/chunks/TK55VASJ.js +2 -0
  484. package/build/dist/chunks/TM7Z5SA4.js +1 -0
  485. package/build/dist/chunks/TNJTET4G.js +1 -0
  486. package/build/dist/chunks/TPEKCXVE.js +1 -0
  487. package/build/dist/chunks/TVIMP5CK.js +1 -0
  488. package/build/dist/chunks/U2YCQWZK.js +1 -0
  489. package/build/dist/chunks/U363GQTF.js +1 -0
  490. package/build/dist/chunks/{U4JGEMKT.js → UEDGYZOC.js} +1 -1
  491. package/build/dist/chunks/UOCRYXAB.js +1 -0
  492. package/build/dist/chunks/UQEEF5W5.js +1 -0
  493. package/build/dist/chunks/{QQECG3WP.js → UUID2E22.js} +1 -1
  494. package/build/dist/chunks/UWBKAWX3.js +7 -0
  495. package/build/dist/chunks/V37L4DU4.js +1 -0
  496. package/build/dist/chunks/VR344DAZ.js +1 -0
  497. package/build/dist/chunks/{TX2EOIRS.js → VST6LFUB.js} +1 -1
  498. package/build/dist/chunks/VTPT5544.js +1 -0
  499. package/build/dist/chunks/VVWFB53Q.js +1 -0
  500. package/build/dist/chunks/WHTRPRRD.js +1 -0
  501. package/build/dist/chunks/WHVZ372B.js +1 -0
  502. package/build/dist/chunks/{AFBEZXNV.js → WNWRF4HE.js} +1 -1
  503. package/build/dist/chunks/{4DP2VPXR.js → WOGWLFAL.js} +1 -1
  504. package/build/dist/chunks/WUT7TZYM.js +1 -0
  505. package/build/dist/chunks/XCKTE4ON.js +1 -0
  506. package/build/dist/chunks/XEPCDGN2.js +1 -0
  507. package/build/dist/chunks/XHYFISVV.js +1 -0
  508. package/build/dist/chunks/XPEDQBLI.js +1 -0
  509. package/build/dist/chunks/{QFNT73OF.js → XQ24RSEI.js} +1 -1
  510. package/build/dist/chunks/XRDXFHIK.js +1 -0
  511. package/build/dist/chunks/XTFRPI4G.js +1 -0
  512. package/build/dist/chunks/XVJ7ILKK.js +1 -0
  513. package/build/dist/chunks/XWKK75TO.js +1 -0
  514. package/build/dist/chunks/{CBLMQ5UU.js → XYPGLG6A.js} +1 -1
  515. package/build/dist/chunks/Y77EVVT4.js +1 -0
  516. package/build/dist/chunks/YEIM6BZQ.js +1 -0
  517. package/build/dist/chunks/{XSKFKBDR.js → YMV5TL5C.js} +1 -1
  518. package/build/dist/chunks/YSMWCKIX.js +1 -0
  519. package/build/dist/chunks/YTLH4M4Y.js +1 -0
  520. package/build/dist/chunks/YUHNPUNK.js +1 -0
  521. package/build/dist/chunks/YWZQJJYY.js +1 -0
  522. package/build/dist/chunks/{EGYVRQUR.js → ZF2VPDRQ.js} +1 -1
  523. package/build/dist/chunks/ZFU65MB4.js +1 -0
  524. package/build/dist/chunks/ZKZUS3QU.js +1 -0
  525. package/build/dist/chunks/ZOMFHTB2.js +1 -0
  526. package/build/dist/chunks/{OLSP46ZD.js → ZP36DSOD.js} +1 -1
  527. package/build/dist/chunks/ZQ6AF3VX.js +1 -0
  528. package/package.json +1 -1
  529. package/build/dist/chunks/2THSW4QN.js +0 -1
  530. package/build/dist/chunks/2TK3ETUO.js +0 -1
  531. package/build/dist/chunks/35KR3VSS.js +0 -1
  532. package/build/dist/chunks/3GQ7A3VB.js +0 -1
  533. package/build/dist/chunks/3XNZUIRU.js +0 -1
  534. package/build/dist/chunks/46547QT3.js +0 -1
  535. package/build/dist/chunks/4EN6MQEI.js +0 -1
  536. package/build/dist/chunks/4I3OU56B.js +0 -1
  537. package/build/dist/chunks/52ELWNXJ.js +0 -2
  538. package/build/dist/chunks/5AXWBSPG.js +0 -1
  539. package/build/dist/chunks/5N3O42X6.js +0 -1
  540. package/build/dist/chunks/5SMVQCAP.js +0 -1
  541. package/build/dist/chunks/5SZPNZG4.js +0 -1
  542. package/build/dist/chunks/64GOINYS.js +0 -1
  543. package/build/dist/chunks/6I4NTKB2.js +0 -1
  544. package/build/dist/chunks/6JAXZNZ3.js +0 -1
  545. package/build/dist/chunks/6O3Q5B6M.js +0 -1
  546. package/build/dist/chunks/6OGDTEGH.js +0 -1
  547. package/build/dist/chunks/6WZX7C4T.js +0 -2
  548. package/build/dist/chunks/6YB3VOUL.js +0 -1
  549. package/build/dist/chunks/7GJ6SLEV.js +0 -1
  550. package/build/dist/chunks/7KWZ5QJU.js +0 -1
  551. package/build/dist/chunks/7QZOTRSA.js +0 -2
  552. package/build/dist/chunks/7WSHW7KW.js +0 -1
  553. package/build/dist/chunks/A7I4IWUB.js +0 -1
  554. package/build/dist/chunks/ABPL3ZZI.js +0 -1
  555. package/build/dist/chunks/ACW63WIL.js +0 -20
  556. package/build/dist/chunks/AEL62KCG.js +0 -1
  557. package/build/dist/chunks/AKYF5264.js +0 -7
  558. package/build/dist/chunks/AW7AXQCZ.js +0 -1
  559. package/build/dist/chunks/AXRL3REN.js +0 -1
  560. package/build/dist/chunks/BBTPRZ6T.js +0 -1
  561. package/build/dist/chunks/BOVMED7R.js +0 -1
  562. package/build/dist/chunks/BTPXJAUX.js +0 -1
  563. package/build/dist/chunks/C7AXJHBT.js +0 -1
  564. package/build/dist/chunks/CBG5HARQ.js +0 -2
  565. package/build/dist/chunks/CDPSMI3Z.js +0 -1
  566. package/build/dist/chunks/CHXBOXOD.js +0 -1
  567. package/build/dist/chunks/CQEJSCFQ.js +0 -1
  568. package/build/dist/chunks/DBNTZEAJ.js +0 -1
  569. package/build/dist/chunks/DHUDSOGR.js +0 -18
  570. package/build/dist/chunks/DJN3JAWB.js +0 -1
  571. package/build/dist/chunks/FEYAY6OZ.js +0 -1
  572. package/build/dist/chunks/GG6Y4OCJ.js +0 -1
  573. package/build/dist/chunks/GGHBFLRC.js +0 -1
  574. package/build/dist/chunks/GGSAKCND.js +0 -1
  575. package/build/dist/chunks/GRQYTVNT.js +0 -1
  576. package/build/dist/chunks/H6T5FXEX.js +0 -1
  577. package/build/dist/chunks/HHXBUYHO.js +0 -1
  578. package/build/dist/chunks/HQUVB7Z5.js +0 -3
  579. package/build/dist/chunks/HU7IMNBI.js +0 -1
  580. package/build/dist/chunks/HWX36XJI.js +0 -1
  581. package/build/dist/chunks/I26DMNJG.js +0 -1
  582. package/build/dist/chunks/I55MURSJ.js +0 -1
  583. package/build/dist/chunks/IMO3GDA5.js +0 -1
  584. package/build/dist/chunks/IPRVIKYC.js +0 -1
  585. package/build/dist/chunks/IVX4R5OL.js +0 -1
  586. package/build/dist/chunks/JQOQMFWD.js +0 -3
  587. package/build/dist/chunks/JUZ5JU6D.js +0 -70
  588. package/build/dist/chunks/JZS3E66E.js +0 -1
  589. package/build/dist/chunks/K3RDPI5J.js +0 -1
  590. package/build/dist/chunks/KBKK7UNY.js +0 -1
  591. package/build/dist/chunks/KVFZKPJT.js +0 -1
  592. package/build/dist/chunks/L5BLHY34.js +0 -1
  593. package/build/dist/chunks/LKXO2BQS.js +0 -1
  594. package/build/dist/chunks/LKZX4CAA.js +0 -1
  595. package/build/dist/chunks/LYMNHO5T.js +0 -1
  596. package/build/dist/chunks/M2UXYCKH.js +0 -1
  597. package/build/dist/chunks/M37654RL.js +0 -1
  598. package/build/dist/chunks/M6LC6DRE.js +0 -1
  599. package/build/dist/chunks/MOE3EVAL.js +0 -1
  600. package/build/dist/chunks/N4Q6GN65.js +0 -1
  601. package/build/dist/chunks/NAZPDRIF.js +0 -1
  602. package/build/dist/chunks/NKX3FE34.js +0 -1
  603. package/build/dist/chunks/NKZKKCK2.js +0 -1
  604. package/build/dist/chunks/NOFUKKP5.js +0 -1
  605. package/build/dist/chunks/O6ROOKY2.js +0 -1
  606. package/build/dist/chunks/OJ4WJUPP.js +0 -1
  607. package/build/dist/chunks/OOZSE2R7.js +0 -1
  608. package/build/dist/chunks/OTXSKFUD.js +0 -1
  609. package/build/dist/chunks/P5AJSLZ7.js +0 -1
  610. package/build/dist/chunks/PACN53TR.js +0 -1
  611. package/build/dist/chunks/PAHXBLCS.js +0 -1
  612. package/build/dist/chunks/PK66GCDT.js +0 -1
  613. package/build/dist/chunks/PSBQWDYI.js +0 -1
  614. package/build/dist/chunks/PXT5YTWU.js +0 -1
  615. package/build/dist/chunks/PZGGE5D3.js +0 -1
  616. package/build/dist/chunks/QA2RRIES.js +0 -1
  617. package/build/dist/chunks/QA3UHEO3.js +0 -1
  618. package/build/dist/chunks/QW2OPEYJ.js +0 -1
  619. package/build/dist/chunks/QYVREJYC.js +0 -1
  620. package/build/dist/chunks/ROFPXEQ5.js +0 -2
  621. package/build/dist/chunks/RTGS7RIO.js +0 -1
  622. package/build/dist/chunks/RUX3RY7Y.js +0 -1
  623. package/build/dist/chunks/RVDUSNWW.js +0 -1
  624. package/build/dist/chunks/S5CBVFHY.js +0 -1
  625. package/build/dist/chunks/SIYUNOLI.js +0 -1
  626. package/build/dist/chunks/TEJ7W534.js +0 -1
  627. package/build/dist/chunks/TPBAFS7K.js +0 -1
  628. package/build/dist/chunks/TVWMTMEF.js +0 -1
  629. package/build/dist/chunks/U2RMUVVY.js +0 -1
  630. package/build/dist/chunks/U5PMVP56.js +0 -1
  631. package/build/dist/chunks/V5JWGWXC.js +0 -1
  632. package/build/dist/chunks/VCOTCVKN.js +0 -1
  633. package/build/dist/chunks/VEQBHI6O.js +0 -1
  634. package/build/dist/chunks/VNV6ZISN.js +0 -1
  635. package/build/dist/chunks/VYAJXLND.js +0 -1
  636. package/build/dist/chunks/WCNHZYQQ.js +0 -1
  637. package/build/dist/chunks/X2P55AC3.js +0 -1
  638. package/build/dist/chunks/XBE3B6Y2.js +0 -1
  639. package/build/dist/chunks/XKSVTN5X.js +0 -1
  640. package/build/dist/chunks/XSRIJUFU.js +0 -1
  641. package/build/dist/chunks/YCZPSMZ5.js +0 -1
  642. package/build/dist/chunks/YN56C7PN.js +0 -1
  643. package/build/dist/chunks/YRNXGQJC.js +0 -1
  644. package/build/dist/chunks/YWRLY5EA.js +0 -1
  645. package/build/dist/chunks/YWSX6IE6.js +0 -1
  646. package/build/dist/chunks/YXTSWRV5.js +0 -1
  647. package/build/dist/chunks/Z6LZGCVW.js +0 -1
  648. package/build/dist/chunks/ZQWZGH7V.js +0 -1
  649. package/build/dist/chunks/ZSN4IRI5.js +0 -1
  650. package/build/dist/chunks/ZV5HIQXC.js +0 -1
  651. package/build/dist/chunks/ZXJ24B4L.js +0 -1
@@ -1 +1 @@
1
- import{a}from"./PK66GCDT.js";import{e as d}from"./NWNYJ26T.js";import{isAddress as p}from"viem";var u={version:"oak-wormhole-check/v1",oakRoute:"/v1/wormhole/check",upstreamPaths:{check:"/api/v1/check"}},h=5e3,m=5e3,i=(e="unavailable")=>({verdict:"unknown",reason:e}),l=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0;function k(e){return d(e)?e.kind==="text"?Object.keys(e).length===2&&typeof e.text=="string"&&!!e.text.trim()&&e.text.length<=a&&Buffer.byteLength(e.text,"utf8")<=a&&!/(?:\b(?:private[ _-]?key|secret[ _-]?key|mnemonic|seed[ _-]?phrase|recovery[ _-]?phrase)\s*[:=]|\b0x[0-9a-f]{64}\b)/i.test(e.text):e.kind==="token"&&Object.keys(e).length===3&&e.chainId===4663&&typeof e.token=="string"&&p(e.token,{strict:!0})&&e.token.toLowerCase()!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee":!1}function y(e){try{let r=new URL(e??"");return r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"?void 0:r.origin}catch{return}}function g(e,r){return d(e)&&e.ok===!0&&(e=e.data),!d(e)||!["clear","flagged","unknown"].includes(String(e.verdict))?i():e.verdict==="unknown"?i(["off","unconfigured","invalid_request","unavailable","rate_limited","price_cap"].includes(String(e.reason))?e.reason:"unavailable"):typeof e.chargedMicrousd!="number"||!Number.isSafeInteger(e.chargedMicrousd)||e.chargedMicrousd<0||e.chargedMicrousd>r||typeof e.evidenceBlockId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(e.evidenceBlockId)?i():{verdict:e.verdict,chargedMicrousd:e.chargedMicrousd,evidenceBlockId:e.evidenceBlockId}}async function b(e){let r=new AbortController,t,n=new Promise((c,o)=>{t=setTimeout(()=>{r.abort(),o(new Error("timeout"))},h)});try{return await Promise.race([n,e(r.signal)])}finally{clearTimeout(t),r.abort()}}async function w(e,r){let t=e.body?.getReader();if(!t)throw new Error("empty_response");let n=()=>{t.cancel().catch(()=>{})};r.addEventListener("abort",n,{once:!0});let c=0,o=[];try{for(;;){if(r.aborted)throw new Error("timeout");let{value:s,done:f}=await t.read();if(f)break;if(c+=s.byteLength,c>65536)throw new Error("response_limit");o.push(s)}if(r.aborted)throw new Error("timeout");return JSON.parse(Buffer.concat(o).toString("utf8"))}finally{r.removeEventListener("abort",n),n(),t.releaseLock()}}async function M(e,r={},t=fetch){if(r.payerMode===void 0||r.payerMode==="off")return i("off");let n=y(r.endpointBaseUrl),c=r.priceCapMicrousd??m;if(r.payerMode!=="server-key"||!n||!l(c))return i("unconfigured");if(!k(e))return i("invalid_request");try{return await b(async o=>{let s=await t(`${n}${u.oakRoute}`,{method:"POST",redirect:"error",credentials:"omit",signal:o,headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({request:e,priceCapMicrousd:c})});return o.aborted||s.redirected||!s.ok?(s.body?.cancel().catch(()=>{}),i()):g(await w(s,o),c)})}catch{return i()}}export{u as a,h as b,m as c,i as d,l as e,k as f,y as g,g as h,b as i,w as j,M as k};
1
+ import{a}from"./XTFRPI4G.js";import{e as d}from"./NWNYJ26T.js";import{isAddress as p}from"viem";var u={version:"oak-wormhole-check/v1",oakRoute:"/v1/wormhole/check",upstreamPaths:{check:"/api/v1/check"}},h=5e3,m=5e3,i=(e="unavailable")=>({verdict:"unknown",reason:e}),l=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>0;function k(e){return d(e)?e.kind==="text"?Object.keys(e).length===2&&typeof e.text=="string"&&!!e.text.trim()&&e.text.length<=a&&Buffer.byteLength(e.text,"utf8")<=a&&!/(?:\b(?:private[ _-]?key|secret[ _-]?key|mnemonic|seed[ _-]?phrase|recovery[ _-]?phrase)\s*[:=]|\b0x[0-9a-f]{64}\b)/i.test(e.text):e.kind==="token"&&Object.keys(e).length===3&&e.chainId===4663&&typeof e.token=="string"&&p(e.token,{strict:!0})&&e.token.toLowerCase()!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee":!1}function y(e){try{let r=new URL(e??"");return r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"?void 0:r.origin}catch{return}}function g(e,r){return d(e)&&e.ok===!0&&(e=e.data),!d(e)||!["clear","flagged","unknown"].includes(String(e.verdict))?i():e.verdict==="unknown"?i(["off","unconfigured","invalid_request","unavailable","rate_limited","price_cap"].includes(String(e.reason))?e.reason:"unavailable"):typeof e.chargedMicrousd!="number"||!Number.isSafeInteger(e.chargedMicrousd)||e.chargedMicrousd<0||e.chargedMicrousd>r||typeof e.evidenceBlockId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(e.evidenceBlockId)?i():{verdict:e.verdict,chargedMicrousd:e.chargedMicrousd,evidenceBlockId:e.evidenceBlockId}}async function b(e){let r=new AbortController,t,n=new Promise((c,o)=>{t=setTimeout(()=>{r.abort(),o(new Error("timeout"))},h)});try{return await Promise.race([n,e(r.signal)])}finally{clearTimeout(t),r.abort()}}async function w(e,r){let t=e.body?.getReader();if(!t)throw new Error("empty_response");let n=()=>{t.cancel().catch(()=>{})};r.addEventListener("abort",n,{once:!0});let c=0,o=[];try{for(;;){if(r.aborted)throw new Error("timeout");let{value:s,done:f}=await t.read();if(f)break;if(c+=s.byteLength,c>65536)throw new Error("response_limit");o.push(s)}if(r.aborted)throw new Error("timeout");return JSON.parse(Buffer.concat(o).toString("utf8"))}finally{r.removeEventListener("abort",n),n(),t.releaseLock()}}async function M(e,r={},t=fetch){if(r.payerMode===void 0||r.payerMode==="off")return i("off");let n=y(r.endpointBaseUrl),c=r.priceCapMicrousd??m;if(r.payerMode!=="server-key"||!n||!l(c))return i("unconfigured");if(!k(e))return i("invalid_request");try{return await b(async o=>{let s=await t(`${n}${u.oakRoute}`,{method:"POST",redirect:"error",credentials:"omit",signal:o,headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({request:e,priceCapMicrousd:c})});return o.aborted||s.redirected||!s.ok?(s.body?.cancel().catch(()=>{}),i()):g(await w(s,o),c)})}catch{return i()}}export{u as a,h as b,m as c,i as d,l as e,k as f,y as g,g as h,b as i,w as j,M as k};
@@ -1 +1 @@
1
- import{b as le,o as K}from"./BOVMED7R.js";import{b as x}from"./66F5ZH34.js";import{c as W,f as de,h as y,i as ce,l as ue}from"./NWNYJ26T.js";import{a as k,i as oe,j as G}from"./FWD4L3CJ.js";import{a as N}from"./XSD5NL7J.js";import{a as O}from"./JXOEJPJ4.js";import{randomBytes as ge,randomUUID as he}from"node:crypto";import{isDeepStrictEqual as pe}from"node:util";import{decodeFunctionData as me,encodeAbiParameters as ne,erc20Abi as J,keccak256 as ie,parseAbi as re,parseAbiParameters as ae,toEventSelector as be,zeroAddress as L}from"viem";var se=oe[k].meridian,Q=se.PredictionMarketEscrow.address,V=se.SecondaryMarketEscrow.address,$={address:se.CollateralToken_USDe.address,chainId:k,symbol:"USDe",decimals:18},we="wss://relayer.predict.meridian.xyz/auction",ke=ae("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),Ie=ae("bytes32,uint256,uint256,address,address,address,bytes"),Se=ae("address,address,address,address,uint256,uint256"),X=re(["function isNonceUsed(address,uint256) view returns (bool)"]),Be=re(["function mint(((address conditionResolver,bytes conditionId,uint8 predictedOutcome)[] picks,uint256 predictorCollateral,uint256 counterpartyCollateral,address predictor,address counterparty,uint256 predictorNonce,uint256 counterpartyNonce,uint256 predictorDeadline,uint256 counterpartyDeadline,bytes predictorSignature,bytes counterpartySignature,bytes32 refCode,bytes predictorSessionKeyData,bytes counterpartySessionKeyData,address predictorSponsor,bytes predictorSponsorData) request)"]),Me=re(["function executeTrade((address token,address collateral,address seller,address buyer,uint256 tokenAmount,uint256 price,uint256 sellerNonce,uint256 buyerNonce,uint256 sellerDeadline,uint256 buyerDeadline,bytes sellerSignature,bytes buyerSignature,bytes32 refCode,bytes sellerSessionKeyData,bytes buyerSessionKeyData) request)"]),$e=be("Transfer(address,address,uint256)"),Ae=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],Ce=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function i(n){throw new N(n)}function _(n){return de(n,"Meridian returned an invalid exchange object.")}function M(n,t,d=!1){return d&&typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&(n=String(n)),(typeof n!="string"||!/^\d+$/.test(n)||BigInt(n)>=1n<<256n)&&i(`Provide ${t} as a decimal base-unit integer string.`),n}function F(n){let t=Number(n);return(!Number.isSafeInteger(t)||t<0||BigInt(t)!==BigInt(n))&&i("Meridian signing terms cannot be represented exactly as JSON numbers."),t}function R(n){let t="Provide a nonzero token, resolver or wallet address.";return ue(ce(n,t),t)}function Z(n,t){return(typeof n!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(n)||t!==void 0&&n.length!==2+t*2)&&i("Meridian returned invalid hexadecimal data."),n}function v(n){return(typeof n!="string"||n.length===0||n.length>256)&&i("Meridian returned an invalid exchange identifier."),n}function j(){return BigInt(Math.floor(Date.now()/1e3))}function ve(n,t){let d=n==="buy"?["picks","stake","minCounterpartyCollateral","usdgAmountIn","slippageBps","continuation","signature"]:["token","amount","minPrice","slippageBps","continuation","signature"];Object.keys(t).some(S=>!d.includes(S))&&i("Unsupported Meridian arguments; use the tool input schema."),t.slippageBps!==void 0&&(typeof t.slippageBps!="number"||!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>=1e4)&&i("Slippage must be an integer from 0 to 9999 basis points.");let c=t.slippageBps;if(n==="sell"){let S=M(t.amount,"the position amount");BigInt(S)===0n&&i("The position amount must be positive.");let B=R(t.token);(y(B,$.address)||y(B,G))&&i("Choose a Meridian position token to sell.");let A;if(t.minPrice!==void 0){let e=M(t.minPrice,"the minimum sale price");BigInt(e)<=1n&&i("The minimum sale price must be greater than 1 base unit."),A=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;A=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:A,priceFloorSource:t.minPrice===void 0?"default":"explicit",...c===void 0?{}:{slippageBps:c}}}(!Array.isArray(t.picks)||t.picks.length<1||t.picks.length>10)&&i("Provide between one and ten Meridian picks.");let m=t.picks.map(S=>{let B=_(S);return(Object.keys(B).some(A=>!["conditionResolver","conditionId","predictedOutcome"].includes(A))||B.predictedOutcome!==0&&B.predictedOutcome!==1)&&i("Each pick needs a resolver, condition ID and outcome 0 or 1."),{conditionResolver:R(B.conditionResolver),conditionId:Z(B.conditionId),predictedOutcome:B.predictedOutcome}}).sort((S,B)=>{let A=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return A<e?-1:A>e?1:0}),g=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(g).size!==m.length&&i("Do not repeat a condition in the same prediction.");let l=M(t.stake,"the USDe stake");BigInt(l)<10n**18n&&i("Meridian requires a stake of at least 1 USDe.");let I=t.usdgAmountIn===void 0?void 0:M(t.usdgAmountIn,"the USDG swap amount");I!==void 0&&BigInt(I)===0n&&i("The USDG swap amount must be positive.");let D=t.minCounterpartyCollateral!==void 0?M(t.minCounterpartyCollateral,"the minimum counterparty collateral"):K(l,c??le);return BigInt(D)<=1n&&i("The minimum counterparty collateral must be greater than 1 base unit."),{side:n,picks:m,stake:l,minCounterpartyCollateral:D,...I===void 0?{}:{usdgAmountIn:I},...c===void 0?{}:{slippageBps:c}}}var ee=class{constructor(t,d){this.id=t;this.prefix=d;this.socket=new globalThis.WebSocket(we),this.socket.addEventListener("open",()=>{this.opened=!0,this.notify?.()}),this.socket.addEventListener("close",()=>this.stop("Meridian exchange socket was lost. Start a fresh auction.")),this.socket.addEventListener("error",()=>this.stop("Meridian exchange socket failed. Start a fresh auction.")),this.socket.addEventListener("message",c=>{try{(typeof c.data!="string"||c.data.length>65536)&&i("Meridian returned a malformed exchange message.");let m=_(JSON.parse(c.data));if(m.type==="pong")return;let g=v(m.type),l=_(m.payload);if(g==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),g===`${d}.ack`){this.auctionId===void 0?((l.id!==t||this.accepting||l.accepted!==void 0)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected the exchange: ${O(v(l.error))}.`),this.auctionId=v(l.auctionId)):((!this.accepting||l.auctionId!==this.auctionId||l.id!==void 0&&l.id!==t)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected acceptance: ${O(v(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!g.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>g===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${O(v(l[D]))}`]);i(`Meridian exchange ${g.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((g===`${d}.pending`||g===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),g===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:g,payload:l}),this.notify?.()}catch(m){this.stop(m instanceof N?m.message:"Meridian rejected or returned an invalid exchange message. Start a fresh auction.")}})}id;prefix;socket;queue=[];notify;error;auctionId;accepting=!1;opened=!1;check(){if(this.error)throw this.error;this.socket.readyState>1&&i("Meridian exchange socket was lost. Start a fresh auction.")}stop(t){this.error??=new N(t),this.notify?.(),this.socket.readyState<2&&this.socket.close()}async wait(t,d=3e4){return new Promise((c,m)=>{let g=setTimeout(()=>this.stop("Meridian exchange timed out. Start a fresh auction."),d),l=()=>{try{if(this.check(),t===void 0?!this.opened:!this.queue.length)return;let I=t===void 0?void 0:this.queue.shift();I&&I.type!==`${this.prefix}.${t}`&&i("Meridian returned an unexpected exchange stage."),clearTimeout(g),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(g),this.notify=void 0,m(I)}};this.notify=l,l()})}send(t,d){this.check(),this.socket.readyState!==1&&i("Meridian exchange socket is not open."),t==="accept"&&(this.accepting=!0),this.socket.send(JSON.stringify({...t==="start"?{id:this.id}:{},type:`${this.prefix}.${t}`,payload:d}))}};function te(n){return ie(ne(ke,[n]))}function De(n,t,d){return ie(ne(Ie,[te(n.picks),BigInt(n.stake),BigInt(d.counterpartyCollateral),t,d.counterparty,L,"0x"]))}function qe(n,t,d,c){return ie(ne(Se,[n.token,$.address,t,d,BigInt(n.amount),BigInt(c)]))}function Y(n,t){let{input:d,wallet:c,nonce:m,deadline:g}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!g)&&i("Meridian exchange is missing its signing terms."),d.side==="buy"?(t||i("Meridian has not returned a winning bid."),{domain:l,primaryType:"MintApproval",types:{MintApproval:Ae},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:g}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:Ce},message:{tradeHash:qe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:g}}}function fe(n){let t=[BigInt(n.deadline)],d=n.continuation;if(d.stage==="primary_accept"||d.stage==="secondary_accept"){t.push(BigInt(d.acceptDeadline));let c=d.winningBid;d.stage==="primary_accept"&&t.push(BigInt(c.counterpartyDeadline)),c.buyerDeadline!==void 0&&t.push(BigInt(M(c.buyerDeadline,"the buyer deadline",!0)))}return t.reduce((c,m)=>c<m?c:m)}function H(n){n.channel?.check(),n.deadline&&j()>=fe(n)&&i("Meridian exchange expired. Start a fresh auction.")}var Oe=n=>{let t=new Map;function d(e){clearTimeout(e.timer),t.delete(e.continuation.requestId),e.channel?.stop("Meridian exchange is closed or expired. Start a fresh auction.")}function c(e,a){clearTimeout(e.timer),e.timer=setTimeout(()=>d(e),a),e.timer.unref?.()}function m(e){let{wallet:a,chainId:s,escrowContract:f,requestId:u}=e.continuation;return{wallet:a,chainId:s,escrowContract:f,requestId:u}}function g(e){return e.side!=="sell"?"":` Effective minimum sale proceeds: ${e.minPrice} USDe base units (${$.address}, 18 decimals). ${e.priceFloorSource==="explicit"?"Caller minPrice is unchanged; slippageBps does not reduce this floor.":`Default floor with ${e.slippageBps??0} bps slippage applied.`}`}async function l(e){let{input:a,wallet:s}=e,f=n.clientFor(k),u=a.side==="buy"?$.address:a.token,r=a.side==="buy"?a.stake:a.amount,[h,w]=await Promise.all([f.readContract({address:u,abi:J,functionName:"balanceOf",args:[s]}),f.readContract({address:u,abi:J,functionName:"allowance",args:[s,e.continuation.escrowContract]})]);if(a.side==="sell"&&await f.readContract({address:u,abi:J,functionName:"decimals"})!==18&&i("Meridian position tokens must have 18 decimals."),h>=BigInt(r)&&w>=BigInt(r))return;(e.continuation.stage==="primary_accept"||e.continuation.stage==="secondary_accept")&&i("Meridian prerequisites changed during the auction. Start a fresh auction after funding and approval.");let p,C;if(h<BigInt(r)){a.side==="sell"&&i("The wallet does not have enough position tokens to sell."),a.usdgAmountIn||i("Not enough USDe. Provide usdgAmountIn in USDG base units to quote a swap before the auction.");let b=await n.quoteSwap({from:G,to:$.address,amountIn:a.usdgAmountIn,...a.slippageBps===void 0?{}:{slippageBps:a.slippageBps}},s);(j()>=BigInt(M(b.expiresAt,"the swap expiry"))||BigInt(M(b.minAmountOut,"the swap minimum"))+h<BigInt(r))&&i("The USDG swap minimum does not cover the USDe stake, or the quote expired. Request a fresh quote with sufficient input.");let o=await n.buildSwap(b.quoteId,s);(!("txs"in o)||!o.txs.length)&&i("The swap coordinator did not return prerequisite transactions."),p=o.txs,C=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],C=`Approve exactly ${r} base units (18 decimals) of ${u} for ${e.continuation.escrowContract} on chain ${k}.`;p.some(b=>b.chainId!==k)&&i("Meridian prerequisite transactions must use chain 4663.");let q=await n.preview(p,s),T=q.changes.map(b=>{let o=b.amount.startsWith("-");return`${o?"-":"+"}${n.formatAmount(o?b.amount.slice(1):b.amount,b.token.decimals)} ${b.token.symbol} (${b.token.address}, chain ${b.token.chainId}, ${b.token.decimals} decimals)`}).join("; ");return e.channel?.stop("Meridian prerequisites must be mined before the auction."),e.channel=void 0,e.deadline=void 0,e.nonce=void 0,e.continuation={...m(e),stage:"prerequisites"},{steps:p.map(b=>({kind:"tx",tx:b})),continuation:structuredClone(e.continuation),summary:`${C}${g(a)} ${q.summary} ${T}. Mine these prerequisites before continuing; no RFQ has started.`}}function I(e){let a=e.continuation;a.stage==="prerequisites"&&i("Meridian prerequisites need to finish before signing."),H(e),c(e,Number(fe(e)-j())*1e3);let s=e.input,f=s.side==="buy"?`Stake ${s.stake} base units of USDe (${$.address}, 18 decimals)`:`Sell ${s.amount} base units of position ${s.token} (18 decimals)`,u=a.stage==="secondary_start"?"Initial buyer-zero, price-zero intent only.":a.stage==="primary_accept"?`Counterparty ${a.winningBid.counterparty}; counterparty collateral ${a.winningBid.counterpartyCollateral} USDe base units; counterparty deadline ${a.winningBid.counterpartyDeadline}.`:`Buyer ${a.winningBid.buyer}; receive ${a.winningBid.price} USDe base units (${$.address}, 18 decimals).`;return{steps:[{kind:"typedData",request:structuredClone(a.request)}],continuation:structuredClone(a),summary:`${f} on chain ${k}.${g(s)} Approval was checked on chain. ${u} Sign locally for domain ${a.request.domain.name}, version 1, escrow ${a.escrowContract}, signature deadline ${e.deadline}${"acceptDeadline"in a?`, acceptance deadline ${a.acceptDeadline}`:""}. External relayer settlement is pending; a signature is not a fill.`}}async function D(e){let a=await e.channel.wait("result"),s=_(a.winningBid),f=v(a.auctionId);s.auctionId!==f&&i("Meridian winning bid belongs to another auction.");let u=M(a.acceptDeadline,"the acceptance deadline",!0);if(e.input.side==="buy"){let r={auctionId:f,counterparty:v(s.counterparty),counterpartyCollateral:M(s.counterpartyCollateral,"the counterparty collateral"),counterpartyNonce:M(s.counterpartyNonce,"the counterparty nonce",!0),counterpartyDeadline:M(s.counterpartyDeadline,"the counterparty deadline",!0),receivedAt:v(s.receivedAt)};R(r.counterparty),(!Number.isFinite(Date.parse(r.receivedAt))||BigInt(r.counterpartyCollateral)<=1n||BigInt(r.counterpartyCollateral)<BigInt(e.input.minCounterpartyCollateral))&&i("Meridian winning bid counterparty collateral is below the caller minimum."),e.continuation={...m(e),stage:"primary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}else{let r={auctionId:f,buyer:v(s.buyer),price:M(s.price,"the sale price"),...s.buyerDeadline!==void 0?{buyerDeadline:M(s.buyerDeadline,"the buyer deadline",!0)}:{},...s.buyerNonce!==void 0?{buyerNonce:M(s.buyerNonce,"the buyer nonce",!0)}:{},...s.receivedAt!==void 0?{receivedAt:v(s.receivedAt)}:{}};R(r.buyer),(BigInt(r.price)<=1n||BigInt(r.price)<BigInt(e.input.minPrice))&&i("Meridian winning bid sale price is below the caller minimum."),e.continuation={...m(e),stage:"secondary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}return I(e)}async function S(e,a){let s=e.continuation;s.stage!=="primary_accept"&&s.stage!=="secondary_accept"&&i("Meridian exchange is not ready for acceptance."),H(e),e.channel.send("accept",{auctionId:s.auctionId,[e.input.side==="buy"?"predictorSignature":"sellerSignature"]:a}),c(e,15e4);let f=await e.channel.wait("filled",12e4),u=Z(f.transactionHash,32),r=n.clientFor(k),[h,w]=await Promise.all([r.waitForTransactionReceipt({hash:u,timeout:12e4}),r.getTransaction({hash:u})]);(h.status!=="success"||!y(h.transactionHash,u)||!y(w.hash,u)||!y(h.to,s.escrowContract)||!y(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:C}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!y(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!y(o.predictor,C)||!y(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!y(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!y(o.predictorSignature,a))&&i("Meridian mint receipt does not match the accepted prediction.")}else if(p.side==="sell"&&s.stage==="secondary_accept"){let o=me({abi:Me,data:w.input}).args[0];(!y(o.token,p.token)||!y(o.collateral,$.address)||!y(o.seller,C)||!y(o.buyer,s.winningBid.buyer)||o.tokenAmount!==BigInt(p.amount)||o.price!==BigInt(s.winningBid.price)||o.sellerNonce!==BigInt(e.nonce)||o.sellerDeadline!==BigInt(e.deadline)||!y(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let q=new Map,T=new Map;for(let o of h.logs){if(o.topics[0]!==$e||o.topics.length!==3)continue;(!/^0x[0-9a-fA-F]{64}$/.test(o.data)||!o.topics.slice(1).every(ye=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ye)))&&i("Meridian receipt has malformed transfer logs.");let E=`0x${o.topics[1].slice(-40)}`,U=`0x${o.topics[2].slice(-40)}`,P=o.address.toLowerCase(),z=BigInt(o.data);q.set(P,(q.get(P)??0n)+(y(U,C)?z:0n)-(y(E,C)?z:0n)),y(E,L)&&y(U,C)&&T.set(P,(T.get(P)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),E=[...T].filter(([U,P])=>!y(U,$.address)&&P===o&&q.get(U)===o);(E.length!==1||q.get($.address.toLowerCase())!==-BigInt(p.stake))&&i("Meridian mint receipt does not prove the expected collateral and position delta."),b=`${o} base units received in position ${E[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((q.get(p.token.toLowerCase())!==-BigInt(p.amount)||q.get($.address.toLowerCase())!==BigInt(s.winningBid.price))&&i("Meridian sale receipt does not prove the expected collateral and position delta."),b=`${p.amount} base units sold from position ${p.token}; ${s.winningBid.price} USDe base units received`):i("Meridian fill has a different exchange stage.");return{txs:[],hashes:[u],status:"mined",summary:`Mined: ${u}. Status: mined. Meridian ${p.side} filled by the external relayer. Successful receipt and transfer deltas verified on chain ${k}: ${b} (18 decimals); collateral USDe ${$.address} (18 decimals).`}}async function B(e,a,s){let f=R(s),u=ve(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(v(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!y(w.wallet,f)||!pe(w.input,u)||!pe(w.continuation,h))&&i("Meridian continuation or arguments do not match the active wallet exchange."),w.busy&&i("Meridian exchange is already processing this continuation."),r=w}else{a.signature!==void 0&&i("A signature requires an active Meridian continuation."),t.size>=1e3&&i("Too many active Meridian exchanges. Please try again later.");let h=he(),w=setTimeout(()=>{let p=t.get(h);p&&d(p)},9e5);w.unref?.(),r={input:u,wallet:f,continuation:{stage:"prerequisites",wallet:f,chainId:k,escrowContract:e==="buy"?Q:V,requestId:h},busy:!1,timer:w},t.set(h,r)}r.busy=!0;try{H(r),await n.clientFor(k).getChainId()!==k&&i("Meridian requires an RPC on chain 4663.");let h=r.continuation.stage;h==="prerequisites"&&a.signature!==void 0&&i("Do not sign before Meridian prerequisites have mined.");let w=await l(r);if(w)return w;if(h==="prerequisites")return r.nonce=(ge(4).readUInt32BE()+1).toString(),r.deadline=(j()+300n).toString(),await n.clientFor(k).readContract({address:r.continuation.escrowContract,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i(`Meridian ${e==="buy"?"predictor":"seller"} nonce is already used. Start a fresh auction.`),r.channel=new ee(r.continuation.requestId,e==="buy"?"auction":"secondary.auction"),await r.channel.wait(),u.side==="buy"?(r.channel.send("start",{id:r.continuation.requestId,picks:u.picks,predictorCollateral:u.stake,predictor:f,predictorNonce:F(r.nonce),predictorDeadline:F(r.deadline),chainId:k,escrowContract:Q,mode:"blind"}),await D(r)):(r.continuation={...m(r),stage:"secondary_start",request:Y(r)},I(r));let p=Z(a.signature);if(e==="sell"&&await n.clientFor(k).readContract({address:V,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),e==="buy"&&await n.clientFor(k).readContract({address:Q,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian predictor nonce is already used. Start a fresh auction."),H(r),h==="secondary_start"&&u.side==="sell")return r.channel.send("start",{id:r.continuation.requestId,token:u.token,collateral:$.address,tokenAmount:u.amount,seller:f,sellerNonce:F(r.nonce),sellerDeadline:F(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let C=await S(r,p);return d(r),C}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let A={continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...A,stake:x("USDe stake in base units, 18 decimals, chain 4663."),minCounterpartyCollateral:x("Optional caller minimum counterparty collateral in USDe base units, 18 decimals."),usdgAmountIn:x("Optional exact USDG swap input in base units, 6 decimals, if USDe balance is insufficient."),slippageBps:{type:"integer",minimum:0,maximum:9999},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:W,conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"},predictedOutcome:{type:"integer",enum:[0,1]}}}}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...A,token:{...W,description:"Position token address on chain 4663."},amount:x("Position amount in base units, 18 decimals."),minPrice:x("Optional minimum total sale proceeds in USDe base units, 18 decimals. Explicit minPrice is never reduced by slippageBps."),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Applied only to the default sale floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ae as a,Ce as b,Oe as c};
1
+ import{b as le,o as K}from"./CAWTAR5V.js";import{b as x}from"./66F5ZH34.js";import{c as W,f as de,h as g,i as ce,l as ue}from"./NWNYJ26T.js";import{a as k,i as oe,j as G}from"./FWD4L3CJ.js";import{a as N}from"./XSD5NL7J.js";import{a as F}from"./JXOEJPJ4.js";import{randomBytes as ye,randomUUID as he}from"node:crypto";import{isDeepStrictEqual as pe}from"node:util";import{decodeFunctionData as me,encodeAbiParameters as ne,erc20Abi as J,keccak256 as ie,parseAbi as re,parseAbiParameters as ae,toEventSelector as be,zeroAddress as L}from"viem";var se=oe[k].meridian,Q=se.PredictionMarketEscrow.address,V=se.SecondaryMarketEscrow.address,$={address:se.CollateralToken_USDe.address,chainId:k,symbol:"USDe",decimals:18},we="wss://relayer.predict.meridian.xyz/auction",ke=ae("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),Ie=ae("bytes32,uint256,uint256,address,address,address,bytes"),Se=ae("address,address,address,address,uint256,uint256"),X=re(["function isNonceUsed(address,uint256) view returns (bool)"]),Be=re(["function mint(((address conditionResolver,bytes conditionId,uint8 predictedOutcome)[] picks,uint256 predictorCollateral,uint256 counterpartyCollateral,address predictor,address counterparty,uint256 predictorNonce,uint256 counterpartyNonce,uint256 predictorDeadline,uint256 counterpartyDeadline,bytes predictorSignature,bytes counterpartySignature,bytes32 refCode,bytes predictorSessionKeyData,bytes counterpartySessionKeyData,address predictorSponsor,bytes predictorSponsorData) request)"]),Me=re(["function executeTrade((address token,address collateral,address seller,address buyer,uint256 tokenAmount,uint256 price,uint256 sellerNonce,uint256 buyerNonce,uint256 sellerDeadline,uint256 buyerDeadline,bytes sellerSignature,bytes buyerSignature,bytes32 refCode,bytes sellerSessionKeyData,bytes buyerSessionKeyData) request)"]),$e=be("Transfer(address,address,uint256)"),Ce=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],ve=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function i(n){throw new N(n)}function _(n){return de(n,"Meridian returned an invalid exchange object.")}function M(n,t,d=!1){return d&&typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&(n=String(n)),(typeof n!="string"||!/^\d+$/.test(n)||BigInt(n)>=1n<<256n)&&i(`Provide ${t} as a decimal base-unit integer string.`),n}function O(n){let t=Number(n);return(!Number.isSafeInteger(t)||t<0||BigInt(t)!==BigInt(n))&&i("Meridian signing terms cannot be represented exactly as JSON numbers."),t}function R(n){let t="Provide a nonzero token, resolver or wallet address.";return ue(ce(n,t),t)}function Z(n,t){return(typeof n!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(n)||t!==void 0&&n.length!==2+t*2)&&i("Meridian returned invalid hexadecimal data."),n}function A(n){return(typeof n!="string"||n.length===0||n.length>256)&&i("Meridian returned an invalid exchange identifier."),n}function j(){return BigInt(Math.floor(Date.now()/1e3))}function Ae(n,t){let d=n==="buy"?["picks","stake","minCounterpartyCollateral","usdgAmountIn","slippageBps","continuation","signature"]:["token","amount","minPrice","slippageBps","continuation","signature"];Object.keys(t).some(S=>!d.includes(S))&&i("Unsupported Meridian arguments; use the tool input schema."),t.slippageBps!==void 0&&(typeof t.slippageBps!="number"||!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>=1e4)&&i("Slippage must be an integer from 0 to 9999 basis points.");let c=t.slippageBps;if(n==="sell"){let S=M(t.amount,"the position amount");BigInt(S)===0n&&i("The position amount must be positive.");let B=R(t.token);(g(B,$.address)||g(B,G))&&i("Choose a Meridian position token to sell.");let C;if(t.minPrice!==void 0){let e=M(t.minPrice,"the minimum sale price");BigInt(e)<=1n&&i("The minimum sale price must be greater than 1 base unit."),C=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;C=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:C,priceFloorSource:t.minPrice===void 0?"default":"explicit",...c===void 0?{}:{slippageBps:c}}}(!Array.isArray(t.picks)||t.picks.length<1||t.picks.length>10)&&i("Provide between one and ten Meridian picks.");let m=t.picks.map(S=>{let B=_(S);return(Object.keys(B).some(C=>!["conditionResolver","conditionId","predictedOutcome"].includes(C))||B.predictedOutcome!==0&&B.predictedOutcome!==1)&&i("Each pick needs a resolver, condition ID and outcome 0 or 1."),{conditionResolver:R(B.conditionResolver),conditionId:Z(B.conditionId),predictedOutcome:B.predictedOutcome}}).sort((S,B)=>{let C=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return C<e?-1:C>e?1:0}),y=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(y).size!==m.length&&i("Do not repeat a condition in the same prediction.");let l=M(t.stake,"the USDe stake");BigInt(l)<10n**18n&&i("Meridian requires a stake of at least 1 USDe.");let I=t.usdgAmountIn===void 0?void 0:M(t.usdgAmountIn,"the USDG swap amount");I!==void 0&&BigInt(I)===0n&&i("The USDG swap amount must be positive.");let D=t.minCounterpartyCollateral!==void 0?M(t.minCounterpartyCollateral,"the minimum counterparty collateral"):K(l,c??le);return BigInt(D)<=1n&&i("The minimum counterparty collateral must be greater than 1 base unit."),{side:n,picks:m,stake:l,minCounterpartyCollateral:D,...I===void 0?{}:{usdgAmountIn:I},...c===void 0?{}:{slippageBps:c}}}var ee=class{constructor(t,d){this.id=t;this.prefix=d;this.socket=new globalThis.WebSocket(we),this.socket.addEventListener("open",()=>{this.opened=!0,this.notify?.()}),this.socket.addEventListener("close",()=>this.stop("Meridian exchange socket was lost. Start a fresh auction.")),this.socket.addEventListener("error",()=>this.stop("Meridian exchange socket failed. Start a fresh auction.")),this.socket.addEventListener("message",c=>{try{(typeof c.data!="string"||c.data.length>65536)&&i("Meridian returned a malformed exchange message.");let m=_(JSON.parse(c.data));if(m.type==="pong")return;let y=A(m.type),l=_(m.payload);if(y==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),y===`${d}.ack`){this.auctionId===void 0?((l.id!==t||this.accepting||l.accepted!==void 0)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected the exchange: ${F(A(l.error))}.`),this.auctionId=A(l.auctionId)):((!this.accepting||l.auctionId!==this.auctionId||l.id!==void 0&&l.id!==t)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected acceptance: ${F(A(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!y.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>y===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${F(A(l[D]))}`]);i(`Meridian exchange ${y.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((y===`${d}.pending`||y===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),y===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:y,payload:l}),this.notify?.()}catch(m){this.stop(m instanceof N?m.message:"Meridian rejected or returned an invalid exchange message. Start a fresh auction.")}})}id;prefix;socket;queue=[];notify;error;auctionId;accepting=!1;opened=!1;check(){if(this.error)throw this.error;this.socket.readyState>1&&i("Meridian exchange socket was lost. Start a fresh auction.")}stop(t){this.error??=new N(t),this.notify?.(),this.socket.readyState<2&&this.socket.close()}async wait(t,d=3e4){return new Promise((c,m)=>{let y=setTimeout(()=>this.stop("Meridian exchange timed out. Start a fresh auction."),d),l=()=>{try{if(this.check(),t===void 0?!this.opened:!this.queue.length)return;let I=t===void 0?void 0:this.queue.shift();I&&I.type!==`${this.prefix}.${t}`&&i("Meridian returned an unexpected exchange stage."),clearTimeout(y),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(y),this.notify=void 0,m(I)}};this.notify=l,l()})}send(t,d){this.check(),this.socket.readyState!==1&&i("Meridian exchange socket is not open."),t==="accept"&&(this.accepting=!0),this.socket.send(JSON.stringify({...t==="start"?{id:this.id}:{},type:`${this.prefix}.${t}`,payload:d}))}};function te(n){return ie(ne(ke,[n]))}function De(n,t,d){return ie(ne(Ie,[te(n.picks),BigInt(n.stake),BigInt(d.counterpartyCollateral),t,d.counterparty,L,"0x"]))}function Pe(n,t,d,c){return ie(ne(Se,[n.token,$.address,t,d,BigInt(n.amount),BigInt(c)]))}function Y(n,t){let{input:d,wallet:c,nonce:m,deadline:y}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!y)&&i("Meridian exchange is missing its signing terms."),d.side==="buy"?(t||i("Meridian has not returned a winning bid."),{domain:l,primaryType:"MintApproval",types:{MintApproval:Ce},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:y}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:ve},message:{tradeHash:Pe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:y}}}function fe(n){let t=[BigInt(n.deadline)],d=n.continuation;if(d.stage==="primary_accept"||d.stage==="secondary_accept"){t.push(BigInt(d.acceptDeadline));let c=d.winningBid;d.stage==="primary_accept"&&t.push(BigInt(c.counterpartyDeadline)),c.buyerDeadline!==void 0&&t.push(BigInt(M(c.buyerDeadline,"the buyer deadline",!0)))}return t.reduce((c,m)=>c<m?c:m)}function H(n){n.channel?.check(),n.deadline&&j()>=fe(n)&&i("Meridian exchange expired. Start a fresh auction.")}var Fe=n=>{let t=new Map;function d(e){clearTimeout(e.timer),t.delete(e.continuation.requestId),e.channel?.stop("Meridian exchange is closed or expired. Start a fresh auction.")}function c(e,a){clearTimeout(e.timer),e.timer=setTimeout(()=>d(e),a),e.timer.unref?.()}function m(e){let{wallet:a,chainId:s,escrowContract:f,requestId:u}=e.continuation;return{wallet:a,chainId:s,escrowContract:f,requestId:u}}function y(e){return e.side!=="sell"?"":` Effective minimum sale proceeds: ${e.minPrice} USDe base units (${$.address}, 18 decimals). ${e.priceFloorSource==="explicit"?"Caller minPrice is unchanged; slippageBps does not reduce this floor.":`Default floor with ${e.slippageBps??0} bps slippage applied.`}`}async function l(e){let{input:a,wallet:s}=e,f=n.clientFor(k),u=a.side==="buy"?$.address:a.token,r=a.side==="buy"?a.stake:a.amount,[h,w]=await Promise.all([f.readContract({address:u,abi:J,functionName:"balanceOf",args:[s]}),f.readContract({address:u,abi:J,functionName:"allowance",args:[s,e.continuation.escrowContract]})]);if(a.side==="sell"&&await f.readContract({address:u,abi:J,functionName:"decimals"})!==18&&i("Meridian position tokens must have 18 decimals."),h>=BigInt(r)&&w>=BigInt(r))return;(e.continuation.stage==="primary_accept"||e.continuation.stage==="secondary_accept")&&i("Meridian prerequisites changed during the auction. Start a fresh auction after funding and approval.");let p,v;if(h<BigInt(r)){a.side==="sell"&&i("The wallet does not have enough position tokens to sell."),a.usdgAmountIn||i("Not enough USDe. Provide usdgAmountIn in USDG base units to quote a swap before the auction.");let b=await n.quoteSwap({from:G,to:$.address,amountIn:a.usdgAmountIn,...a.slippageBps===void 0?{}:{slippageBps:a.slippageBps}},s);(j()>=BigInt(M(b.expiresAt,"the swap expiry"))||BigInt(M(b.minAmountOut,"the swap minimum"))+h<BigInt(r))&&i("The USDG swap minimum does not cover the USDe stake, or the quote expired. Request a fresh quote with sufficient input.");let o=await n.buildSwap(b.quoteId,s);(!("txs"in o)||!o.txs.length)&&i("The swap coordinator did not return prerequisite transactions."),p=o.txs,v=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],v=`Approve exactly ${r} base units (18 decimals) of ${u} for ${e.continuation.escrowContract} on chain ${k}.`;p.some(b=>b.chainId!==k)&&i("Meridian prerequisite transactions must use chain 4663.");let P=await n.preview(p,s),T=P.changes.map(b=>{let o=b.amount.startsWith("-");return`${o?"-":"+"}${n.formatAmount(o?b.amount.slice(1):b.amount,b.token.decimals)} ${b.token.symbol} (${b.token.address}, chain ${b.token.chainId}, ${b.token.decimals} decimals)`}).join("; ");return e.channel?.stop("Meridian prerequisites must be mined before the auction."),e.channel=void 0,e.deadline=void 0,e.nonce=void 0,e.continuation={...m(e),stage:"prerequisites"},{steps:p.map(b=>({kind:"tx",tx:b})),continuation:structuredClone(e.continuation),summary:`${v}${y(a)} ${P.summary} ${T}. Mine these prerequisites before continuing; no RFQ has started.`}}function I(e){let a=e.continuation;a.stage==="prerequisites"&&i("Meridian prerequisites need to finish before signing."),H(e),c(e,Number(fe(e)-j())*1e3);let s=e.input,f=s.side==="buy"?`Stake ${s.stake} base units of USDe (${$.address}, 18 decimals)`:`Sell ${s.amount} base units of position ${s.token} (18 decimals)`,u=a.stage==="secondary_start"?"Initial buyer-zero, price-zero intent only.":a.stage==="primary_accept"?`Counterparty ${a.winningBid.counterparty}; counterparty collateral ${a.winningBid.counterpartyCollateral} USDe base units; counterparty deadline ${a.winningBid.counterpartyDeadline}.`:`Buyer ${a.winningBid.buyer}; receive ${a.winningBid.price} USDe base units (${$.address}, 18 decimals).`;return{steps:[{kind:"typedData",request:structuredClone(a.request)}],continuation:structuredClone(a),summary:`${f} on chain ${k}.${y(s)} Approval was checked on chain. ${u} Sign locally for domain ${a.request.domain.name}, version 1, escrow ${a.escrowContract}, signature deadline ${e.deadline}${"acceptDeadline"in a?`, acceptance deadline ${a.acceptDeadline}`:""}. External relayer settlement is pending; a signature is not a fill.`}}async function D(e){let a=await e.channel.wait("result"),s=_(a.winningBid),f=A(a.auctionId);s.auctionId!==f&&i("Meridian winning bid belongs to another auction.");let u=M(a.acceptDeadline,"the acceptance deadline",!0);if(e.input.side==="buy"){let r={auctionId:f,counterparty:A(s.counterparty),counterpartyCollateral:M(s.counterpartyCollateral,"the counterparty collateral"),counterpartyNonce:M(s.counterpartyNonce,"the counterparty nonce",!0),counterpartyDeadline:M(s.counterpartyDeadline,"the counterparty deadline",!0),receivedAt:A(s.receivedAt)};R(r.counterparty),(!Number.isFinite(Date.parse(r.receivedAt))||BigInt(r.counterpartyCollateral)<=1n||BigInt(r.counterpartyCollateral)<BigInt(e.input.minCounterpartyCollateral))&&i("Meridian winning bid counterparty collateral is below the caller minimum."),e.continuation={...m(e),stage:"primary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}else{let r={auctionId:f,buyer:A(s.buyer),price:M(s.price,"the sale price"),...s.buyerDeadline!==void 0?{buyerDeadline:M(s.buyerDeadline,"the buyer deadline",!0)}:{},...s.buyerNonce!==void 0?{buyerNonce:M(s.buyerNonce,"the buyer nonce",!0)}:{},...s.receivedAt!==void 0?{receivedAt:A(s.receivedAt)}:{}};R(r.buyer),(BigInt(r.price)<=1n||BigInt(r.price)<BigInt(e.input.minPrice))&&i("Meridian winning bid sale price is below the caller minimum."),e.continuation={...m(e),stage:"secondary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}return I(e)}async function S(e,a){let s=e.continuation;s.stage!=="primary_accept"&&s.stage!=="secondary_accept"&&i("Meridian exchange is not ready for acceptance."),H(e),e.channel.send("accept",{auctionId:s.auctionId,[e.input.side==="buy"?"predictorSignature":"sellerSignature"]:a}),c(e,15e4);let f=await e.channel.wait("filled",12e4),u=Z(f.transactionHash,32),r=n.clientFor(k),[h,w]=await Promise.all([r.waitForTransactionReceipt({hash:u,timeout:12e4}),r.getTransaction({hash:u})]);(h.status!=="success"||!g(h.transactionHash,u)||!g(w.hash,u)||!g(h.to,s.escrowContract)||!g(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:v}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!g(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!g(o.predictor,v)||!g(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!g(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!g(o.predictorSignature,a))&&i("Meridian mint receipt does not match the accepted prediction.")}else if(p.side==="sell"&&s.stage==="secondary_accept"){let o=me({abi:Me,data:w.input}).args[0];(!g(o.token,p.token)||!g(o.collateral,$.address)||!g(o.seller,v)||!g(o.buyer,s.winningBid.buyer)||o.tokenAmount!==BigInt(p.amount)||o.price!==BigInt(s.winningBid.price)||o.sellerNonce!==BigInt(e.nonce)||o.sellerDeadline!==BigInt(e.deadline)||!g(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let P=new Map,T=new Map;for(let o of h.logs){if(o.topics[0]!==$e||o.topics.length!==3)continue;(!/^0x[0-9a-fA-F]{64}$/.test(o.data)||!o.topics.slice(1).every(ge=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ge)))&&i("Meridian receipt has malformed transfer logs.");let U=`0x${o.topics[1].slice(-40)}`,E=`0x${o.topics[2].slice(-40)}`,q=o.address.toLowerCase(),z=BigInt(o.data);P.set(q,(P.get(q)??0n)+(g(E,v)?z:0n)-(g(U,v)?z:0n)),g(U,L)&&g(E,v)&&T.set(q,(T.get(q)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),U=[...T].filter(([E,q])=>!g(E,$.address)&&q===o&&P.get(E)===o);(U.length!==1||P.get($.address.toLowerCase())!==-BigInt(p.stake))&&i("Meridian mint receipt does not prove the expected collateral and position delta."),b=`${o} base units received in position ${U[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((P.get(p.token.toLowerCase())!==-BigInt(p.amount)||P.get($.address.toLowerCase())!==BigInt(s.winningBid.price))&&i("Meridian sale receipt does not prove the expected collateral and position delta."),b=`${p.amount} base units sold from position ${p.token}; ${s.winningBid.price} USDe base units received`):i("Meridian fill has a different exchange stage.");return{txs:[],hashes:[u],status:"mined",summary:`Mined: ${u}. Status: mined. Meridian ${p.side} filled by the external relayer. Successful receipt and transfer deltas verified on chain ${k}: ${b} (18 decimals); collateral USDe ${$.address} (18 decimals).`}}async function B(e,a,s){let f=R(s),u=Ae(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(A(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!g(w.wallet,f)||!pe(w.input,u)||!pe(w.continuation,h))&&i("Meridian continuation or arguments do not match the active wallet exchange."),w.busy&&i("Meridian exchange is already processing this continuation."),r=w}else{a.signature!==void 0&&i("A signature requires an active Meridian continuation."),t.size>=1e3&&i("Too many active Meridian exchanges. Please try again later.");let h=he(),w=setTimeout(()=>{let p=t.get(h);p&&d(p)},9e5);w.unref?.(),r={input:u,wallet:f,continuation:{stage:"prerequisites",wallet:f,chainId:k,escrowContract:e==="buy"?Q:V,requestId:h},busy:!1,timer:w},t.set(h,r)}r.busy=!0;try{H(r),await n.clientFor(k).getChainId()!==k&&i("Meridian requires an RPC on chain 4663.");let h=r.continuation.stage;h==="prerequisites"&&a.signature!==void 0&&i("Do not sign before Meridian prerequisites have mined.");let w=await l(r);if(w)return w;if(h==="prerequisites")return r.nonce=(ye(4).readUInt32BE()+1).toString(),r.deadline=(j()+300n).toString(),await n.clientFor(k).readContract({address:r.continuation.escrowContract,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i(`Meridian ${e==="buy"?"predictor":"seller"} nonce is already used. Start a fresh auction.`),r.channel=new ee(r.continuation.requestId,e==="buy"?"auction":"secondary.auction"),await r.channel.wait(),u.side==="buy"?(r.channel.send("start",{id:r.continuation.requestId,picks:u.picks,predictorCollateral:u.stake,predictor:f,predictorNonce:O(r.nonce),predictorDeadline:O(r.deadline),chainId:k,escrowContract:Q,mode:"blind"}),await D(r)):(r.continuation={...m(r),stage:"secondary_start",request:Y(r)},I(r));let p=Z(a.signature);if(e==="sell"&&await n.clientFor(k).readContract({address:V,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),e==="buy"&&await n.clientFor(k).readContract({address:Q,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian predictor nonce is already used. Start a fresh auction."),H(r),h==="secondary_start"&&u.side==="sell")return r.channel.send("start",{id:r.continuation.requestId,token:u.token,collateral:$.address,tokenAmount:u.amount,seller:f,sellerNonce:O(r.nonce),sellerDeadline:O(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let v=await S(r,p);return d(r),v}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let C={continuation:{type:"object",description:"Internal continuation returned by the previous local signing round."},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Internal hexadecimal signature supplied by local signing; never enter manually."}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...C,stake:x('USDe stake in base units (18 decimals): "1000000000000000000" = 1 USDe.'),minCounterpartyCollateral:x('Minimum counterparty USDe collateral in base units (18 decimals): "1000000000000000000" = 1 USDe.'),usdgAmountIn:x('USDG swap input in base units if USDe is short (6 decimals): "1000000" = 1 USDG.'),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points (50 = 0.5%)."},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:{...W,description:"Condition resolver contract address on chain 4663."},conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Condition identifier as a 0x-prefixed even-length hex string."},predictedOutcome:{type:"integer",enum:[0,1],description:"Predicted binary outcome, 0 or 1, as defined by the condition."}}},description:"Prediction picks for the auction."}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...C,token:{...W,description:"Position token address on chain 4663."},amount:x('Position token amount in base units (18 decimals): "1000000000000000000" = 1 position token.'),minPrice:x('Minimum total USDe proceeds in base units (18 decimals): "1000000000000000000" = 1 USDe. Explicit minimum is not reduced by slippage.'),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points (50 = 0.5%); applies only to the default floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ce as a,ve as b,Fe as c};
@@ -0,0 +1 @@
1
+ import{k as h,m as x,n as l}from"./QJNLLI6N.js";import{g}from"./NWNYJ26T.js";import{a as r}from"./XSD5NL7J.js";import{encodeFunctionData as y,erc20Abi as S,getAddress as f,parseAbi as R}from"viem";var W=[{chainId:1,vault:"0x57b68c4ea221ee8da6eb14ebdfccee5177567771",asset:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",gateway:"0xed8a2a23bf9d6818651527daaf3bf4ffeb53945f"},{chainId:42161,vault:"0xc7273772b87860097373d91b3880fd4cc61fba2d",asset:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",gateway:"0x67defe8d90c8cd013fd527669e76e0be420f1208"}].map(t=>({chainId:t.chainId,vault:f(t.vault),asset:f(t.asset),gateway:f(t.gateway)})),E=R(["function balanceOf(address) view returns (uint256)","function asset() view returns (address)","function yieldPool() view returns (address)","function maxWithdraw(address) view returns (uint256)","function convertToAssets(uint256) view returns (uint256)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function redeem(uint256,address,address) returns (uint256)","function withdraw(uint256,address,address) returns (uint256)"]),O=R(["function redeem(address,uint256,address,uint256) returns (uint256)","function withdraw(address,uint256,address,uint256) returns (uint256)"]),I={type:"string",pattern:"^[1-9][0-9]*$"},A={type:"integer",enum:[1,42161]};function T(t){let o=W.find(i=>i.chainId===x(t));if(!o)throw new r("Relay legacy vault exits support Ethereum (1) and Arbitrum (42161).");return o}function b(t){let o=l(t);if(o==="0")throw new r("Provide a positive Relay vault amount or limit.");return o}function H(t,o){let i=T(t.chainId),s=f(h(o));if(Object.keys(t).some(c=>!["chainId","mode","amount","native","minAssetsOut","maxSharesIn"].includes(c)))throw new r("Provide only the documented Relay vault exit arguments.");if(t.mode!=="redeem"&&t.mode!=="withdraw")throw new r("Choose redeem (shares) or withdraw (WETH amount).");if(t.native!==void 0&&typeof t.native!="boolean")throw new r("Provide native as a boolean.");let e=b(t.amount),n=t.native===!0,a=t.mode==="redeem";if(!a&&!n)throw new r("Direct WETH withdrawals cannot enforce maxSharesIn on-chain. Use native withdraw or redeem a fixed number of shares.");if(t.minAssetsOut!==void 0&&(!n||!a)||t.maxSharesIn!==void 0&&a)throw new r("minAssetsOut applies only to native redeem; maxSharesIn applies only to withdraw.");let d=n&&a?b(t.minAssetsOut):void 0,u=a?e:b(t.maxSharesIn),w=(c,p,v)=>({to:c,data:p,chainId:i.chainId,value:"0",description:v}),m=[];return n?(m.push(w(i.vault,y({abi:S,functionName:"approve",args:[i.gateway,BigInt(u)]}),`Approve exactly ${u} WETH-REL share base units for the Relay native gateway.`)),m.push(w(i.gateway,y({abi:O,functionName:t.mode,args:[i.vault,BigInt(e),s,BigInt(a?d:u)]}),`Relay legacy vault ${t.mode} to native ETH for ${s}.`))):m.push(w(i.vault,y({abi:E,functionName:t.mode,args:[BigInt(e),s,s]}),`Relay legacy vault ${t.mode} to WETH for ${s}.`)),{pin:i,txs:m,wallet:s,redeem:a,native:n,amount:e,maxSharesIn:u,minAssetsOut:d}}function L(t,o,i){let s=H(o,i).txs;if(t.length!==s.length||t.some((e,n)=>e.chainId!==s[n].chainId||h(e.to)!==h(s[n].to)||e.value!=="0"||!g(e.data,s[n].data)))throw new r("Relay vault transactions differ from the requested exit.")}var k=t=>{async function o(i,s){let e=T(i),n;try{n=t.clientFor(e.chainId)}catch(c){throw/No RPC URL configured for chain/.test(t.plainError(c))?new r(`Relay legacy vault reads and exits on chain ${e.chainId} need an RPC. Ask the operator to configure OAK_RPC_URL_${e.chainId} on the server. No vault balances were checked.`):c}if(await n.getChainId()!==e.chainId)throw new r("The RPC chain does not match the Relay vault chain.");let a=(c,p,v=[])=>n.readContract({address:c,abi:E,functionName:p,args:v});if(h(await a(e.vault,"asset"))!==h(e.asset))throw new r("Relay vault asset does not match the pinned WETH.");let d=l(String(await a(e.vault,"balanceOf",[s]))),u=f(h(await a(e.vault,"yieldPool"))),w=l(String(await a(e.vault,"convertToAssets",[BigInt(d)]))),m=l(String(await a(u,"maxWithdraw",[e.vault])));return{pin:e,shares:d,assets:w,liquidAssets:m,read:a}}return{tools:[{name:"relay_vault_status",inputSchema:{type:"object",description:"Read legacy vault shares and shared liquidity. Requires server OAK_RPC_URL_1 or OAK_RPC_URL_42161 for the selected chain; no API key. New deposits are unsupported.",additionalProperties:!1,required:["chainId"],properties:{chainId:{...A,description:"Legacy vault chain ID: 1 for Ethereum or 42161 for Arbitrum."}}},execute:async(i,s)=>{if(Object.keys(i).some(u=>u!=="chainId"))throw new r("Provide only the Relay vault chainId.");let{pin:e,shares:n,assets:a,liquidAssets:d}=await o(i.chainId,s);return{chainId:e.chainId,vault:e.vault,shares:{token:{address:e.vault,chainId:e.chainId,symbol:"WETH-REL",decimals:18},amount:n},assets:{token:{address:e.asset,chainId:e.chainId,symbol:"WETH",decimals:18},amount:a},liquidAssets:d,summary:"Relay legacy vault wind-down: new deposits are unsupported. Available yield-pool liquidity is shared by all LPs and may change. Withdraw with relay_vault_withdraw; gas is paid in ETH on the vault chain."}}},{name:"relay_vault_withdraw",inputSchema:{type:"object",additionalProperties:!1,required:["chainId","mode","amount"],properties:{chainId:{...A,description:"Legacy vault chain ID: 1 for Ethereum or 42161 for Arbitrum."},mode:{type:"string",enum:["redeem","withdraw"],description:"redeem fixes share input; withdraw fixes asset output (WETH or native ETH)."},amount:{...I,description:'Amount in base units: WETH-REL shares for redeem or WETH for withdraw (both 18 decimals: "1000000000000000000" = 1 WETH-REL share or 1 WETH).'},native:{type:"boolean",description:"Receive native ETH through the gateway."},minAssetsOut:{...I,description:'Minimum ETH output in base units for native redeem (18 decimals: "1000000000000000000" = 1 ETH).'},maxSharesIn:{...I,description:'Maximum WETH-REL shares in base units for withdraw (18 decimals: "1000000000000000000" = 1 WETH-REL).'}}},execute:async(i,s)=>{let e=H(i,s),n=await o(i.chainId,s),a=e.redeem?e.amount:l(String(await n.read(e.pin.vault,"previewWithdraw",[BigInt(e.amount)]))),d=e.redeem?l(String(await n.read(e.pin.vault,"previewRedeem",[BigInt(e.amount)]))):e.amount;if(BigInt(a)>BigInt(n.shares)||BigInt(a)>BigInt(e.maxSharesIn))throw new r("Relay vault exit exceeds your shares or maxSharesIn.");if(BigInt(d)>BigInt(n.liquidAssets))throw new r("Relay vault liquidity is insufficient. Withdraw less or retry when liquidity returns.");if(e.minAssetsOut!==void 0&&BigInt(d)<BigInt(e.minAssetsOut))throw new r("Relay vault output is below minAssetsOut.");let u=await t.preview(e.txs,s);return{txs:e.txs,preview:u,chainId:e.pin.chainId,expectedAssets:d,expectedShares:a,summary:`Relay legacy vault exit on chain ${e.pin.chainId}: ${a} share base units for about ${d} ${e.native?"ETH":"WETH"} base units (18 decimals), to ${e.wallet}. ${e.minAssetsOut?`Gateway minimum ${e.minAssetsOut}.`:e.redeem?"Direct ERC-4626 redeem has no calldata minimum output.":`Gateway maximum input ${e.maxSharesIn} share base units.`} Review the local preview and confirm before signing. No destination bridge or future yield is promised.`}}}]}};export{W as a,H as b,L as c,k as d};
@@ -0,0 +1 @@
1
+ import{a as v}from"./OZ5MDUD2.js";import{h as w}from"./2GXHYI23.js";import{a as y}from"./JKD2B6OX.js";import{b as P,c as k,d as l}from"./2MZXTOZU.js";import{k as h}from"./U2YCQWZK.js";import{a as f}from"./43LI5NKJ.js";import{m as b,n as B}from"./NWNYJ26T.js";import{a as d}from"./FWD4L3CJ.js";import{a as s}from"./XSD5NL7J.js";import{erc20Abi as L,formatUnits as R}from"viem";var U=70515n,C=250202n,S=568341n;function N(a,r){return{token:{...a},amount:r.toString()}}function A(a){if(a.network!==void 0&&a.network!=="mainnet")throw new s("LayerBank requires chain 4663.")}async function g(a,r,n,e){try{return b(await a.readContract({address:r.address,abi:L,functionName:"balanceOf",args:[n],blockNumber:e}),"LayerBank returned a malformed wallet balance read.")}catch(t){throw t instanceof s?t:new s("LayerBank wallet balance could not be read. Please try again.")}}async function T(a,r,n){try{let[e,t]=await Promise.all([r.getGasPrice(),h("ETH",{client:r,http:a.http,chainId:d,blockNumber:n})]),i=B(t.usdE18,"LayerBank gas reference is unavailable.",{positive:!0}),c=b(e,"LayerBank gas reference is unavailable.");if(c===0n)throw new s("LayerBank gas reference is unavailable.");let u=m=>Number(R(m*c*i/10n**18n,18)),o=u(U+C),p=u(S);if(![o,p].every(m=>Number.isFinite(m)&&m>0))throw new s("LayerBank gas reference is unavailable.");return{gasInUsd:o,gasOutUsd:p}}catch{throw new s("LayerBank gas costs could not be checked against a fresh ETH/USD reference. Please try again.")}}async function x(a,r){A(a),f(r);let n=a.clientFor(d),e=await y(n),[t,i,c,u]=await Promise.all([g(n,k,r,e.blockNumber),g(n,l,r,e.blockNumber),v(a.http),T(a,n,e.blockNumber)]),o=[...c.checks,"Gas costs use measured USDG calls plus 20% headroom; entry includes approval and supply."];e.active||o.push("LayerBank reserve is inactive."),e.frozen&&o.push("LayerBank reserve is frozen for deposits."),e.paused&&o.push("LayerBank reserve is paused."),e.capRoomBase===0n&&o.push("LayerBank supply cap has no room left.");let p={rateBasePct:e.rateBasePct,...c.bonus==="unavailable"?{}:{bonus:c.bonus},cashUsdgBase:e.cashUsdgBase,capRoomBase:e.capRoomBase,open:e.active&&!e.frozen&&!e.paused&&e.capRoomBase>0n,walletUsdgBase:t,walletReceiptBase:i,...u,checks:o};return{reserve:e,reading:p}}function F(a){return async r=>{try{return(await x(a,r)).reading}catch(n){return{rateBasePct:0,cashUsdgBase:0n,capRoomBase:0n,open:!1,walletUsdgBase:0n,walletReceiptBase:0n,gasInUsd:0,gasOutUsd:0,checks:[n instanceof s?a.plainError(n):"LayerBank could not be checked right now. Please try again."]}}}}async function W(a,r){A(a),f(r);let n=a.clientFor(d),e=await y(n),t=await g(n,l,r,e.blockNumber);if(t===0n)return[];let i=a.formatAmount(t.toString(),6);return[{module:"layerbank",id:`${d}:${P}`,chainId:d,assets:[N(l,t)],economics:{principal:[w("redeemable",{token:{...k},amount:t.toString(),source:"layerbank.receiptBalance",heldAs:l.address,measuredAtBlock:e.blockNumber.toString()})],debt:[],rewards:[],backing:[],coverage:{complete:!0}},description:`${i} lRobUSDG = ${i} USDG; base supply rate ${e.rateBasePct}% a year, read now.`}]}export{U as a,C as b,S as c,N as d,A as e,g as f,x as g,F as h,W as i};
@@ -0,0 +1 @@
1
+ import{a as k}from"./ZOMFHTB2.js";import{e as P,i as O}from"./4FPV4CRC.js";import{a as g,b as f,f as E,g as S}from"./J73ATSEQ.js";import{a as h,w as M}from"./BAIY32AV.js";import{a as y}from"./66F5ZH34.js";import{c as v,g as C}from"./NWNYJ26T.js";import{a as b}from"./FWD4L3CJ.js";import{a as l}from"./XSD5NL7J.js";import{encodeFunctionData as c,parseAbi as H,zeroAddress as R}from"viem";var r=H(["function owner() view returns (address)","function feeTo() view returns (address)","function feeToSetter() view returns (address)","function protocolFeeController() view returns (address)","function setFeeTo(address)","function setFeeToSetter(address)","function setOwner(address)","function enableFeeAmount(uint24,int24)","function setFeeProtocol(uint8,uint8)","function collectProtocol(address,uint128,uint128) returns (uint128,uint128)","function transferOwnership(address)","function setProtocolFeeController(address)","function setProtocolFee((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks),uint24)","function collectProtocolFees(address recipient,address currency,uint256 amount) returns (uint256)"]),K=["set_fee_recipient","set_fee_setter","set_owner","enable_fee","set_pool_fee","collect_protocol","set_controller"],V={version:{description:'Uniswap version: "v2" for pairs, "v3" for concentrated liquidity or "v4" for PoolManager.',type:"string",enum:["v2","v3","v4"]},operation:{description:"set_fee_recipient/set_fee_setter: v2 roles; set_owner: owner; enable_fee: v3 tier; set_pool_fee: protocol fees; collect_protocol: collect fees; set_controller: v4 controller.",type:"string",enum:K},target:{...v,description:"Intended fee recipient, fee setter, owner or controller address for the selected administrative operation."},token0:{...v,description:"Lower sorted ERC-20 token address; use WETH for native ETH in v3."},token1:{...v,description:"Higher sorted ERC-20 token address."},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"integer"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"integer"},fee0:{description:"Token0 or zero-for-one protocol fee: v3 divisor 0 (off) or 4\u201310; v4 pips, hundredths of a basis point, from 0 to 1000 (1000 = 0.1%).",type:"integer"},fee1:{description:"Token1 or one-for-zero protocol fee: v3 divisor 0 (off) or 4\u201310; v4 pips, hundredths of a basis point, from 0 to 1000 (1000 = 0.1%).",type:"integer"},currency:{...v,description:"Address of the currency whose protocol fees are collected; the zero address means native ETH."},amount:y('Amount of currency in base units; use currency decimals. Example: "1000000" = 1 currency at 6 decimals.'),amount0Max:y('Maximum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'),amount1Max:y('Maximum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'),poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object"}};function G(_){let x=async e=>{let i=_.clientFor(b);if(e==="v2"){let[t,o]=await Promise.all([i.readContract({address:k,abi:r,functionName:"feeToSetter"}),i.readContract({address:k,abi:r,functionName:"feeTo"})]);return{version:e,contract:k,owner:t,feeRecipient:o}}if(e==="v3")return{version:e,contract:P.factory,owner:await i.readContract({address:P.factory,abi:r,functionName:"owner"})};if(e==="v4"){let[t,o]=await Promise.all([i.readContract({address:h,abi:r,functionName:"owner"}),i.readContract({address:h,abi:r,functionName:"protocolFeeController"})]);return{version:e,contract:h,owner:t,controller:o}}throw new l("Provide protocol version v2, v3 or v4.")};return{tools:[{name:"uniswap_protocol_status",inputSchema:{type:"object",additionalProperties:!1,required:["version"],properties:{version:V.version}},async execute(e){return S(e,["version"]),x(e.version)}},{name:"uniswap_protocol_admin",inputSchema:{type:"object",additionalProperties:!1,required:["version","operation"],properties:V},async execute(e,i){let{version:t,operation:o}=e,w=await x(t),I=_.clientFor(b),T=t==="v4"&&["set_pool_fee","collect_protocol"].includes(String(o))?"controller"in w?w.controller:void 0:w.owner;if(!T||!C(T,i))throw new l("The signing wallet does not hold the required Uniswap owner/controller role.");let N=w.contract,s,a,A=()=>{let n=f(e.target);if(n===R)throw new l("Administration target must be nonzero.");return n},d=(n,p,u,m)=>{if(typeof n!="number"||!Number.isInteger(n)||n<u||n>m)throw new l(`${p} must be an integer from ${u} to ${m}.`);return n};if(t==="v2"&&o==="set_fee_recipient")a=["target"],s=c({abi:r,functionName:"setFeeTo",args:[f(e.target)]});else if(t==="v2"&&o==="set_fee_setter")a=["target"],s=c({abi:r,functionName:"setFeeToSetter",args:[A()]});else if(t==="v3"&&o==="set_owner")a=["target"],s=c({abi:r,functionName:"setOwner",args:[A()]});else if(t==="v3"&&o==="enable_fee")a=["fee","tickSpacing"],s=c({abi:r,functionName:"enableFeeAmount",args:[d(e.fee,"fee",0,999999),d(e.tickSpacing,"tickSpacing",1,16383)]});else if(t==="v3"&&["set_pool_fee","collect_protocol"].includes(String(o))){a=["token0","token1","fee",...o==="set_pool_fee"?["fee0","fee1"]:["amount0Max","amount1Max"]];let n=f(e.token0),p=f(e.token1),u=d(e.fee,"fee",0,999999);if(N=await I.readContract({address:P.factory,abi:O,functionName:"getPool",args:[n,p,u]}),N===R)throw new l("No factory-verified v3 pool exists for these tokens and fee.");if(o==="set_pool_fee"){let m=z=>{let F=d(z,"fee divisor",0,10);if(F!==0&&F<4)throw new l("V3 protocol fee divisors must be zero or 4 through 10.");return F};s=c({abi:r,functionName:"setFeeProtocol",args:[m(e.fee0),m(e.fee1)]})}else s=c({abi:r,functionName:"collectProtocol",args:[i,g(e.amount0Max,"amount0Max",128,!0),g(e.amount1Max,"amount1Max",128,!0)]})}else if(t==="v4"&&o==="set_owner")a=["target"],s=c({abi:r,functionName:"transferOwnership",args:[A()]});else if(t==="v4"&&o==="set_controller")a=["target"],s=c({abi:r,functionName:"setProtocolFeeController",args:[f(e.target)]});else if(t==="v4"&&o==="set_pool_fee"){a=["poolKey","fee0","fee1"];let n=M(e.poolKey),p=d(e.fee0,"fee0 pips",0,1e3),u=d(e.fee1,"fee1 pips",0,1e3);s=c({abi:r,functionName:"setProtocolFee",args:[n,p+(u<<12)]})}else if(t==="v4"&&o==="collect_protocol")a=["currency","amount"],s=c({abi:r,functionName:"collectProtocolFees",args:[i,f(e.currency),g(e.amount,"amount",256,!0)]});else throw new l("This operation is not supported by the selected Uniswap protocol version.");return S(e,["version","operation",...a]),E(_,[_.unsignedTx({to:N,data:s,value:"0",chainId:b,description:`Uniswap ${t} protocol administration: ${o}. Role holder ${i}.`})],i,"Privileged protocol operation. Review the exact role/recipient/fee changes. Protocol fee collections pay the signing wallet; no wallet token approval is required.")}}]}}export{r as a,G as b};
@@ -0,0 +1,18 @@
1
+ import{a as ae}from"./3CCBUYUM.js";import{a as xt,d as It,e as Tt}from"./EVBHQQQG.js";import{a as Re}from"./7MR37STI.js";import{a as Ze,b as Ge,d as At}from"./L646YWDP.js";import{h as Je,i as St}from"./2GXHYI23.js";import{b as kt,c as yt,d as gt}from"./DNNFKDZR.js";import{d as wt,e as te}from"./CAWTAR5V.js";import{a as ht}from"./H5DY7CNB.js";import{b as bt}from"./SPJCSEKP.js";import{a as q}from"./43LI5NKJ.js";import{a as A,d as W}from"./66F5ZH34.js";import{d as Oe,g as R,i as Ee}from"./NWNYJ26T.js";import{b as Le}from"./IX3GZMTM.js";import{k as ft}from"./6NUNCD5J.js";import{a as f,i as z}from"./FWD4L3CJ.js";import{a as i,e as ie}from"./XSD5NL7J.js";import{a as Ye}from"./JXOEJPJ4.js";import{encodeFunctionData as be,erc20Abi as Qa,getAddress as aa,parseAbi as pt,zeroAddress as Xa}from"viem";import{decodeAbiParameters as ca,encodeFunctionData as ua,getAddress as le,parseAbiParameters as ma,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as ra,encodeFunctionData as na,erc20Abi as sa,getAddress as Ct,parseAbi as ia,parseAbiParameters as la,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",da="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=ia(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${da} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var Pt=(e,t)=>e<t?e:t;async function io(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),c=e.clientFor(f),m=await At(c,t,s),d=(S,B,Ce,ee=[])=>c.readContract({address:S,abi:B,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,b,h,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,sa,"balanceOf",[n]),d(t,Ze,"previewRedeem",[a])]);if(typeof b!="string"||Ct(b)!==$)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<p.timestamp||u>p.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Ge(h))throw new i("maxShares exceeds the wallet share balance.");let y=Pt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-y,T=k[0]?.penalty??0n,x=g*10n**18n/(10n**18n+T);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(x===0n)break;let B=Pt(S.supplied,x);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),x-=B}if(x>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Ge(w))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let P=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],E=(await Promise.all(P.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,B)=>S+Ge(B),0n);if(E===0n||E>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>ra(la(Lt),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${E} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,v=na({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),U=[e.approval(t,et,E.toString(),f),e.unsignedTx({to:et,data:v,value:"0",chainId:f,description:F})],D=await e.preview(U,n),V=-D.changes.filter(S=>S.token.chainId===f&&R(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(V<=0n||V>E)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:U,preview:D,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},_e={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},pa=ma("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),$t=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:Ut,description:"Bundle: supply, withdraw, supplyCollateralAndBorrow, repayAndWithdrawCollateral, or migrateBorrowPosition (move debt to destinationMarketId)."},marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits); the source market for migrateBorrowPosition."},destinationMarketId:{type:"string",description:"Only for migrateBorrowPosition: verified market id (0x + 64 hex) to move the borrow into; must share the same tokens."},assets:A(`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),collateralAssets:A(`Collateral amount in base units of the market's collateral token (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),shares:A("Market share amount in base units (supply or borrow shares, read the position), instead of assets. Give assets or shares, not both."),maxRepayAssets:A('Most loan token you accept paying to repay, in base units of the loan token (read its decimals). Example: "1000000" = 1 USDG.'),maxLtv:A("Highest loan-to-value allowed after the bundle, as an 18-decimal wad in base units (0.8e18 = 80 percent); cannot exceed the market LLTV."),deadline:A("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000."),allocations:{type:"array",maxItems:4,description:"Up to four Public Allocator moves that add liquidity to the market before borrowing or withdrawing; one per vault.",items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string",description:"Pinned NetNet or Longbow V2 vault address (0x + 40 hex) to pull liquidity from; one entry per vault."},sourceMarketId:{type:"string",description:"Source market id (0x + 64 hex) to pull from; omit to allocate idle vault assets."},assets:A(`Amount to reallocate, in base units of the vault's asset (USDG 6 decimals, WETH 18). Example: "1000000" = 1 USDG.`),maxPenaltyAssets:A(`Highest allocator penalty you accept, in base units of the vault's asset. Example: "10000" = 0.01 USDG for a 6-decimal asset.`)}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(f);if(await n.getChainId()!==f||typeof r!="string"||!Ut.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(v=>!l.includes(v)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,c]=await Promise.all([n.readContract({address:we,abi:Re,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:we,abi:Re,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(le(u)!==$||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async v=>{if(typeof v!="string"||!j(v))throw new i("Choose a verified Morpho market with a supported exit.");let U=await n.readContract({address:$,abi:O,functionName:"idToMarketParams",args:[v],blockNumber:a.number}),D={loanToken:le(U[0]),collateralToken:le(U[1]),oracle:le(U[2]),irm:le(U[3]),lltv:U[4]};if(!R(ke({...D,lltv:String(D.lltv)}),v))throw new i("Blue bundle market identity mismatch.");return D},d=await m(t.marketId),p=r==="migrateBorrowPosition"?await m(t.destinationMarketId):d;if(d.loanToken!==p.loanToken||d.collateralToken!==p.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:$,abi:O,functionName:"isAuthorized",args:[s,we],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${we}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),h=t.shares===void 0?0n:N(t.shares,!0),w=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(h===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&h>0n||b===0n&&h===0n&&w===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],x=0n;for(let v of k){if(!v||typeof v!="object"||Array.isArray(v)||Object.keys(v).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let U=v,D=await It(e,{vault:U.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(D.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(D.definition.vault.toLowerCase());let V=N(U.assets),S=N(U.maxPenaltyAssets,!0);if(!D.permission||V>=1n<<128n||V>D.headroom||D.penalty>10n**18n||D.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(V*D.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=B;let Ce=U.sourceMarketId===void 0,ee=Ce?void 0:D.sources.find(Xe=>R(Xe.id,String(U.sourceMarketId)));if(Ce?!D.canIdle||V>D.data.idle:!ee||!ee.canPull||V>ee.capacity||V>D.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:D.definition.vault,adapter:D.target.adapter,marketParams:D.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?ca(pa,ee.data)[0]:D.params,assets:V,penalty:D.penalty,fromIdle:Ce})}let M,C,P,I=0n;if(r==="supply")M="blueBundlesV1Supply",P=d.loanToken,I=b,C=[d,b,tt,0n,he,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[d,b,h,_e,T,0n,he,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",P=d.collateralToken,I=w,x>=b&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[d,w,b,y,tt,_e,T,0n,he,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",P=d.loanToken,I=N(t.maxRepayAssets,!0),b>I||h>0n&&I===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[d,b,h,I,w,y,tt,_e,0n,he,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[d,p,y,_e,T,0n,he,o];let E=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${I}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...P&&I?[e.approval(P,we,I.toString(),f)]:[],e.unsignedTx({to:we,data:ua({abi:Re,functionName:M,args:C}),value:"0",chainId:f,description:E})],H=await e.preview(Z,s),F=new Map;for(let v of H.changes)if(BigInt(v.amount)<0n){let U=v.token.address.toLowerCase();F.set(U,(F.get(U)??0n)-BigInt(v.amount))}if([...F].some(([v,U])=>!P||v!==P.toLowerCase()||U>I))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:E}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as fa,encodeAbiParameters as Rt,encodeFunctionData as at,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as ba}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ha=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=ae.find(e=>e.name==="take"),Ot=[nt.inputs[0]],wa=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(wa,[e])]));return rt(Bt(["0xff",e.midnight,ba,t]))}var de=10n**18n,Gt=(e,t)=>(e+(t-1n)/2n)/t;function _t(e){if(e<0n)return 10n**36n/_t(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*de),l=n*r/(3n*de);return de+r+n+l<<s}function ka(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Gt(Gt(10n**36n,de+_t(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function He(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function ot(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ya=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let a=He(n,32),o=e.clientFor(f);if(await o.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),c=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await c("toMarket",[a]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![z[f].tokens.USDG.address,z[f].tokens.WETH.address].some(k=>R(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[p,b,h,w]=await Promise.all([c("position",[a,l]),c("updatePositionView",[m,a,l]),c("marketState",[a]),c("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Nt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Nt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:f}};return{id:a,rpc:o,block:u,market:m,read:c,token:y,loan:await y(m.loanToken),position:ot(p,6),updated:ot(b,3),state:ot(h,13),healthy:w}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,c)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,d)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ya(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string",description:"Hex proof data (0x...) that the offer's pinned ratifier uses to confirm the maker approved this offer."},units:A("Fixed debt units to trade, as a decimal string below 2^128. The asset cost or proceeds follow from the offer price; maxAssets and minAssets bound them."),maxAssets:A('Most loan token you will spend when buying credit, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minAssets:A('Least loan token you must receive when selling credit or borrowing, in base units of the market loan token. Example: "1000000" = 1 USDG.')},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=He(n.offer),[o]=fa(Ot,a);if(!R(Rt(Ot,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Et(o.market),l),c=N(n.units),m=N(n.maxAssets,!0),d=N(n.minAssets,!0),p=He(n.ratifierData);if(c>=1n<<128n||R(o.maker,l)||o.callback!==ye||o.callbackData!=="0x"||!ha.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==ye||!o.buy&&o.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&c>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),h=ka(o.tick);if(b>h&&o.buy)throw new i("Settlement fee exceeds the offer price.");let w=o.buy?h-b:h,y=w+b,k=v=>o.buy?v/de:(v+de-1n)/de,g=k(c*y),T=k(c*w);if(o.buy?T<d||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||x+(o.maxAssets?o.buy?g:T:c)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],P=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,p,l],blockNumber:u.block.number});if(M!==!0||P!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let I=at({abi:ae,functionName:"take",args:[o,p,c,l,o.buy?l:ye,ye,"0x"]}),E=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),f)],e.unsignedTx({to:Y,data:I,value:"0",chainId:f,description:E})],H=await r(Z,l,E),F=H.preview.changes.filter(v=>v.token.chainId===f&&R(v.token.address,u.loan.address)).reduce((v,U)=>v+BigInt(U.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"],description:"Action: add or remove collateral, repay debt, withdraw matured credit, refresh the position, or claim continuous fees (fee claimer only)."},amount:A('Amount in base units of the relevant token: the collateral token for collateral operations, else the loan token (read decimals). Example: "1000000" = 1 USDG.'),collateralIndex:{type:"integer",minimum:0,maximum:127,description:"Zero-based position of the collateral in the market collateral list; required for supplyCollateral and withdrawCollateral only."}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,c,m=a.loan,d=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(d=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,d,l]}else{if(d=N(n.amount),d>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let h=BigInt(String(n.collateralIndex)),w=await a.token(a.market.collateralParams[Number(h)].token);if(m=w,o==="withdrawCollateral"&&d>await a.read("collateral",[a.id,l,h]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,h,d,l]:[a.market,h,d,l,l],o==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&d>a.position[4]||o==="withdraw"&&(d>a.updated[0]||d>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,d,l,ye,"0x"]:[a.market,d,l,l],o==="repay"&&(c=a.loan)}}let p=`Midnight ${o}: ${d} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:at({abi:ae,functionName:String(o),args:u}),value:"0",chainId:f,description:p})];return r(b,l,p)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"],description:"Midnight management function name; role-gated except setConsumed and setIsAuthorized, which act on this wallet."},values:{type:"array",maxItems:3,description:"Ordered arguments for the chosen operation, as in the Midnight ABI: decimal strings for integers (base units), 0x addresses or bytes32, or booleans.",items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(p=>p.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let c=e.clientFor(f);if(await c.getChainId()!==f)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((p,b)=>{let h=n.values[b];if(p.type==="bool"){if(typeof h!="boolean")throw new i("Use boolean management values.");return h}if(p.type==="address")return Ee(h,"Use explicit management addresses.",Oe);if(p.type==="bytes32")return He(h,32);if(/^uint/.test(p.type)){let w=N(h,!0);if(w>=1n<<BigInt(p.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return w}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!R(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let p=await c.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:at({abi:ae,functionName:o,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as ga,encodeFunctionData as G,erc20Abi as it,getAddress as L,isAddress as Fe,keccak256 as Sa,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Aa="https://api.morpho.org/graphql",$=L(z[f].morpho.morpho_blue.address),xa=L(z[f].morpho.adaptive_curve_irm.address),Ia=L(z[f].morpho.USDG.address),me=L(z[f].morpho.WETH.address),Ta=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Ma={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},lt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],va=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return va.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Ma[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,Ue=120n,ze=1000000n,We=1n,Se=10n**18n,Pa=10n**36n,jt=(1n<<128n)-1n,Ca=(1n<<256n)-1n,X=Ve(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),La=Ve(["function price() view returns (uint256)"]),Da=Ve(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),Kt=Ve(["function deposit() payable"]);function pe(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function $e(e,t){return e===0n?0n:(e+t-1n)/t}function Ua(e,t,s){return e*(s+ze)/(t+We)}function $a(e,t,s){return $e(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return $e(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Pa*s/Se}function Ba(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function xe(e,t){let s=[],r={};for(let n of t.changes){let l=Ba(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Qt(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function je(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Fe(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Le(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=Se)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function ke(e){let t=je(e),s=ga(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return Sa(s)}function dt(e){let t=e.toLowerCase();return t===ht.toLowerCase()||t===wt.toLowerCase()||t===te.toLowerCase()}function Ie(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function ne(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function Xt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=f){if(q(t),dt(t))return{...kt,chainId:s};let r=L(t),n=r.toLowerCase();if(s===f){if(n===Ia.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,a]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[o]=re(J("string"),l),[u]=re(J("uint8"),a);return{address:r,symbol:Xt(o),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,$,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=re(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function Jt(e,t){let s=await ne(e,$,G({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Te(e,t,s){let r=await ne(e,$,G({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Ke(e,t){let s=await ne(e,L(t),G({abi:La,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Na(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,L(t.irm),G({abi:Da,functionName:"borrowRateView",args:[t,s]})),[n]=re(J("uint256"),r);return n}function Qe(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=$e(n*n,2n*Se),a=$e(l*n,3n*Se);return e.totalBorrowAssets+$e(e.totalBorrowAssets*(n+l+a),Se)}async function Be(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Na(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:Qe(s,l,o),accruedThrough:o,rate:l}}async function Zt(e,t,s){let r=await ne(e,L(t),G({abi:it,functionName:"balanceOf",args:[L(s)]})),[n]=re(J("uint256"),r);return n}async function fe(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?je(n):void 0,a=l?ke(l):void 0,o=r!==void 0?Qt(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!j(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[c,m]=await Promise.all([Yt(e,u),Jt(e,u)]);if(c.loanToken===te||c.collateralToken===te||c.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${f}.`);let d=ke(c);if(d.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${d}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===c.oracle.toLowerCase()&&l.irm.toLowerCase()===c.irm.toLowerCase()&&l.lltv===c.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:c,marketState:m}}function Me(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Le(t);if(s<=0n||s>jt)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function ve(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function Oa(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:a,marketParams:o}=await fe(l,t,!0),u=await Q(l,o.collateralToken,f),c=o.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),b=p.toString(),h=e.formatAmount(b,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:b,description:`Wrap ${h} ETH into WETH at ${me}.`})),w.push(e.approval(o.collateralToken,$,b,f)),w.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supplyCollateral",args:[o,p,n,"0x"]}),value:"0",description:`Supply ${h} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply_collateral",chainId:f,marketId:a,marketParams:pe(o),collateralToken:u,assets:b,formattedAssets:h,onBehalf:n,txs:w,summary:`${d?`Send ${h} ETH to wrap into WETH. `:""}Supply ${h} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ea(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.loanToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=Me(t),w=h.toString(),y=e.formatAmount(w,m.decimals),k=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(h>k)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${k.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),T=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||T+h>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+h).toString()} exceeds max borrow ${g.toString()} base units.`);let x=$a(h,b.totalBorrowAssets,c.totalBorrowShares),C=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"borrow",args:[u,h,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${w} base units) from Morpho market ${o}.`})],P=await e.preview(C,r),{formattedChanges:I,formattedNetOutflows:E}=xe(e,P);return{action:"morpho_borrow",chainId:f,marketId:o,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:y,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:P,formattedChanges:I,formattedNetOutflows:E}}async function Ga(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f);if(t.shares!==void 0){let I=Le(t.shares);if(I<=0n||I===Ca||I>jt)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(W("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await fe(l,t,!0),[c,m,d]=await Promise.all([Q(l,o.loanToken,f),Te(l,a,n),Zt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let p=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let I=Le(t.shares);if(I>m.borrowShares)throw new i(`Repay shares (${I.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=I}else p=Me(t);let h=b>0n?await Be(l,o,u,Ue):void 0,w=b>0n?se(b,h.totalBorrowAssets,u.totalBorrowShares):p;if(d<w)throw new i(`Insufficient loan token balance for repayment: wallet holds ${d.toString()} base units, but ${w.toString()} base units are required (including accrued interest).`);let y=w.toString(),k=e.formatAmount(y,c.decimals),g=e.approval(o.loanToken,$,y,f),T=e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"repay",args:[o,p,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${c.symbol}) on Morpho market ${a}.`:`Repay ${k} ${c.symbol} (${p.toString()} base units) on Morpho market ${a}.`}),x=[g,T],M=await e.preview(x,r),{formattedChanges:C,formattedNetOutflows:P}=xe(e,M);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,repayAssets:p.toString(),repayShares:b.toString(),requiredAssets:y,...h?{accruedThrough:h.accruedThrough.toString(),borrowRatePerSecond:h.rate.toString(),inclusionSeconds:Ue.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:x,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${c.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${Ue} seconds.`:`Repay ${k} ${c.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:P}}async function Ra(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.collateralToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(h<=0n||h>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${h.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let C=d.collateral-h,P=Ae(C,p,u.lltv),I=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(I>P)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${P.toString()} would fall below current debt ${I.toString()} base units.`)}let w=h.toString(),y=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdrawCollateral",args:[u,h,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${w} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw_collateral",chainId:f,marketId:o,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function _a(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:a,marketState:o}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==me.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let c=Me(t),m=c.toString(),[d,p]=await Promise.all([Q(n,a.loanToken,f),u?Promise.resolve(c):Zt(n,a.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,d.decimals),h=[];u&&h.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${me}.`})),h.push(e.approval(a.loanToken,$,m,f)),h.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supply",args:[a,c,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Ua(c,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(a),loanToken:d,assets:m,formattedAssets:b,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:h,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${d.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ha(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),l=W("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await fe(n,t,!0),[c,m]=await Promise.all([Q(n,o.loanToken,f),Te(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${a}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),b=l?m.supplyShares:0n;if(!l&&p>d)throw new i(`Withdrawal exceeds the lent balance: requested ${p.toString()} base units, position holds about ${d.toString()}. Use withdrawAll for a full exit.`);let h=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>h)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${h.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdraw",args:[o,p,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${c.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,withdrawAssets:p.toString(),withdrawShares:b.toString(),estimatedAssets:w.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${c.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function ea(e,t,s){let r=await e.http(Aa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function ta(e){let t=`query Markets($chainId: Int!) {
2
+ markets(first: 1000, where: { chainId_in: [$chainId] }) {
3
+ items {
4
+ marketId chain { id } lltv listed
5
+ loanAsset { address symbol decimals }
6
+ collateralAsset { address symbol decimals }
7
+ oracle { address } morphoBlue { address } irmAddress
8
+ state { supplyAssets borrowAssets liquidityAssets fee supplyApy borrowApy }
9
+ warnings { type level }
10
+ }
11
+ pageInfo { count countTotal }
12
+ }
13
+ }`;try{let r=(await ea(e,t,{chainId:f})).markets;if(!Array.isArray(r?.items)||typeof r.pageInfo?.countTotal!="number"||r.pageInfo.countTotal!==r.items.length||r.items.some(n=>!n||typeof n.marketId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n.marketId)))throw new i("Morpho GraphQL returned an incomplete or invalid market inventory.");return r.items}catch(s){throw new i(`Morpho GraphQL read failed: ${ie(s)}`)}}async function qa(e,t){return(await ta(e)).find(r=>r.marketId.toLowerCase()===t)??null}async function Fa(e,t){let r=await ea(e,`query Positions($chainId: Int!, $wallet: String!) {
14
+ marketPositions(first: 1000, where: { chainId_in: [$chainId], userAddress_in: [$wallet] }) {
15
+ items { market { marketId } }
16
+ pageInfo { countTotal }
17
+ }
18
+ }`,{chainId:f,wallet:t}),n=r.marketPositions?.items;if(!Array.isArray(n)||r.marketPositions?.pageInfo?.countTotal!==n.length)throw new i("Morpho GraphQL returned an incomplete wallet position list.");return n.map(l=>Qt(l.market?.marketId))}function Ft(e){let t=e;return!t||typeof t.address!="string"||!Fe(t.address,{strict:!1})?null:{address:L(t.address),symbol:Xt(t.symbol),decimals:typeof t.decimals=="number"?t.decimals:null}}function Vt(e){return typeof e=="string"&&Fe(e,{strict:!1})?L(e):null}function zt(e,t){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new i(`Morpho ${t} filter must be a token address or symbol.`);let s=e.trim().toLowerCase();return r=>!!r&&(String(r.address).toLowerCase()===s||typeof r.symbol=="string"&&r.symbol.toLowerCase()===s.replace(/^\$/,""))}async function Va(e,t){if(t.marketId!==void 0||t.marketParams!==void 0||t.includeGraphql!==void 0)throw new i("Use discover without marketId, marketParams or includeGraphql.");let s=t.limit===void 0?20:Number(t.limit);if(!Number.isSafeInteger(s)||s<1||s>100)throw new i("Morpho discover limit must be an integer from 1 to 100.");let r=zt(t.loanToken,"loanToken"),n=zt(t.collateralToken,"collateralToken"),l=W("verifiedOnly",t.verifiedOnly)===!0,a=await ta(e),o=a.map(c=>{let m=c.marketId.toLowerCase(),d=c.state??{},p=Ft(c.loanAsset),b=Ft(c.collateralAsset),h=Array.isArray(c.warnings)?c.warnings.map(w=>({type:String(w?.type??"").slice(0,64),level:String(w?.level??"").slice(0,16)})):[];return{marketId:m,listed:c.listed===!0,warnings:h,loanToken:p,collateralToken:b,lltv:typeof c.lltv=="string"||typeof c.lltv=="number"?String(c.lltv):null,oracle:Vt(c.oracle?.address),irm:Vt(c.irmAddress),state:{supplyAssets:d.supplyAssets===void 0?null:String(d.supplyAssets),borrowAssets:d.borrowAssets===void 0?null:String(d.borrowAssets),liquidityAssets:d.liquidityAssets===void 0?null:String(d.liquidityAssets),supplyApy:typeof d.supplyApy=="number"?d.supplyApy:null,borrowApy:typeof d.borrowApy=="number"?d.borrowApy:null},oak:ct(m)}}).filter(c=>(!l||c.oak.actions==="enabled")&&(!r||r(c.loanToken))&&(!n||n(c.collateralToken))),u=c=>{try{return BigInt(c.state.liquidityAssets??"0")}catch{return 0n}};return o.sort((c,m)=>{let d=+(m.oak.actions==="enabled")-+(c.oak.actions==="enabled");if(d)return d;let p=u(m)-u(c);return p>0n?1:p<0n?-1:0}),{chainId:f,morphoBlue:$,source:"Morpho API market inventory; token symbols, rates and liquidity are indexer data, not chain reads.",totalMatching:o.length,inventoryTotal:a.length,markets:o.slice(0,s),next:'Re-read a market with morpho_status {"marketId":"<id>"} before acting. Only oak.actions "enabled" markets accept Oak transactions.'}}async function za(e,t,s){let r=e.clientFor(f),n=s??t.wallet,l=n&&Fe(n,{strict:!1})?L(n):void 0;if(W("discover",t.discover)===!0)return Va(e,t);for(let c of["loanToken","collateralToken","verifiedOnly","limit"])if(t[c]!==void 0)throw new i(`Morpho ${c} is a discover filter; pass discover:true with it.`);let a=W("includeGraphql",t.includeGraphql)===!0,o=t.marketId||t.marketParams?[t]:Ta.map(c=>({marketId:c})),u=await Promise.all(o.map(async c=>{let{marketId:m,marketParams:d,marketState:p}=await fe(r,c),[b,h,w,y,k,g]=await Promise.all([Q(r,d.loanToken,f),Q(r,d.collateralToken,f),Ke(r,d.oracle),Be(r,d,p),l?Te(r,m,l):Promise.resolve(void 0),a?qa(e,m):Promise.resolve(void 0)]),T=p.totalSupplyAssets>p.totalBorrowAssets?p.totalSupplyAssets-p.totalBorrowAssets:0n,x;if(k){let M=k.borrowShares>0n?se(k.borrowShares,y.totalBorrowAssets,p.totalBorrowShares):0n,C=k.supplyShares>0n?ut(k.supplyShares,p.totalSupplyAssets,p.totalSupplyShares):0n,P=Ae(k.collateral,w,d.lltv),I=M>0n?e.formatAmount((P*Se/M).toString(),18):null;x={supplyShares:k.supplyShares.toString(),supplyAssets:C.toString(),borrowShares:k.borrowShares.toString(),borrowAssets:M.toString(),collateralAssets:k.collateral.toString(),maxBorrowAssets:P.toString(),healthFactor:I}}return{marketId:m,marketParams:pe(d),loanToken:b,collateralToken:h,state:{totalSupplyAssets:p.totalSupplyAssets.toString(),totalSupplyShares:p.totalSupplyShares.toString(),totalBorrowAssets:p.totalBorrowAssets.toString(),totalBorrowShares:p.totalBorrowShares.toString(),availableLiquidity:T.toString(),lastUpdate:p.lastUpdate.toString(),fee:p.fee.toString()},oraclePrice:w.toString(),borrowRatePerSecond:y.rate.toString(),oak:ct(m),...x?{position:x}:{},...a?{graphql:g??null}:{}}}));return{chainId:f,morphoBlue:$,adaptiveCurveIrm:xa,markets:u}}async function Wa(e,t,s,r){let[n,l]=await Promise.all([Yt(t,s),Jt(t,s)]),[a,o,u,c]=await Promise.all([Q(t,n.loanToken,f),Q(t,n.collateralToken,f),Ke(t,n.oracle),Be(t,n,l)]),m=[];r.collateral>0n&&m.push({token:o,amount:r.collateral.toString()});let d=r.supplyShares>0n?ut(r.supplyShares,l.totalSupplyAssets,l.totalSupplyShares):0n;d>0n&&m.push({token:a,amount:d.toString()});let p=r.borrowShares>0n?se(r.borrowShares,c.totalBorrowAssets,l.totalBorrowShares):0n,b=Ae(r.collateral,u,n.lltv),h=e.formatAmount(r.collateral.toString(),o.decimals),w=e.formatAmount(p.toString(),a.decimals);return{module:De,id:s,chainId:f,assets:m,economics:{principal:[...r.collateral>0n?[Je("collateral",{token:o,amount:r.collateral.toString(),source:"morpho.collateral"})]:[],...d>0n?[Je("redeemable",{token:a,amount:d.toString(),source:"morpho.supplyAssets"})]:[]],debt:p>0n?[St({token:a,amount:p.toString(),source:"morpho.borrowAssets"})]:[],rewards:[],backing:[],coverage:{complete:!0}},description:`Morpho Blue market ${s}: collateral=${h} ${o.symbol} (${r.collateral.toString()}), debt=${w} ${a.symbol} (${p.toString()}, shares=${r.borrowShares.toString()}), maxBorrow=${b.toString()}${r.supplyShares>0n?`, lent=${e.formatAmount(d.toString(),a.decimals)} ${a.symbol} (supplyShares=${r.supplyShares.toString()})`:""}.${j(s)?"":" Read-only: not in Oak's verified market registry, so Oak cannot build exits here."}`}}async function ja(e,t){q(t);let s=L(t),r=e.clientFor(f),n=[],l=new Set(lt.map(d=>d.marketId)),a;try{for(let d of await Fa(e,s))l.add(d)}catch(d){a=ie(d)}let o=[...l],u=[],c=[];if(typeof r.multicall=="function")try{let d=await r.multicall({multicallAddress:ft,batchSize:0,allowFailure:!0,contracts:o.map(p=>({address:$,abi:X,functionName:"position",args:[p,s]}))});if(d.length!==o.length)throw new i("Morpho multicall returned an incomplete position list.");d.forEach((p,b)=>{let h=o[b];if(p.status!=="success"){c.push({marketId:h,reason:ie(p.error)});return}let[w,y,k]=p.result;u.push({marketId:h,position:{supplyShares:w,borrowShares:y,collateral:k}})})}catch(d){c.push(...o.map(p=>({marketId:p,reason:ie(d)})))}else for(let d=0;d<o.length;d+=qt)u.push(...await Promise.all(o.slice(d,d+qt).map(async p=>({marketId:p,position:await Te(r,p,s).catch(b=>{c.push({marketId:p,reason:ie(b)})})}))));c.length&&n.push({module:De,id:"morpho-market-reads-incomplete",chainId:f,assets:[],incomplete:!0,description:`Morpho could not read ${c.length} of ${o.length} markets. ${[...new Set(c.map(d=>d.reason))].slice(0,3).join(" ")} Example market IDs: ${c.slice(0,3).map(d=>d.marketId).join(", ")}. Retry positions or check a known market with morpho_status {"marketId":"<id>"}; other readable markets are retained.`});let m=u.filter(d=>d.position!==void 0&&(d.position.supplyShares>0n||d.position.borrowShares>0n||d.position.collateral>0n));for(let{marketId:d,position:p}of m)try{n.push(await Wa(e,r,d,p))}catch(b){let h=j(d)!==void 0;n.push({module:De,id:d,chainId:f,assets:[],incomplete:!0,description:`Unreadable ${h?"verified":"unverified"} Morpho market ${d}: the wallet holds supplyShares=${p.supplyShares.toString()}, borrowShares=${p.borrowShares.toString()}, collateral=${p.collateral.toString()} base units, but its token or oracle reads failed (${ie(b)}). Retry morpho_status {"marketId":"${d}"}.${h?"":" Read-only in Oak."}`})}return a!==void 0&&n.push({module:De,id:"morpho-discovery-unavailable",incomplete:!0,chainId:f,assets:[],description:`Incomplete: Morpho API position discovery failed (${a}). Only Oak's ${lt.length} verified markets were checked on chain; check any other market with morpho_status {"marketId":"<id>"}.`}),n}var ce="Morpho Blue market id: 0x followed by 64 hex digits (bytes32). Provide this or marketParams.",ue="Market parameters object with loanToken, collateralToken, oracle, irm (addresses) and lltv (decimal string, 18 decimals). Provide this or marketId.",ge="Position owner address. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",st="Address receiving the tokens. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",oe=()=>`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,qe=`Amount of the market's collateral token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,Ka=e=>({tools:[{name:"morpho_supply_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(qe),amount:A(qe),collateralToken:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$",description:"Optional collateral token address (0x + 40 hex); must match the market collateral token, or be the native ETH sentinel to wrap."},wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the token supplied is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Oa(e,s,r)},{name:"morpho_withdraw_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(qe),amount:A(qe),withdrawAll:{type:"boolean",description:"true withdraws the full collateral balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ra(e,s,r)},{name:"morpho_borrow",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ea(e,s,r)},{name:"morpho_repay",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),shares:A("Borrow shares to repay, in share base units exactly as your position reports them (not loan-token units). Use instead of assets or amount."),repayAll:{type:"boolean",description:"true repays the entire debt; do not combine with assets, amount or shares."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Ga(e,s,r)},{name:"morpho_supply",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the market loan token is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>_a(e,s,r)},{name:"morpho_withdraw",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),withdrawAll:{type:"boolean",description:"true withdraws the full supplied balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ha(e,s,r)},{name:"morpho_status",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},includeGraphql:{type:"boolean",description:"true also fetches Morpho API (GraphQL) market data alongside on-chain reads."},discover:{type:"boolean",description:"List the Morpho API market inventory with Oak action eligibility instead of reading markets on chain."},loanToken:{type:"string",description:"discover filter: loan token address or symbol."},collateralToken:{type:"string",description:"discover filter: collateral token address or symbol."},verifiedOnly:{type:"boolean",description:"discover filter: only markets Oak can act on."},limit:{type:"integer",minimum:1,maximum:100,description:"discover page size, default 20."}}},execute:(s,r)=>za(e,s,r)}].map(s=>{let r=new Set(Object.keys(s.inputSchema.properties));if(r.add("wallet"),s.name!=="morpho_status")for(let l of["onBehalf","receiver","data"])r.add(l);let n=new Set(["loanToken","collateralToken","oracle","irm","lltv"]);return{...s,execute:async(l,a)=>{for(let o of Object.keys(l))if(!r.has(o))throw new i(`Unknown argument ${Ye(o)} for ${s.name}; remove it and retry.`);if(l.marketParams&&typeof l.marketParams=="object"){for(let o of Object.keys(l.marketParams))if(!n.has(o))throw new i(`Unknown Morpho marketParams field ${Ye(o)}; remove it and retry.`)}return s.execute(l,a)}}}),positions:s=>ja(e,s)}),Ko=e=>bt(De,[Ka(e),Tt(e),Wt(e),Ht(e),$t(e)]);var _=z[f].morpho.morpho_blue.address,Pe="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",O=pt(["function owner() view returns (address)","function feeRecipient() view returns (address)","function isIrmEnabled(address) view returns (bool)","function isLltvEnabled(uint256) view returns (bool)","function isAuthorized(address,address) view returns (bool)","function nonce(address) view returns (uint256)",`function idToMarketParams(bytes32) view returns ${Pe}`,"function market(bytes32) view returns (uint128,uint128,uint128,uint128,uint128,uint128)","function position(bytes32,address) view returns (uint256 supplyShares,uint128 borrowShares,uint128 collateral)",`function createMarket(${Pe} marketParams)`,`function accrueInterest(${Pe} marketParams)`,`function setFee(${Pe} marketParams,uint256 newFee)`,"function setAuthorization(address authorized,bool newIsAuthorized)","function setOwner(address newOwner)","function setFeeRecipient(address newFeeRecipient)","function enableIrm(address irm)","function enableLltv(uint256 lltv)",`function liquidate(${Pe} marketParams,address borrower,uint256 seizedAssets,uint256 repaidShares,bytes data) returns (uint256,uint256)`]),Ya=pt(["function price() view returns (uint256)"]),Ja=pt([`function borrowRateView(${Pe} marketParams,(uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee) market) view returns (uint256)`]),oa=["createMarket","accrueInterest","setAuthorization","setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"],Za=new Set(["setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"]);function Ne(e){if(typeof e!="string"||!/^\d+$/.test(e)||e.length>78||BigInt(e)>=1n<<256n)throw new i("Provide a uint256 decimal base-unit string.");return BigInt(e)}function mt(e){return Ee(e,"Provide an explicit account address.",Oe)}var Wt=e=>{async function t(){let n=e.clientFor(f);if(await n.getChainId()!==f)throw new i("Morpho protocol tools require chain 4663.");return n}async function s(n){if(typeof n!="string"||!j(n))throw new i("Choose a market in Oak\u2019s verified registry.");let l=await t(),a=await l.readContract({address:_,abi:O,functionName:"idToMarketParams",args:[n]}),o={loanToken:a[0],collateralToken:a[1],oracle:a[2],irm:a[3],lltv:a[4]};if(!R(ke({...o,lltv:o.lltv.toString()}),n))throw new i("On-chain Morpho parameters do not match the selected market.");return{rpc:l,params:o,marketId:n}}let r=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Morpho protocol argument.");return await o(u,c)}catch(m){throw new i(e.plainError(m))}}});return{tools:[r("morpho_protocol",{authorized:{type:"string",description:"Optional address to check whether it is authorized to manage the Oak wallet's Morpho positions."}},[],async(n,l)=>{let a=await t(),[o,u,c]=await Promise.all([a.readContract({address:_,abi:O,functionName:"owner"}),a.readContract({address:_,abi:O,functionName:"feeRecipient"}),a.readContract({address:_,abi:O,functionName:"nonce",args:[l]})]),m=n.authorized===void 0?void 0:mt(n.authorized);return{chainId:f,morpho:_,owner:o,feeRecipient:u,nonce:c.toString(),...m?{authorized:m,isAuthorized:await a.readContract({address:_,abi:O,functionName:"isAuthorized",args:[l,m]})}:{}}}),r("morpho_manage",{operation:{enum:oa,description:"Protocol action: createMarket, accrueInterest, setAuthorization, setOwner, setFeeRecipient, enableIrm, enableLltv or setFee. Owner-only except accrueInterest, setAuthorization and createMarket."},marketId:{type:"string",description:"Verified market id (0x + 64 hex digits). Used by accrueInterest and setFee."},marketParams:{type:"object",description:"For createMarket only: loanToken, collateralToken, oracle, irm addresses and lltv as a decimal string (18 decimals)."},account:{type:"string",description:"Address argument: authorized account for setAuthorization, new owner, new fee recipient, or IRM to enable."},enabled:{type:"boolean",description:"For setAuthorization: true grants the account control of all your Morpho positions, false revokes it."},value:A("18-decimal wad in base units: for setFee the fee (max 0.25e18 = 25 percent), for enableLltv the LLTV (below 1e18; 0.8e18 = 80 percent).")},["operation"],async(n,l)=>{if(typeof n.operation!="string"||!oa.includes(n.operation))throw new i("Choose a documented Morpho protocol operation.");let a=n.operation,o=await t(),u=a==="createMarket"?["operation","marketParams"]:a==="accrueInterest"?["operation","marketId"]:a==="setFee"?["operation","marketId","value"]:a==="enableLltv"?["operation","value"]:a==="setAuthorization"?["operation","account","enabled"]:["operation","account"];if(Object.keys(n).some(p=>!u.includes(p)))throw new i("Unexpected fields for this Morpho operation.");if(Za.has(a)){let p=await o.readContract({address:_,abi:O,functionName:"owner"});if(aa(p)!==aa(l))throw new i("This wallet does not hold the Morpho owner role.")}let c;if(a==="createMarket"){if(!n.marketParams||typeof n.marketParams!="object"||Array.isArray(n.marketParams)||Object.keys(n.marketParams).some(w=>!["loanToken","collateralToken","oracle","irm","lltv"].includes(w)))throw new i("Provide only the five documented market parameter fields.");let p=je(n.marketParams),[b,h]=await Promise.all([o.readContract({address:_,abi:O,functionName:"isIrmEnabled",args:[p.irm]}),o.readContract({address:_,abi:O,functionName:"isLltvEnabled",args:[p.lltv]})]);if(!b||!h)throw new i("The new market\u2019s IRM and LLTV must first be enabled by the Morpho owner.");c=be({abi:O,functionName:"createMarket",args:[p]})}else if(a==="accrueInterest"||a==="setFee"){let{params:p}=await s(n.marketId);if(a==="setFee"){let b=Ne(n.value);if(b>250000000000000000n)throw new i("Morpho market fee cannot exceed 25% (0.25e18).");c=be({abi:O,functionName:"setFee",args:[p,b]})}else c=be({abi:O,functionName:"accrueInterest",args:[p]})}else if(a==="enableLltv"){let p=Ne(n.value);if(p>=10n**18n)throw new i("Morpho LLTV must be below 1e18.");c=be({abi:O,functionName:"enableLltv",args:[p]})}else{let p=mt(n.account);if(a==="setAuthorization"){if(typeof n.enabled!="boolean")throw new i("Provide enabled as a boolean.");c=be({abi:O,functionName:"setAuthorization",args:[p,n.enabled]})}else if(a==="setOwner"||a==="enableIrm"||a==="setFeeRecipient")c=be({abi:O,functionName:a,args:[p]});else throw new i("Unsupported Morpho operation.")}let m=`Morpho ${a}: ${JSON.stringify(n)}. ${a==="setAuthorization"&&n.enabled?"This account can manage all your Morpho positions, including borrowing and withdrawals. There is no amount cap.":""}${a==="setOwner"&&n.account===Xa?"Setting the owner to zero permanently relinquishes protocol administration.":""}${a==="createMarket"?"New market creation does not add it to Oak\u2019s verified action registry.":""}`,d=[e.unsignedTx({to:_,data:c,value:"0",chainId:f,description:m})];return{txs:d,preview:await e.preview(d,l),summary:m}}),r("morpho_liquidate",{marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits) holding the unhealthy position."},borrower:{type:"string",description:"Address of the unhealthy borrower to liquidate."},repaidShares:A("Borrow shares to repay, in share base units (read the borrower position); cannot exceed their debt shares."),maxAssets:A('Most loan token you will pay, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minCollateral:A("Least collateral you must receive, in collateral token units (base units, read its decimals); checked in simulation only.")},["marketId","borrower","repaidShares","maxAssets","minCollateral"],async(n,l)=>{let{rpc:a,params:o,marketId:u}=await s(n.marketId),c=mt(n.borrower),m=Ne(n.repaidShares),d=Ne(n.maxAssets),p=Ne(n.minCollateral),[b,h,w,y]=await Promise.all([a.readContract({address:_,abi:O,functionName:"market",args:[u]}),a.readContract({address:_,abi:O,functionName:"position",args:[u,c]}),a.readContract({address:o.oracle,abi:Ya,functionName:"price"}),a.getBlock()]);if(m===0n||m>h[1]||w===0n)throw new i("Liquidation shares must fit the current debt and the oracle must be valid.");let k={totalSupplyAssets:b[0],totalSupplyShares:b[1],totalBorrowAssets:b[2],totalBorrowShares:b[3],lastUpdate:b[4],fee:b[5]},g=await a.readContract({address:o.irm,abi:Ja,functionName:"borrowRateView",args:[o,k]}),T=Qe(k,g,y.timestamp);if(se(h[1],T,b[3])<=Ae(h[2],w,o.lltv))throw new i("This borrower is healthy; liquidation is unavailable.");let x=se(m,Qe(k,g,y.timestamp+120n),b[3]);if(x>d)throw new i("Liquidation funding exceeds maxAssets.");if(await a.readContract({address:o.loanToken,abi:Qa,functionName:"balanceOf",args:[l]})<x)throw new i("Top up the loan token before liquidating.");let C=`Liquidate ${m} debt shares of ${c} on ${u}; exact approval ${x} loan-token base units; preview minimum ${p} collateral units. No callbacks; the wallet funds repayment. Approval can leave interest-buffer dust; revoke it afterward.`,P=[e.approval(o.loanToken,_,x.toString(),f),e.unsignedTx({to:_,data:be({abi:O,functionName:"liquidate",args:[o,c,0n,m,"0x"]}),value:"0",chainId:f,description:C})],I=await e.preview(P,l),E=Z=>I.changes.filter(H=>H.token.chainId===f&&R(H.token.address,Z)).reduce((H,F)=>H+BigInt(F.amount),0n);if(-E(o.loanToken)<=0n||-E(o.loanToken)>x||E(o.collateralToken)<p||E(o.collateralToken)<=0n)throw new i("Liquidation preview does not match the funding limit and collateral minimum.");return{txs:P,preview:I,requiredAssets:x.toString(),summary:`${C} MinCollateral is a local simulation check, not an on-chain floor.`}})]}};export{O as a,Wt as b,we as c,$t as d,Y as e,ha as f,Ot as g,wa as h,Et as i,ka as j,Ht as k,De as l,Aa as m,$ as n,xa as o,Ia as p,me as q,Ta as r,Ma as s,lt as t,j as u,Ue as v,Ua as w,$a as x,ut as y,se as z,Ae as A,Ba as B,je as C,ke as D,Xt as E,Qe as F,Ka as G,Ko as H,et as I,vt as J,N as K,io as L};
@@ -0,0 +1,70 @@
1
+ import{a as ct}from"./63YRSLDK.js";var St={};ct(St,{ACCESS_FEE_LINE:()=>H,ACCESS_FREE_UNTIL_LINE:()=>K,ACCESS_NO_PLAN:()=>T,BANNED_COPY:()=>Nt,BONUS_CLAUSE:()=>l,CARD_FOOTER_ASK:()=>m,CARD_FOOTER_NO_ASK:()=>k,CARD_HEADER:()=>s,CARD_HEADER_AMOUNT:()=>r,CARD_HEADER_AMOUNT_NOT_HELD:()=>i,ETH_HINT:()=>f,FEES_ESTIMATED_HIGH:()=>W,LAYERBANK_RISK_SUMMARY:()=>u,LAYERBANK_SETUP_MISMATCH:()=>_t,LAYERBANK_SITE:()=>wt,LB_BONUS_NOTE:()=>S,LB_CASH_NOTE:()=>L,LB_DEPOSIT_SCREEN:()=>x,LB_WITHDRAW_SCREEN:()=>N,LP_ADD_BUTTON:()=>bt,LP_BLOCK:()=>X,LP_BLOCK_UNREADABLE:()=>at,LP_DECLINE_BUTTON:()=>Tt,LP_FEE_CLAUSE:()=>Z,LP_FUNDER_LINE:()=>et,LP_GAS_LINE:()=>Q,LP_NOT_A_PROMISE:()=>tt,LP_NOT_WORTH_CLAUSE:()=>ot,LP_RANGE_CLAUSE:()=>V,LP_RATE_LINE:()=>j,LP_SHARE_LINE:()=>J,MATURED_NOTICE:()=>F,MATURED_STOCK_NOTICE:()=>z,MATURED_STOCK_NOTICE_NO_AMOUNT:()=>q,MERKL_AFTER_DEPOSIT:()=>nt,MERKL_EARNING_EMPTY:()=>rt,MERKL_LAST_UPDATE_CLAUSE:()=>st,NOTHING_TO_EARN:()=>b,NO_NEW_TERM:()=>$,OPTION_A:()=>h,OPTION_A_CANT_CHECK:()=>y,OPTION_A_CLOSED:()=>g,OPTION_A_NO_ROOM:()=>E,OPTION_B:()=>c,OPTION_B_CANT_CHECK:()=>w,OPTION_B_NONE:()=>p,PAYOUT_APPROX:()=>v,PAYOUT_EXACT:()=>U,PENDLE_BUY_STABLE_SCREEN:()=>A,PENDLE_BUY_STOCK_SCREEN:()=>O,PENDLE_CONTRACT_CHANGE:()=>mt,PENDLE_EARLY_EXIT:()=>_,PENDLE_FIXED_RATE:()=>Et,PENDLE_REDEEM_SCREEN:()=>C,PENDLE_REDEEM_STOCK_SCREEN:()=>I,PENDLE_RISK_SUMMARY:()=>d,PENDLE_SELL_DEFAULT_BUTTON:()=>kt,PENDLE_SELL_GAP_LINE:()=>D,PENDLE_SELL_NO_GAP_LINE:()=>R,PENDLE_SELL_SCREEN:()=>P,PENDLE_SERVICE_DOWN:()=>ht,PENDLE_SITE:()=>gt,PRICE_MISMATCH_REFUSAL:()=>dt,SLIPPAGE_CAP_REFUSAL:()=>it,STOCK_PAID_IN:()=>Y,STOCK_SHORT_TERM:()=>B,STOCK_SHORT_TERM_DAYS:()=>ft,TEMPLATES:()=>xt,THIN_MARKET_REFUSAL:()=>ut,TOO_SMALL:()=>M,TOO_SMALL_NO_SIZE:()=>G,fill:()=>yt,placeholdersOf:()=>pt});function t(e){return{text:e}}function pt(e){return[...new Set([...e.text.matchAll(/\{([a-z][a-z0-9_]*)\}/g)].map(o=>o[1]))]}function yt(e,o){let lt=o;return e.text.replace(/\{([a-z][a-z0-9_]*)\}/g,(Lt,a)=>{let n=lt[a];if(typeof n!="string")throw new Error(`Missing value for {${a}}`);return n})}var wt="layerbank.finance",gt="app.pendle.finance",s=t("You have {amount_usd} in USDG that isn't earning anything. Here are two ways to make it earn. Pick one, or neither."),r=t("Looking at {amount_usd} of your USDG. Here are two ways to make it earn. Pick one, or neither."),i=t("Looking at {amount_usd} of USDG. Here are two ways to make it earn. Pick one, or neither."),u="LayerBank is a lending app; if its code fails or almost everything is lent out, you could lose money or have to wait.",d="Pendle is a trading app; thin trading can make leaving early cost you, and its code can fail or be changed by its team.",_="If you leave early you sell at the market price that day, and that can be less than you put in.",Et="The rate is fixed only if you hold until the end date.",mt="Pendle's router can be upgraded by Pendle's team, so its code can change.",h=t(`A. LayerBank: lending, take it out any time
2
+ Pays about {lb_base_rate}% a year from borrowers today{bonus_clause}. The rate changes, up or down.
3
+ You can take your money out any time while LayerBank has cash on hand (right now {lb_cash_usd}).
4
+ Risk: ${u}
5
+ Cost: network fees of about {lb_gas_in_usd} to put it in and {lb_gas_out_usd} to take it out.`),l=t(", plus a bonus of {lb_bonus_rate}% a year for the next {bonus_days}. After that I count only the {lb_base_rate}%, because Oak can't see whether the bonus will be renewed"),c=t(`B. Pendle: a fixed rate until {pendle_end_date}
6
+ Pays a fixed {pendle_rate}% a year if you keep it until {pendle_end_date}. You get {pendle_payout_usd} back for every {pendle_unit_usd} you put in.
7
+ ${_}
8
+ Risk: ${d}
9
+ Cost: about {pendle_cost_in_usd} in fees to start and about {pendle_gas_out_usd} to cash out.`),p=t("B. Pendle has no fixed-rate USDG term open right now."),y=t("A. LayerBank can't be checked right now, so I won't offer it."),w=t("B. Pendle can't be checked right now, so I won't offer it."),g=t("A. LayerBank isn't taking new deposits right now, so I won't offer it."),E=t("A. LayerBank can only take {cap_room_usd} more right now, which is less than {amount_usd}, so I won't offer it."),m=t("Nobody guarantees either one. Which do you want: {choices}?"),k=t("Nobody guarantees either one."),f=t("You hold ETH but no USDG. I can swap some ETH to USDG first with Oak's swap tool and show you the price before anything happens."),b=t("This wallet holds no USDG and no ETH to put to work, so there is nothing to compare yet."),T=t("Putting money in or taking it out through Oak needs an active Oak plan ({plan_price}). Taking it out on {project_site} always works too, with this same wallet."),x=t(`Put {amount_usd} into LayerBank?
10
+
11
+ What you get: about {lb_total_rate}% a year at today's rate. The rate changes.
12
+ What happens: {amount_usd} of USDG leaves your wallet and becomes {amount_usd} of "lRobUSDG", your receipt for money lent through LayerBank. Your receipt grows as interest arrives. Oak's preview checks the amount, but the contract doesn't enforce a minimum, so it can differ slightly.
13
+ The risk: LayerBank is a lending app. If its code fails, or almost everything is lent out, you could lose money or have to wait to get it back.
14
+ Taking it out: any time LayerBank has cash on hand. Right now that is {lb_cash_usd}. You can also take it out on layerbank.finance with this wallet.
15
+ Cost: about {gas_usd} in network fees now and about {gas_out_usd} to take it out.
16
+
17
+ Put in {amount_usd}? [Yes] [No]`),N=t(`Take {amount_or_all} out of LayerBank?
18
+
19
+ You get back {usdg_out} USDG (your {amount_deposited_clause} plus interest so far{bonus_note}). Oak's preview checks the amount, but the contract doesn't enforce a minimum, so it can differ slightly.
20
+ {cash_note}
21
+ Cost: about {gas_usd} in network fees.
22
+
23
+ Take it out? [Yes] [No]`),S=t(". Your bonus is paid separately; ask me to claim it"),L=t("LayerBank only has {lb_cash_usd} on hand right now, so I can take out {max_now} today."),A=t(`Lock {amount_usd} in a fixed rate until {pendle_end_date}?
24
+
25
+ What you get: a fixed {pendle_rate}% a year, if you keep it until {pendle_end_date}. You put in {amount_usd} and get {pt_out} tokens. Each token pays out {payout_per_pt_phrase} on {pendle_end_date}. That is about {gain_usd} more than you put in.
26
+ What happens now: {amount_usd} of USDG leaves your wallet and you receive at least {pt_min} "PT-USDG" tokens (the price can move a little before this goes through; Oak refuses anything worse than {slippage_pct}%).
27
+ The risk: if you leave before {pendle_end_date}, you sell at the market price that day, and that can be less than you put in. Pendle is a trading app; its code can fail, and its team can change it.
28
+ Cost: about {fees_usd} in trading and network fees now, and about {gas_out_usd} to cash out at the end.
29
+
30
+ Lock {amount_usd} until {pendle_end_date}? [Yes] [No]`),O=t(`Lock {amount_units} {stock_symbol} in a fixed rate until {pendle_end_date}?
31
+
32
+ What you get: you put in {amount_units} {stock_symbol} and receive at least {pt_min} tokens. On {pendle_end_date} each token pays out {payout_per_pt_phrase}. That is {gain_units} {stock_symbol} more than you put in, a fixed {pendle_rate}% a year in {stock_symbol}, not in dollars.
33
+ The catch: the payout is in {stock_symbol}, not dollars. If the stock token is worth less on {pendle_end_date}, you get less in dollars, even though the {stock_symbol} count is fixed.
34
+ The risk: leaving early sells at the market price that day, which can be less than you put in. This term is short ({days_left} days), so the extra {stock_symbol} is small. Pendle is a trading app; its code can fail, and its team can change it.
35
+ Cost: about {fees_usd} in trading and network fees now and about {gas_out_usd} to cash out.
36
+
37
+ Lock it until {pendle_end_date}? [Yes] [No]`),P=t(`Leave early and sell {pt_amount} tokens now?
38
+
39
+ If you wait until {pendle_end_date}, these tokens pay {payout_at_end} {unit}.
40
+ If you sell now, the market pays about {sell_now} {unit}, and Oak accepts no less than {sell_min}. {gap_line}
41
+ Selling early can lose money. The price today may be lower than what you paid.
42
+ Cost: about {fees_usd} in trading and network fees.
43
+
44
+ Sell now? [Yes, sell now] [No, keep waiting]`),D=t("That is {gap} less than waiting."),R=t("The quoted output before fees is at least the payout at the end of the term. Fees, the minimum output and what you paid still affect whether you lose money."),kt="No, keep waiting",C=t(`Cash out {pt_amount} tokens for {usdg_out} USDG?
45
+
46
+ The term ended on {pendle_end_date}. Each token pays out {payout_per_pt_phrase} now, with no market price involved.
47
+ Cost: about {gas_usd} in network fees.
48
+
49
+ Cash out? [Yes] [No]`),I=t(`Cash out {pt_amount} tokens for about {unit_out} {stock_symbol}?
50
+
51
+ The term ended on {pendle_end_date}. You receive {stock_symbol}, not USDG: about {unit_out} {stock_symbol}, worth about {value_usd} at today's price, which can move. No market price is involved in the payout itself.
52
+ To end up in USDG, I can swap the {stock_symbol} afterwards with Oak's swap tool and show you that price first.
53
+ Cost: about {gas_usd} in network fees.
54
+
55
+ Cash out? [Yes] [No]`),U=t("exactly 1 {unit}"),v=t("about {x} {unit} at today's exchange rate"),Y=t("Paid in {stock_symbol}, not dollars."),B=t("ends in {days_left} days, usually too short to be worth the fees"),ft=7,M=t("At {amount_usd}, this is too small to be worth it. You would earn about {gross_usd} over {horizon}, and fees would take about {costs_usd}, leaving about {net_usd}. Putting in {suggest_usd} or more would be worth it, and I can still do it if you want."),G=t("At {amount_usd}, this is too small to be worth it. You would earn about {gross_usd} over {horizon}, and fees would take about {costs_usd}, leaving about {net_usd}. At today's rate no amount would make up for the fees, and I can still do it if you want."),H=t("Also: Oak access costs {plan_price} per 30 days, which you pay whether or not you earn. At this size that is more than you would earn in a month."),K=t("Oak access is free for you until {free_until}. After that it costs {plan_price} per 30 days, which you pay whether or not you earn, and at this size that is more than you would earn in a month."),W=t("Fees estimated high because the live price was unavailable."),F=t(`Your fixed term on Pendle ended on {pendle_end_date}. Your {pt_amount} tokens are worth {usdg_out} USDG now.
56
+ Want me to cash out to USDG, or start a new term? One "yes" is enough; say "cash out" or "new term".`),z=t('Your fixed term on Pendle ended on {pendle_end_date}. Your {pt_amount} tokens pay out about {unit_out} {stock_symbol} now, worth about {value_usd}. Want me to cash out and swap that to USDG, or start a new term? One "yes" is enough.'),q=t('Your fixed term on Pendle in {stock_symbol} ended on {pendle_end_date}. Your tokens pay out in {stock_symbol}, not USDG; I will show the exact amount before anything is sent. Want me to cash out and swap that to USDG, or start a new term? One "yes" is enough.'),$=t("There is no new fixed-rate USDG term open right now. I cashed out to USDG; want me to show LayerBank instead?"),X=t(`Before you add liquidity: what it is worth, and what can go wrong
57
+
58
+ Worth: {worth_line}
59
+ {funder_line}What can go wrong:
60
+ - Price exposure: you put in two coins. If one moves a lot against the other, you can end up with less than you started with, even if you earn rewards.
61
+ - Going out of range: if the price leaves the range you chose, you stop earning until it comes back, and you hold mostly the weaker coin.
62
+ - The rewards can end: the campaign ends on {end_date}, or sooner, and the rate shown is today's rate, which changes.
63
+ Your call. [Add liquidity] [Don't]`),j=t("Merkl lists this pool's reward rate at about {apr}% a year until {end_date}. That rate is an average over everyone in the pool."),V=t("Rewards count only while the price stays inside your range."),Z=t("They are weighted {w}% by the trading fees your position earns, so your share can be lower."),J=t("For your {amount_usd}, at that average rate: about {per_day_usd} a day, about {gross_usd} until {end_date}."),Q=t("Network fees to join and leave are about {gas_usd}."),tt=t("Rates change; this is not a promise."),et=t("Uniswap pays the trading fees; Merkl runs the bonus, funded by {creator}. Oak can't identify who that is."),ot=t("That is not worth it at this size."),at=t(`Before you add liquidity: what it is worth, and what can go wrong
64
+
65
+ Worth: the reward rate or end date couldn't be read, so I can't tell you what this is worth.
66
+ What can go wrong:
67
+ - Price exposure: you put in two coins. If one moves a lot against the other, you can end up with less than you started with, even if you earn rewards.
68
+ - Going out of range: if the price leaves the range you chose, you stop earning until it comes back, and you hold mostly the weaker coin.
69
+ - The rewards can end: a campaign can end at any time, and any rate shown is the rate of that day, which changes.
70
+ Your call. If you say nothing, the answer is Don't. [Don't] [Add liquidity]`),bt="Add liquidity",Tt="Don't",nt=t("Your position is in the pool. Merkl adds new positions to its reward list after a delay, and rewards become claimable only after Merkl's next reward update{last_update_clause}. An empty list right after a deposit is normal; check again later."),st=t(": the last one was at {time} UTC"),rt=t("Merkl lists no earning positions for this wallet right now. If you just added liquidity: {after_deposit}"),it=t("Oak won't accept a price move that big. The most it allows is {cap_pct}%."),ut=t("This is a thin market and your size moves the price too much. Try a smaller amount."),dt=t("Pendle's price doesn't match what Oak checked on the chain. Nothing was signed."),_t=t("LayerBank's setup no longer matches what Oak checked. Nothing was signed."),ht=t("Pendle's price service isn't answering, so I can't quote or start a new term; I can still cash out ended terms."),xt={CARD_HEADER:s,CARD_HEADER_AMOUNT:r,CARD_HEADER_AMOUNT_NOT_HELD:i,OPTION_A:h,BONUS_CLAUSE:l,OPTION_B:c,OPTION_B_NONE:p,OPTION_A_CANT_CHECK:y,OPTION_B_CANT_CHECK:w,OPTION_A_CLOSED:g,OPTION_A_NO_ROOM:E,CARD_FOOTER_ASK:m,CARD_FOOTER_NO_ASK:k,ETH_HINT:f,NOTHING_TO_EARN:b,ACCESS_NO_PLAN:T,LB_DEPOSIT_SCREEN:x,LB_WITHDRAW_SCREEN:N,LB_BONUS_NOTE:S,LB_CASH_NOTE:L,PENDLE_BUY_STABLE_SCREEN:A,PENDLE_BUY_STOCK_SCREEN:O,PENDLE_SELL_SCREEN:P,PENDLE_SELL_GAP_LINE:D,PENDLE_SELL_NO_GAP_LINE:R,PENDLE_REDEEM_SCREEN:C,PENDLE_REDEEM_STOCK_SCREEN:I,PAYOUT_EXACT:U,PAYOUT_APPROX:v,STOCK_PAID_IN:Y,STOCK_SHORT_TERM:B,TOO_SMALL:M,TOO_SMALL_NO_SIZE:G,ACCESS_FEE_LINE:H,ACCESS_FREE_UNTIL_LINE:K,FEES_ESTIMATED_HIGH:W,MATURED_NOTICE:F,MATURED_STOCK_NOTICE:z,MATURED_STOCK_NOTICE_NO_AMOUNT:q,NO_NEW_TERM:$,LP_BLOCK:X,LP_RATE_LINE:j,LP_RANGE_CLAUSE:V,LP_FEE_CLAUSE:Z,LP_SHARE_LINE:J,LP_GAS_LINE:Q,LP_NOT_A_PROMISE:tt,LP_FUNDER_LINE:et,LP_NOT_WORTH_CLAUSE:ot,LP_BLOCK_UNREADABLE:at,MERKL_AFTER_DEPOSIT:nt,MERKL_LAST_UPDATE_CLAUSE:st,MERKL_EARNING_EMPTY:rt,SLIPPAGE_CAP_REFUSAL:it,THIN_MARKET_REFUSAL:ut,PRICE_MISMATCH_REFUSAL:dt,LAYERBANK_SETUP_MISMATCH:_t,PENDLE_SERVICE_DOWN:ht},Nt=[/\bsafe(ly|ty)?\b/i,/\bguaranteed\b/i,/\brisk-free\b/i,/\bpassive\b/i,/\binvest/i,/\bAPY\b(?! a year)/];export{pt as a,yt as b,wt as c,gt as d,s as e,r as f,i as g,u as h,d as i,_ as j,Et as k,mt as l,h as m,l as n,c as o,p,y as q,w as r,g as s,E as t,m as u,k as v,f as w,b as x,T as y,x as z,N as A,S as B,L as C,A as D,O as E,P as F,D as G,R as H,kt as I,C as J,I as K,U as L,v as M,Y as N,B as O,ft as P,M as Q,G as R,H as S,K as T,W as U,F as V,z as W,q as X,$ as Y,X as Z,j as _,V as $,Z as aa,J as ba,Q as ca,tt as da,et as ea,ot as fa,at as ga,bt as ha,Tt as ia,nt as ja,st as ka,rt as la,it as ma,ut as na,dt as oa,_t as pa,ht as qa,xt as ra,Nt as sa,St as ta};
@@ -0,0 +1 @@
1
+ function c(r,t){return r==="hoodlock_airdrop_claim"&&!Object.hasOwn(t,"id")}var h=new Map([]),_="find_tool",l="run_tool",i=["oak_setup","oak_identity_unlink","oak_subscribe","oak_renew","oak_redeem","send","hoodlock_feature_buy","hoodlock_feature_claim","hoodlock_referral_register","heyresearch_token_facts","heyresearch_feed","heyresearch_follow","heyresearch_unfollow","heyresearch_position_context"],p={oak:["account","balances","find_token","price","quote","swap","positions","send","oak_setup","oak_subscribe","oak_renew","oak_identity_unlink","oak_redeem"],kyberswap:[],velora:[],steakhouse:["steakhouse_deposit","steakhouse_withdraw"],spark:["spark_deposit","spark_withdraw"],layerbank:["layerbank_deposit","layerbank_withdraw"],borro:["borro_deposit","borro_withdraw"],chop:["chop_wrap","chop_unwrap"],factor:["factor_sign_up","factor_open_jobs"],raeto:["raeto_status","raeto_join","raeto_ask"],gloam:["gloam_shield","gloam_pay","gloam_claim","gloam_cash_out"],pendle:["pendle_buy","pendle_sell","pendle_redeem"],earn:["earn_options"],netnet:["netnet_deposit","netnet_withdraw"],longbow:["longbow_list","longbow_deposit","longbow_withdraw"],grove:["grove_deposit","grove_withdraw"],beefy:["beefy_list","beefy_deposit","beefy_withdraw"],pons:["pons_browse","pons_buy","pons_sell","pons_launch"],orbio:["orbio_credit_status","orbio_buy_credit"],hoodlock:["hoodlock_list_locks","hoodlock_lock","hoodlock_withdraw"],merkl:["merkl_rewards","merkl_claim"],relay:["relay_bridge_in","relay_bridge_out","relay_status"],lighter:["lighter_funding"],wormhole:[],erc8004:["erc8004_identity"],hoodag:["hoodag_resolve","hoodag_register"],heyresearch:["heyresearch_research_project","heyresearch_token_facts","heyresearch_feed","heyresearch_follow","heyresearch_position_context"],priors:["priors_status","priors_lend","priors_withdraw","priors_borrow","priors_repay"],morpho:["morpho_status","morpho_supply","morpho_withdraw","morpho_supply_collateral","morpho_withdraw_collateral","morpho_borrow","morpho_repay"],uniswap:["uniswap_list_positions","uniswap_add","uniswap_remove","uniswap_collect"],hookr:["hookr_orders","hookr_create","hookr_cancel"],meridian:["meridian_browse","meridian_positions","meridian_sell","meridian_redeem"],tickerspring:["tickerspring_account","tickerspring_create","tickerspring_cancel","tickerspring_claim"],clanker:["clanker_browse","clanker_launch"],poolstrade:["poolstrade_status","poolstrade_buy","poolstrade_sell","poolstrade_launch"]};function w(r,t){let a=new Set(r),s=new Set;for(let[e,n]of Object.entries(p))for(let o of n){if(s.has(o))throw new Error(`Visible tool ${o} is listed twice.`);if(e!=="oak"&&!o.startsWith(`${e}_`))throw new Error(`Visible tool ${o} is filed under ${e}.`);if(i.includes(o)||a.has(o))s.add(o);else if(t==="mainnet")throw new Error(`Visible tool ${o} is not registered.`)}for(let e of[_,l,...i,"oak_playbook"])if(a.has(e))throw new Error(`Tool name ${e} is reserved for the add-on.`);return s}export{c as a,h as b,_ as c,l as d,i as e,p as f,w as g};
@@ -0,0 +1,3 @@
1
+ import{c as O,e as T,i as M,j as x,k as V,m as D,n as N}from"./PZEF5LBL.js";import{a as b,b as h,c as R,e as f,f as A,g as k,h as P,i as I,j as v,l as S,m as B,n as $}from"./CSOO4SW7.js";import{a as y}from"./I6PQW2JI.js";import{a as E}from"./K6D6SDIG.js";import{a as c}from"./XSD5NL7J.js";import{encodeFunctionData as j,formatUnits as z}from"viem";var m=(o,e)=>({token:o,amount:e.toString()}),J=6e4;function ie(){let o=new WeakMap;return{entry(e){let r=o.get(e);return(!r||Date.now()>=r.expiresAt)&&(r={logs:new Map,expiresAt:Date.now()+J},o.set(e,r)),r}}}function K(o,e){return{to:o.log.address,data:j({abi:E,functionName:"debond",args:[e,[],[]]}),value:"0",chainId:4663,description:`Unwrap ${e} log base units from ${o.log.address}.`}}async function _(o,e,r,a,t=BigInt(e.measuredAtBlock),s){if(a>BigInt(e.totalSupply))throw new c("Unwrap amount exceeds the issued Chop log supply.");let i=h(await A(o,e.log.address,"convertToAssets",[a],t,r,s)),p=1n<<96n,d=BigInt(e.managedUnderlying)*(a*p/BigInt(e.totalSupply))/p;if(i>d)throw new c("Chop redemption exceeds the measured backing.");return{gross:m(e.underlying,d),fee:m(e.underlying,d-i),net:m(e.underlying,i)}}async function F(o,e){if(f(e),o.network==="testnet")throw new c("Chop requires chain 4663.");let r=o.clientFor(4663),a=await P(r,e),t=I();await v(r,y.registry,a,e,t);let s=await A(r,y.registry.address,"allIndexes",[],a,void 0,e);if(!Array.isArray(s)||s.length>1e3)throw new c("Chop registry inventory is unreadable or too large.");let i=s.filter(n=>n&&n.verified===!0).map(n=>b(n.index));if(new Set(i).size!==i.length)throw new c("Chop registry returned duplicate logs.");let p=[];for(let n=0;n<i.length;n+=4)f(e),p.push(...await Promise.all(i.slice(n,n+4).map(l=>S(r,l,"read",a,e,t))));f(e);let d=p.map(n=>`${n.log.symbol} (${n.log.address}): ${M(n)}`),u=p.flatMap(n=>n.drift.length?[`Code changed for ${n.log.address}: ${n.drift.join(", ")}.`]:[]);return{logs:p.map(n=>({...n,plainSummary:V(n)})),measuredAtBlock:a.toString(),warnings:[...T,...d,...u]}}async function se(o,e,r){if(f(r),!e)return F(o,r);let a=o.clientFor(4663),t=e.entry(a);if(t.inventory)return structuredClone(t.inventory);let s=t.pending;if(!s){let n=new AbortController,l={controller:n,waiters:0,promise:F(o,n.signal)};l.promise=l.promise.then(g=>{f(n.signal),t.inventory=structuredClone(g);for(let w of g.logs)t.logs.set(w.log.address.toLowerCase(),structuredClone(w));return g}).finally(()=>{n.abort(),t.pending===l&&(t.pending=void 0)}),t.pending=s=l}let i=s;i.waiters++;let p,d=!1,u=()=>{d||(d=!0,--i.waiters===0&&t.pending===i&&(i.controller.abort(),t.pending=void 0))};try{let n=await new Promise((l,g)=>{p=()=>{u(),g(new c("Chop read was cancelled."))},r?.addEventListener("abort",p,{once:!0}),i.promise.then(l,g)});return f(r),structuredClone(n)}finally{p&&r?.removeEventListener("abort",p),u()}}async function ae(o,e,r){let{limit:a,offset:t}=r,s=new Set(e.logs.map(l=>`${l.log.symbol} (${l.log.address}): ${M(l)}`)),i=e.warnings.filter(l=>!s.has(l)),p=Object.entries(e).map(([l,g])=>({name:l,chars:JSON.stringify(g).length,...Array.isArray(g)?{items:g.length}:{}})),d=o.clientFor(4663),u=e.logs.slice(t,t+a),n=[];for(let l=0;l<u.length;l+=4)n.push(...await Promise.all(u.slice(l,l+4).map(async g=>{let w=await k(d,[{target:g.pool,fn:"balanceOf",args:[g.staking.address]},{target:g.pool,fn:"totalSupply"}],BigInt(g.measuredAtBlock)),L=h(w[0]),C=h(w[1]);if(L>C)throw new c("Chop staked LP balance exceeds the pool supply.");return{log:g.log.address,symbol:g.log.symbol,backingPerLog:g.backingPerLog,fees:g.fees,pool:g.pool,stakedShare:{stakedLp:L.toString(),totalLp:C.toString(),bps:C===0n?null:Number(L*10000n/C)},riskLines:x(g).split(`
2
+ `).filter(W=>!T.includes(W)).join(`
3
+ `)}})));for(;;){let l=t+n.length,g=`Use detail: "full" for every complete row, or fields: ["logs"] or ["warnings"] for whole sections. ${l<e.logs.length?`Continue with offset: ${l}, limit: ${a}.`:"End of this list; use offset: 0 to start again."} Summary rows omit financial measurements and full contract metadata.`,w={warnings:i,summary:{logs:n,offset:t,total:e.logs.length,omitted:e.logs.length-n.length,measuredAtBlock:e.measuredAtBlock},sections:p,more:g};if(JSON.stringify(w).length<=8e3)return w;if(n.length<=1)throw new c('Chop risk lines exceed the summary budget. Request fields or detail: "full" to read them whole.');n.pop()}}async function de(o,e){let r=o.clientFor(4663),a=[];for(let t=0;t<e.length;t+=4)a.push(...await Promise.all(e.slice(t,t+4).map(async s=>{let[i,p,d,u]=await k(r,[{target:b(y.chop),fn:"balanceOf",args:[s.rewards]},{target:s.pool,fn:"token0"},{target:s.pool,fn:"token1"},{target:s.pool,fn:"getReserves"}],BigInt(s.measuredAtBlock)),n=[b(p),b(d)].map(g=>[s.log,s.paired].find(w=>w.address.toLowerCase()===g.toLowerCase()));if(!n[0]||!n[1]||n[0]===n[1])throw new c("Chop pool tokens disagree with the verified log.");if(!Array.isArray(u)||u.length!==3)throw new c("Chop pool reserves are unavailable.");let l=m(s.underlying,BigInt(s.managedUnderlying));return{...s,backingNow:{...l,humanAmount:z(BigInt(l.amount),s.underlying.decimals)},rewardPot:m({address:b(y.chop),symbol:"CHOP",decimals:18,chainId:4663},h(i)),reserves:[m(n[0],h(u[0])),m(n[1],h(u[1]))]}})));return a}var U=o=>BigInt(o.replace(".","")),H=o=>`${o/100n}.${(o%100n).toString().padStart(2,"0")}`;function le(o){return o.some(e=>e.usdEstimate===null)?{reserves:o,usdEstimate:null,estimateLabel:"price unavailable",estimateReason:"A pool reserve has no USD estimate"}:{reserves:o,usdEstimate:H(o.reduce((e,r)=>e+U(r.usdEstimate),0n)),estimateLabel:"estimate, not a quote",estimateSource:"sum of the two reserve estimates"}}function pe(o,e){let r={label:"rough",pct:null,inputToken:e,assumptions:"Constant-product marginal price move for buying the log with $100 of the paired token; excludes pool and token fees, gas and other trades."};if(o.some(d=>BigInt(d.amount)===0n))return{...r,reason:"The pool is empty on at least one side"};let a=o.find(d=>d.token.address.toLowerCase()===e.address.toLowerCase());if(!a?.usdEstimate||U(a.usdEstimate)===0n)return{...r,reason:"Paired reserve price unavailable or below one cent"};let t=U(a.usdEstimate),i=((t+10000n)**2n-t**2n)*10000n,p=t**2n;return{...r,pct:H((2n*i+p)/(2n*p))}}var q=new WeakMap,Y=10;async function Z(o,e,r,a,t,s){if(f(t),e.length>Y)throw new c("Chop holdings probes support at most ten logs per call.");if(e.length===0)return[];let i=t?q.get(t):void 0;t&&!i&&(i=I(),q.set(t,i)),await v(o,y.whitelist,a,t,i);let p=await k(o,e.flatMap(d=>[{target:d.log.address,fn:"balanceOf",args:[r]},{target:d.staking.address,fn:"balanceOf",args:[r]},{target:d.staking.address,fn:"withdrawableStake",args:[r]},{target:d.rewards,fn:"getUnpaid",args:[y.chop,r]},{target:d.rewards,fn:"getClaimable",args:[y.chop,r]},{target:y.whitelist.address,fn:"paused",args:[y.chop]},{target:d.log.address,fn:"totalSupply"},{target:d.log.address,fn:"totalAssets",args:[d.underlying.address]}]),a,t);return f(t),Promise.all(e.map(async(d,u)=>{let n=await Q(o,d,r,a,t,p.slice(u*8,(u+1)*8));return f(t),s?.(n,u),n}))}async function G(o,e,r,a=BigInt(e.measuredAtBlock),t){return(await Z(o,[e],r,a,t))[0]}async function Q(o,e,r,a,t,s){if(f(t),typeof s[5]!="boolean")throw new c("Chop reward pause state is unavailable.");let i=h(s[0]),p=h(s[6]),d=h(s[7]);if(p===0n)throw new c("This Chop log has no issued supply.");let u={...e,totalSupply:p.toString(),managedUnderlying:d.toString()},n=i===0n?{gross:m(e.underlying,0n),fee:m(e.underlying,0n),net:m(e.underlying,0n)}:await _(o,u,r,i,a,t),l={address:b(y.chop),symbol:"CHOP",decimals:18,chainId:4663};return{log:e.log.address,logTokens:m(e.log,i),...n,stakedLp:m(e.staking,h(s[1])),withdrawableLp:m(e.staking,h(s[2])),pendingChop:m(l,h(s[3])),claimableChop:m(l,h(s[4])),rewardsPaused:s[5],measuredAtBlock:a.toString(),warnings:x(e)}}async function ge(o,e,r,a){let t=o.clientFor(4663);b(r);let s=a?.entry(t),i=b(e).toLowerCase(),p=s?.logs.get(i)??await S(t,e,"read");return s&&!s.logs.has(i)&&s.logs.set(i,structuredClone(p)),G(t,p,r,await P(t))}async function ue(o,e,r,a){let t=R(a),s=o.clientFor(4663);b(r);let i=await S(s,e,"exit"),p=h(await A(s,i.log.address,"balanceOf",[r],BigInt(i.measuredAtBlock)));if(p===0n)throw new c(D(i.log.symbol));if(t>p)throw new c(N(i.log,t,p));let d=await _(s,i,r,t),u=BigInt(d.net.amount);if(u===0n)throw new c("This Chop unwrap would return no underlying.");let n=K(i,t),l=o.unsignedTx(n);B([l],[n]);let g=await o.preview([l],r);B(g.txs,[n]);let w=$(g,[{token:i.log,min:-t,max:-t},{token:i.underlying,min:u}]);return{log:i.log.address,amount:t.toString(),...d,simulatedNet:m(i.underlying,w.get(i.underlying.address.toLowerCase())),quotedNet:d.net.amount,preview:g,measuredAtBlock:i.measuredAtBlock,warning:O,summary:x(i)}}export{m as a,J as b,ie as c,K as d,_ as e,se as f,ae as g,de as h,le as i,pe as j,Y as k,Z as l,G as m,ge as n,ue as o};
@@ -0,0 +1 @@
1
+ import{a as f,b as p,c as b,e as y,f as F}from"./JJGZ7W3V.js";import{a as l,b as h}from"./CZL6T2ZQ.js";import{a as d}from"./ZQ6AF3VX.js";import{a as m}from"./K7HTDKAT.js";import{a as u}from"./DGCJZ3HO.js";import{a as o,e as g}from"./XSD5NL7J.js";import{decodeErrorResult as A,getAddress as i,isAddressEqual as w}from"viem";function $(e,r,a=[]){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!r.includes(t)))throw new o("Unexpected Factor argument.");if(a.some(t=>e[t]===void 0))throw new o("Provide every required Factor input.")}function S(e,r,a=!0){if(typeof e!="string"&&typeof e!="bigint"||!/^[0-9]+$/.test(String(e)))throw new o(`Provide ${r} as a decimal integer string.`);let t=BigInt(e);if(a&&t===0n||t>=2n**256n)throw new o(`${r} must fit a positive uint256.`);return t}function C(e){if(e.chainId!==l.chainId)throw new o("Factor requires Robinhood Chain 4663.");if(!w(i(e.to),h.desk.address))throw new o("Factor calls must target the pinned desk. Nothing was sent.");if(e.value!=="0")throw new o('Factor calls must attach value "0". Nothing was sent.');if(e.gasLimit!==void 0)throw new o("Factor calls use the sender\u2019s gas estimate; omit a fixed gas limit.")}async function x(e,r,a){if(e.network==="testnet")throw new o("Factor requires Robinhood Chain 4663.");let t=i(r),s=e.clientFor(l.chainId),[n,c,T]=await Promise.all([p(s),m(e.http),F(s,t)]);if(f({...n,stateDesk:c==="unreachable"?c:c.desk},a),T)throw new o(u.walletCode);return c}async function E(e,r){return e.readContract({address:h.desk.address,abi:d,functionName:"agent",args:[i(r)]})}async function I(e,r,a){let t=await b(e,S(r,"job"));if(!w(t.agent,i(a)))throw w(await y(e,t.agent),a)?new o(u.lineAccount):new o("Only the job's agent can do this.");return t}function k(e){let r=e;for(let a=0;a<12&&r&&typeof r=="object";a++){let t=r;if(typeof t.data=="string"&&/^0x[0-9a-f]+$/i.test(t.data))try{let s=A({abi:d,data:t.data}),n=s.args?.[0];switch(s.errorName){case"NotAgent":return"Only the job's agent can do this.";case"NotCustomer":return"Only this job\u2019s customer can do this.";case"NotRegistered":return"This wallet has not registered as a Factor agent.";case"AlreadyRegistered":return"This wallet is already registered as a Factor agent.";case"EarlyNotAllowed":return"The customer did not allow an early advance on this job.";case"TooLate":return"It is too late for that on this job.";case"WrongState":return"The job is not in a state that permits this action. Read the job again.";case"OverHalf":return`Advances stop at half the job price; ${String(n)} wei remains drawable.`;case"OverLimit":return`This agent\u2019s pool limit permits ${String(n)} wei now.`;case"PoolShort":return`Factor\u2019s pool has room to advance ${String(n)} wei now.`;case"Barred":return"Factor\u2019s pool no longer advances this agent.";case"ZeroAmount":return"The draw amount must be greater than zero.";case"TooSmall":return`Factor requires at least ${String(n)} wei for a job.`;case"TooSoon":return`Factor permits this action from Unix second ${String(n)}.`;case"BadDueTime":return"The due time must be from 1 hour to 30 days away.";case"GasShort":return"The simulation supplied too little gas for the desk payout. Re-estimate gas.";case"ReentrancyGuardReentrantCall":return"Factor\u2019s desk refused a reentrant call.";case"NothingOwed":return"No Factor payout is waiting for this wallet.";case"OwesThePool":return`The bond cannot leave while ${String(n)} wei is owed to the pool.`;case"OverBond":return`The bond holds only ${String(n)} wei.`;case"PushFailed":return"The recipient refused the Factor payout.";case"ZeroAddress":return"Factor requires a nonzero address."}}catch{}r=typeof t.data=="object"&&t.data!==null?t.data:t.cause??t.error}return g(e)}async function q(e,r,a){C(r);try{await e.call({account:i(a),to:r.to,data:r.data,value:0n})}catch(t){throw new o(`${k(t)} Nothing was sent.`)}}export{$ as a,S as b,C as c,x as d,E as e,I as f,k as g,q as h};