@floorlaunchpad/sdk 0.1.1 → 0.3.1

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 (298) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/LICENSE +201 -60
  3. package/README.md +54 -24
  4. package/dist/abi/evm-event-names.js +12 -0
  5. package/dist/abi/evm.gen.js +130 -0
  6. package/dist/abi/functions.gen.js +144 -0
  7. package/dist/abi/index.js +17 -0
  8. package/dist/abi/solana.gen.js +130 -0
  9. package/dist/burn.js +21 -0
  10. package/dist/client/evm/index.js +191 -0
  11. package/dist/client/index.js +19 -0
  12. package/dist/client/solana/index.js +259 -0
  13. package/dist/client/types.js +5 -0
  14. package/dist/codec.js +77 -0
  15. package/dist/config/codeHash.js +9 -0
  16. package/dist/config/generated.js +803 -0
  17. package/dist/config/index.js +49 -0
  18. package/dist/config/registry.gen.js +118 -0
  19. package/dist/config/solana-genesis.js +7 -0
  20. package/dist/ed25519.js +31 -0
  21. package/dist/errors.js +249 -0
  22. package/dist/events/index.js +40 -0
  23. package/dist/events/types.gen.js +3 -0
  24. package/dist/evm/abi.js +283 -0
  25. package/dist/evm/balances.js +26 -0
  26. package/dist/evm/chains.js +148 -0
  27. package/dist/evm/floor/abi.gen.js +195 -0
  28. package/dist/evm/floor/calls.js +230 -0
  29. package/dist/evm/floor/create.js +49 -0
  30. package/dist/evm/floor/events.js +41 -0
  31. package/dist/evm/floor/iface.js +44 -0
  32. package/dist/evm/items.js +209 -0
  33. package/dist/evm/keccak.js +118 -0
  34. package/dist/evm/multicall.js +30 -0
  35. package/dist/evm/router.js +184 -0
  36. package/dist/evm/squid.js +107 -0
  37. package/dist/evm/zap.js +128 -0
  38. package/dist/fixtures.js +53 -0
  39. package/dist/generated/index.js +28 -0
  40. package/dist/generated/interface.gen.js +146 -0
  41. package/dist/handle.js +22 -0
  42. package/dist/index.js +93 -7
  43. package/dist/indexer/bodies.js +473 -0
  44. package/dist/indexer/client.js +105 -0
  45. package/dist/indexer/contract.js +358 -0
  46. package/dist/indexer/decode.js +97 -0
  47. package/dist/indexer/partners.js +105 -0
  48. package/dist/indexer/paths.js +127 -0
  49. package/dist/indexer/read.js +109 -0
  50. package/dist/indexer/stream.js +71 -0
  51. package/dist/lock.js +16 -0
  52. package/dist/math/fixed.js +154 -0
  53. package/dist/math/genesis.js +39 -0
  54. package/dist/math/index.js +20 -0
  55. package/dist/math/u256.js +49 -0
  56. package/dist/math/v2/ask.js +162 -0
  57. package/dist/math/v2/book.js +607 -0
  58. package/dist/math/v2/circulating.js +62 -0
  59. package/dist/math/v2/create.js +122 -0
  60. package/dist/math/v2/display.js +208 -0
  61. package/dist/math/v2/error.js +17 -0
  62. package/dist/math/v2/feasibility.js +174 -0
  63. package/dist/math/v2/fees.js +121 -0
  64. package/dist/math/v2/holders.js +105 -0
  65. package/dist/math/v2/milestones.js +40 -0
  66. package/dist/math/v2/pow.js +69 -0
  67. package/dist/math/v2/preset.js +151 -0
  68. package/dist/math/v2/receipt.js +108 -0
  69. package/dist/math/v2/relay.js +217 -0
  70. package/dist/math/v2/rows.js +365 -0
  71. package/dist/math/v2/split.js +111 -0
  72. package/dist/math/v2/sqrt.js +84 -0
  73. package/dist/math/v2/supply.js +21 -0
  74. package/dist/math/v2/team.js +75 -0
  75. package/dist/math/v2/trade.js +126 -0
  76. package/dist/math/v2/wide.js +51 -0
  77. package/dist/quote.js +6 -0
  78. package/dist/registryPrice.js +23 -0
  79. package/dist/route/edge-jupiter.js +42 -0
  80. package/dist/route/edge.js +11 -0
  81. package/dist/route/graph.js +51 -0
  82. package/dist/route/path.js +75 -0
  83. package/dist/route/quote.js +15 -0
  84. package/dist/route-jupiter.js +35 -0
  85. package/dist/route.js +8 -0
  86. package/dist/sha256.js +61 -0
  87. package/dist/solana/alt.js +18 -0
  88. package/dist/solana/floor/accounts.js +392 -0
  89. package/dist/solana/floor/borsh.js +66 -0
  90. package/dist/solana/floor/create.js +65 -0
  91. package/dist/solana/floor/events.js +144 -0
  92. package/dist/solana/floor/genesis.js +91 -0
  93. package/dist/solana/floor/genesisList.js +68 -0
  94. package/dist/solana/floor/instructions.js +448 -0
  95. package/dist/solana/floor/metadata.js +198 -0
  96. package/dist/solana/floor/mint.js +206 -0
  97. package/dist/solana/floor/program.js +64 -0
  98. package/dist/solana/floor/registry.js +83 -0
  99. package/dist/solana/instruction.js +49 -0
  100. package/dist/solana/pda.js +88 -0
  101. package/dist/solana/tx.js +138 -0
  102. package/dist/v2/burnPreview.js +35 -0
  103. package/dist/v2/circulating.js +11 -0
  104. package/dist/v2/claimAllEvm.js +70 -0
  105. package/dist/v2/claims-evm.js +120 -0
  106. package/dist/v2/claims.js +218 -0
  107. package/dist/v2/dead.js +21 -0
  108. package/dist/v2/devbuy.js +37 -0
  109. package/dist/v2/events.js +115 -0
  110. package/dist/v2/evm.js +299 -0
  111. package/dist/v2/evmReads.js +76 -0
  112. package/dist/v2/genesis.js +76 -0
  113. package/dist/v2/layouts.js +217 -0
  114. package/dist/v2/market-evm.js +74 -0
  115. package/dist/v2/presetRowEvm.js +45 -0
  116. package/dist/v2/press.js +106 -0
  117. package/dist/v2/quoteMint.js +52 -0
  118. package/dist/v2/receipt-tx.js +149 -0
  119. package/dist/v2/route-alt.js +114 -0
  120. package/dist/v2/route.js +389 -0
  121. package/dist/v2/router.js +22 -0
  122. package/dist/v2/solana.js +391 -0
  123. package/dist/v2/solanaSettle.js +97 -0
  124. package/dist/v2/tx/evm.js +126 -0
  125. package/dist/v2/tx/genesis.js +47 -0
  126. package/dist/v2/tx/index.js +5 -0
  127. package/dist/v2/tx/solana.js +118 -0
  128. package/dist/v2/types.js +13 -0
  129. package/docs/aggregator.md +61 -0
  130. package/docs/bot.md +50 -0
  131. package/docs/floor-line.md +66 -0
  132. package/docs/frontend.md +29 -0
  133. package/docs/wallet.md +54 -0
  134. package/examples/floor-line.html +104 -0
  135. package/package.json +429 -32
  136. package/src/abi/evm-event-names.ts +12 -0
  137. package/src/abi/evm.gen.ts +139 -0
  138. package/src/abi/functions.gen.ts +154 -0
  139. package/src/abi/index.ts +30 -0
  140. package/src/abi/solana.gen.ts +140 -0
  141. package/src/burn.ts +37 -0
  142. package/src/client/evm/index.ts +199 -0
  143. package/src/client/index.ts +23 -0
  144. package/src/client/solana/index.ts +260 -0
  145. package/src/client/types.ts +162 -0
  146. package/src/codec.ts +77 -0
  147. package/src/config/codeHash.ts +9 -0
  148. package/src/config/generated.ts +803 -0
  149. package/src/config/index.ts +93 -0
  150. package/src/config/registry.gen.ts +118 -0
  151. package/src/config/solana-genesis.ts +7 -0
  152. package/src/ed25519.ts +31 -0
  153. package/src/errors.ts +270 -0
  154. package/src/events/index.ts +44 -0
  155. package/src/events/types.gen.ts +842 -0
  156. package/src/evm/abi.ts +292 -0
  157. package/src/evm/balances.ts +26 -0
  158. package/src/evm/chains.ts +171 -0
  159. package/src/evm/floor/abi.gen.ts +195 -0
  160. package/src/evm/floor/calls.ts +247 -0
  161. package/src/evm/floor/create.ts +68 -0
  162. package/src/evm/floor/events.ts +51 -0
  163. package/src/evm/floor/iface.ts +45 -0
  164. package/src/evm/items.ts +252 -0
  165. package/src/evm/keccak.ts +118 -0
  166. package/src/evm/multicall.ts +43 -0
  167. package/src/evm/router.ts +209 -0
  168. package/src/evm/squid.ts +138 -0
  169. package/src/evm/zap.ts +152 -0
  170. package/src/fixtures.ts +53 -0
  171. package/src/generated/index.ts +29 -0
  172. package/src/generated/interface.gen.ts +153 -0
  173. package/src/handle.ts +22 -0
  174. package/src/index.ts +93 -6
  175. package/src/indexer/bodies.ts +528 -0
  176. package/src/indexer/client.ts +180 -0
  177. package/src/indexer/contract.ts +419 -0
  178. package/src/indexer/decode.ts +109 -0
  179. package/src/indexer/partners.ts +115 -0
  180. package/src/indexer/paths.ts +190 -0
  181. package/src/indexer/read.ts +119 -0
  182. package/src/indexer/stream.ts +83 -0
  183. package/src/lock.ts +16 -0
  184. package/src/math/fixed.ts +154 -0
  185. package/src/math/genesis.ts +39 -0
  186. package/src/math/index.ts +24 -0
  187. package/src/math/u256.ts +49 -0
  188. package/src/math/v2/ask.ts +218 -0
  189. package/src/math/v2/book.ts +660 -0
  190. package/src/math/v2/circulating.ts +69 -0
  191. package/src/math/v2/create.ts +139 -0
  192. package/src/math/v2/display.ts +250 -0
  193. package/src/math/v2/error.ts +19 -0
  194. package/src/math/v2/feasibility.ts +200 -0
  195. package/src/math/v2/fees.ts +121 -0
  196. package/src/math/v2/holders.ts +124 -0
  197. package/src/math/v2/milestones.ts +51 -0
  198. package/src/math/v2/pow.ts +71 -0
  199. package/src/math/v2/preset.ts +189 -0
  200. package/src/math/v2/receipt.ts +162 -0
  201. package/src/math/v2/relay.ts +235 -0
  202. package/src/math/v2/rows.ts +412 -0
  203. package/src/math/v2/split.ts +160 -0
  204. package/src/math/v2/sqrt.ts +86 -0
  205. package/src/math/v2/supply.ts +27 -0
  206. package/src/math/v2/team.ts +75 -0
  207. package/src/math/v2/trade.ts +145 -0
  208. package/src/math/v2/wide.ts +52 -0
  209. package/src/quote.ts +6 -0
  210. package/src/registryPrice.ts +28 -0
  211. package/src/route/edge-jupiter.ts +71 -0
  212. package/src/route/edge.ts +22 -0
  213. package/src/route/graph.ts +77 -0
  214. package/src/route/path.ts +84 -0
  215. package/src/route/quote.ts +46 -0
  216. package/src/route-jupiter.ts +36 -0
  217. package/src/route.ts +8 -0
  218. package/src/sha256.ts +61 -0
  219. package/src/solana/alt.ts +25 -0
  220. package/src/solana/floor/accounts.ts +395 -0
  221. package/src/solana/floor/borsh.ts +66 -0
  222. package/src/solana/floor/create.ts +89 -0
  223. package/src/solana/floor/events.ts +151 -0
  224. package/src/solana/floor/genesis.ts +111 -0
  225. package/src/solana/floor/genesisList.ts +75 -0
  226. package/src/solana/floor/instructions.ts +504 -0
  227. package/src/solana/floor/metadata.ts +246 -0
  228. package/src/solana/floor/mint.ts +242 -0
  229. package/src/solana/floor/program.ts +64 -0
  230. package/src/solana/floor/registry.ts +96 -0
  231. package/src/solana/instruction.ts +61 -0
  232. package/src/solana/pda.ts +91 -0
  233. package/src/solana/tx.ts +143 -0
  234. package/src/v2/burnPreview.ts +52 -0
  235. package/src/v2/circulating.ts +22 -0
  236. package/src/v2/claimAllEvm.ts +97 -0
  237. package/src/v2/claims-evm.ts +179 -0
  238. package/src/v2/claims.ts +288 -0
  239. package/src/v2/dead.ts +21 -0
  240. package/src/v2/devbuy.ts +55 -0
  241. package/src/v2/events.ts +131 -0
  242. package/src/v2/evm.ts +349 -0
  243. package/src/v2/evmReads.ts +121 -0
  244. package/src/v2/genesis.ts +80 -0
  245. package/src/v2/layouts.ts +219 -0
  246. package/src/v2/market-evm.ts +95 -0
  247. package/src/v2/presetRowEvm.ts +54 -0
  248. package/src/v2/press.ts +124 -0
  249. package/src/v2/quoteMint.ts +63 -0
  250. package/src/v2/receipt-tx.ts +251 -0
  251. package/src/v2/route-alt.ts +114 -0
  252. package/src/v2/route.ts +494 -0
  253. package/src/v2/router.ts +22 -0
  254. package/src/v2/solana.ts +439 -0
  255. package/src/v2/solanaSettle.ts +117 -0
  256. package/src/v2/tx/evm.ts +152 -0
  257. package/src/v2/tx/genesis.ts +66 -0
  258. package/src/v2/tx/index.ts +5 -0
  259. package/src/v2/tx/solana.ts +140 -0
  260. package/src/v2/types.ts +284 -0
  261. package/dist/adapter.d.ts +0 -28
  262. package/dist/adapter.d.ts.map +0 -1
  263. package/dist/adapter.js +0 -2
  264. package/dist/adapter.js.map +0 -1
  265. package/dist/chain.d.ts +0 -23
  266. package/dist/chain.d.ts.map +0 -1
  267. package/dist/chain.js +0 -25
  268. package/dist/chain.js.map +0 -1
  269. package/dist/client.d.ts +0 -26
  270. package/dist/client.d.ts.map +0 -1
  271. package/dist/client.js +0 -43
  272. package/dist/client.js.map +0 -1
  273. package/dist/dex-adapter.d.ts +0 -228
  274. package/dist/dex-adapter.d.ts.map +0 -1
  275. package/dist/dex-adapter.js +0 -407
  276. package/dist/dex-adapter.js.map +0 -1
  277. package/dist/index.d.ts +0 -7
  278. package/dist/index.d.ts.map +0 -1
  279. package/dist/index.js.map +0 -1
  280. package/dist/quotes.d.ts +0 -12
  281. package/dist/quotes.d.ts.map +0 -1
  282. package/dist/quotes.gen.d.ts +0 -8
  283. package/dist/quotes.gen.d.ts.map +0 -1
  284. package/dist/quotes.gen.js +0 -2170
  285. package/dist/quotes.gen.js.map +0 -1
  286. package/dist/quotes.js +0 -24
  287. package/dist/quotes.js.map +0 -1
  288. package/dist/types.d.ts +0 -111
  289. package/dist/types.d.ts.map +0 -1
  290. package/dist/types.js +0 -2
  291. package/dist/types.js.map +0 -1
  292. package/src/adapter.ts +0 -20
  293. package/src/chain.ts +0 -39
  294. package/src/client.ts +0 -41
  295. package/src/dex-adapter.ts +0 -477
  296. package/src/quotes.gen.ts +0 -2170
  297. package/src/quotes.ts +0 -29
  298. package/src/types.ts +0 -115
@@ -0,0 +1,389 @@
1
+
2
+
3
+ import { EVM_NATIVE, NoRouteError, SOL_NATIVE, coinKey } from "../route/graph.js";
4
+ import { FloorQuoteError } from "../quote.js";
5
+ import { FloorMathError } from "../math/index.js";
6
+ import { COMPUTE_BUDGET_PROGRAM_ID, MAX_COMPUTE_UNIT_LIMIT, computeUnitLimitFor, computeUnitLimitInstruction, computeUnitPriceInstruction } from "../solana/instruction.js";
7
+
8
+ import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, WSOL_MINT, associatedTokenAddress } from "../solana/pda.js";
9
+ import { PACKET_DATA_SIZE, closeAccountInstruction, compileV0Message, createAssociatedTokenAccountIdempotentInstruction, syncNativeInstruction, systemTransferInstruction, transactionSize } from "../solana/tx.js";
10
+
11
+ import { FLOOR_AMM_PROGRAM_ID, launchPda, quoteVault, tokenVault, traderRefEscrow, traderRefPda } from "../solana/floor/program.js";
12
+ import { approveCall, buyCall, sellCall } from "../evm/floor/calls.js";
13
+
14
+ import { EVM_TOKEN_SCALE } from "./market-evm.js";
15
+ import { checkFloorHops, evmRouteCall } from "../evm/router.js";
16
+
17
+ import { edgeLegInstructions } from "../route/edge.js";
18
+
19
+ import { jupiterEdgeLeg } from "../route/edge-jupiter.js";
20
+
21
+ import { buyFromBalanceInstructionV2, buyInstructionV2, canHoldPosition, openHolderPositionInstruction, sellFromBalanceInstructionV2, sellInstructionV2 } from "./solana.js";
22
+
23
+ import { quoteReceivedV2, quoteTransferFeeV2 } from "./quoteMint.js";
24
+
25
+ import { MAX_SLIPPAGE_BPS, minOutAt } from "./press.js";
26
+ import { buyLessIn } from "../math/v2/trade.js";
27
+
28
+ export function isWrapHopV2(h ) {
29
+ return h.kind === "edge" && ((h.from === SOL_NATIVE && h.to === WSOL_MINT) || (h.from === WSOL_MINT && h.to === SOL_NATIVE));
30
+ }
31
+
32
+ export const MAX_QUOTE_CHAIN_V2 = 8;
33
+
34
+ function chainOf (byToken , coin , edge ) {
35
+ const pools = [];
36
+ const coins = [coinKey(coin)];
37
+ for (let c = coin; ; ) {
38
+ const pool = edge.has(coinKey(c)) ? undefined : byToken.get(coinKey(c));
39
+ if (!pool) return { pools, coins, base: c };
40
+ if (pools.length >= MAX_QUOTE_CHAIN_V2 || pools.includes(pool)) throw new NoRouteError("QuoteCycle", `${coin}'s quote chain does not end`);
41
+ pools.push(pool);
42
+ c = pool.quote;
43
+ coins.push(coinKey(c));
44
+ }
45
+ }
46
+
47
+ export function findRouteV2 (pools , from , to , opts = {}) {
48
+ if (coinKey(from) === coinKey(to)) throw new NoRouteError("Same", `${from} → itself`);
49
+ const byToken = new Map ();
50
+ for (const p of pools) byToken.set(coinKey(p.token), p);
51
+ const edge = new Set([...(opts.edge ?? [])].map(coinKey));
52
+ const a = chainOf(byToken, from, edge);
53
+ const b = chainOf(byToken, to, edge);
54
+ const all = [...a.pools, ...b.pools];
55
+ if (all.length === 0) throw new NoRouteError("NoFloorHop", `${from} → ${to} crosses no FLOOR launch`);
56
+ const chain = all[0].chain;
57
+ if (all.some((x) => x.chain !== chain)) throw new NoRouteError("Mixed", `${from} → ${to} mixes chains`);
58
+ for (let i = 0; i < a.coins.length; i++) {
59
+ const j = b.coins.indexOf(a.coins[i]);
60
+ if (j < 0) continue;
61
+ const hops = [...a.pools.slice(0, i).map((pool) => ({ kind: "sell" , pool })), ...b.pools.slice(0, j).reverse().map((pool) => ({ kind: "buy" , pool }))];
62
+ return { chain, from, to, hops };
63
+ }
64
+ if (a.pools.length + b.pools.length === 0) throw new NoRouteError("NoFloorHop", `${from} → ${to}: no launch on the way (an outside leg alone is not a FLOOR route)`);
65
+ if (edge.size === 0) throw new NoRouteError("NoFloorHop", `${from} → ${to}: the quote chains never meet (an outside leg needs \`edge\`)`);
66
+ const hops = [
67
+ ...a.pools.map((pool) => ({ kind: "sell" , pool })),
68
+ { kind: "edge", from: a.base, to: b.base },
69
+ ...[...b.pools].reverse().map((pool) => ({ kind: "buy" , pool })),
70
+ ];
71
+ return { chain, from, to, hops };
72
+ }
73
+
74
+ const less = (x , slippageBps ) => (x > 0n ? minOutAt(x, slippageBps) : 1n);
75
+
76
+ const lessIn = (x , slippageBps ) => (x > 0n ? buyLessIn(x, slippageBps) : 0n);
77
+
78
+ export function fillsNothing(e ) {
79
+ if (e instanceof FloorQuoteError) return e.code === "NothingToBuy" || e.code === "Zero";
80
+ if (e instanceof FloorMathError) return e.code === "NothingToDo" || e.code === "Zero";
81
+ return false;
82
+ }
83
+
84
+ export function minChain (f , min , isNothing = fillsNothing) {
85
+ if (min <= 0n) return null;
86
+ try {
87
+ const r = f();
88
+ return r.out > 0n ? r : null;
89
+ } catch (e) {
90
+ if (isNothing(e)) return null;
91
+ throw e;
92
+ }
93
+ }
94
+
95
+ function* priceHops (p ) {
96
+ if (p.amountIn <= 0n) throw new RangeError("amountIn must be > 0");
97
+ if (!Number.isInteger(p.slippageBps) || p.slippageBps < 0 || p.slippageBps > MAX_SLIPPAGE_BPS) throw new RangeError(`slippageBps in 0..=${MAX_SLIPPAGE_BPS}`);
98
+ if (!p.path.hops.some((h) => h.kind !== "edge")) throw new RangeError("an empty path (no FLOOR hop)");
99
+
100
+ if (p.path.chain === "evm") checkFloorHops(p.chainId, p.path.hops.filter((h) => h.kind !== "edge").length);
101
+ const seen = new Set ();
102
+ for (const h of p.path.hops) {
103
+ if (h.kind === "edge") continue;
104
+ const id = coinKey(h.pool.token);
105
+ if (seen.has(id)) throw new RangeError(`the path trades ${h.pool.token} twice: quote it as one hop`);
106
+ seen.add(id);
107
+ }
108
+ const hops = [];
109
+ let expected = p.amountIn;
110
+ let min = p.amountIn;
111
+ let surplus ;
112
+ for (const [i, hop] of p.path.hops.entries()) {
113
+ if (hop.kind === "edge") {
114
+ if (isWrapHopV2(hop)) {
115
+
116
+ hops.push({ hop, amountIn: expected, amountOut: expected, minOut: min, minReceived: min, quote: { out: expected }, minFloored: false });
117
+ continue;
118
+ }
119
+
120
+ const out = p.path.hops.slice(0, i).some((h) => h.kind === "sell");
121
+ const amountIn = out ? min : expected;
122
+ const e = yield { from: hop.from, to: hop.to, amountIn, slippageBps: p.slippageBps };
123
+
124
+ if (e.minOut < 1n || e.minOut > e.outAmount) throw new RangeError(`the edge quote for hop ${i} has minOut ${e.minOut}: it must be 1..=outAmount ${e.outAmount}`);
125
+ if (e.inAmount !== amountIn) throw new RangeError(`the edge quote for hop ${i} is for ${e.inAmount}, not ${amountIn}`);
126
+ if (out) surplus = { coin: hop.from, expected: expected - min };
127
+ hops.push({ hop, amountIn, amountOut: e.outAmount, minOut: e.minOut, minReceived: e.minOut, quote: { out: e.outAmount }, minFloored: false, edge: e });
128
+ expected = e.outAmount;
129
+ min = e.minOut;
130
+ continue;
131
+ }
132
+
133
+ const tf = hop.pool.quoteTransferFee;
134
+ if (tf?.fee && hop.pool.chain !== "solana") throw new RangeError(`pool ${hop.pool.symbol}: quoteTransferFee is Solana's (Token-2022)`);
135
+ const fee = (x ) => (tf ? quoteTransferFeeV2(tf.fee, tf.epoch, x) : 0n);
136
+ const arrives = (x ) => (tf ? quoteReceivedV2(tf.fee, tf.epoch, x) : x);
137
+ let qe ;
138
+ if (hop.kind === "buy") {
139
+ const w = fee(expected);
140
+ if (w >= expected) throw new RangeError(`hop ${i} (buy ${hop.pool.symbol}): QuoteTransferShort: the quote mint's transfer fee ${w} takes the whole amount ${expected}`);
141
+ qe = p.quote(hop.pool.launch, hop.kind, expected - w);
142
+ } else qe = p.quote(hop.pool.launch, hop.kind, expected);
143
+ if (qe.out <= 0n) throw new RangeError(`hop ${i} (${hop.kind} ${hop.pool.symbol}) fills nothing on ${expected}`);
144
+
145
+ let qm ;
146
+ let minOut ;
147
+ let minReceived ;
148
+ let amountOut ;
149
+ if (hop.kind === "buy") {
150
+ const mIn = lessIn(min, p.slippageBps);
151
+ const mw = fee(mIn);
152
+
153
+ qm = mIn === expected ? qe : mw >= mIn ? null : minChain(() => p.quote(hop.pool.launch, hop.kind, mIn - mw), mIn - mw, p.isNothing);
154
+ minOut = qm ? qm.out : 1n;
155
+ minReceived = minOut;
156
+ amountOut = qe.out;
157
+ } else {
158
+ qm = min === expected ? qe : minChain(() => p.quote(hop.pool.launch, hop.kind, min), min, p.isNothing);
159
+ minOut = qm ? less(qm.out, p.slippageBps) : 1n;
160
+ minReceived = arrives(minOut);
161
+ amountOut = arrives(qe.out);
162
+ if (amountOut <= 0n) throw new RangeError(`hop ${i} (sell ${hop.pool.symbol}): the quote mint's transfer fee takes the whole payout ${qe.out}`);
163
+ }
164
+ hops.push({ hop, amountIn: expected, amountOut, minOut, minReceived, quote: qe, minFloored: qm === null });
165
+ expected = amountOut;
166
+ min = minReceived;
167
+ }
168
+ return { path: p.path, amountIn: p.amountIn, amountOut: expected, minOut: min, hops, slippageBps: p.slippageBps, ...(p.path.chain === "evm" ? { chainId: p.chainId } : {}), ...(surplus ? { surplus } : {}) };
169
+ }
170
+
171
+ export function quoteRouteV2 (p ) {
172
+ const r = priceHops(p).next();
173
+ if (!r.done) throw new RangeError(`the outside leg ${r.value.from} → ${r.value.to} needs an EdgeQuoter: use quoteRouteEdgeV2`);
174
+ return r.value;
175
+ }
176
+
177
+ export async function quoteRouteEdgeV2 (p ) {
178
+ const g = priceHops(p);
179
+ let r = g.next();
180
+ while (!r.done) {
181
+ if (!p.edge) throw new RangeError(`the outside leg ${r.value.from} → ${r.value.to} needs an EdgeQuoter (\`edge\`)`);
182
+ r = g.next(await p.edge(r.value));
183
+ }
184
+ return r.value;
185
+ }
186
+
187
+ function quoteProgramOf(pool , all ) {
188
+ if (pool.quoteTokenProgram) return pool.quoteTokenProgram;
189
+ if (all.some((x) => coinKey(x.token) === coinKey(pool.quote))) return TOKEN_2022_PROGRAM_ID;
190
+ throw new RangeError(`pool ${pool.symbol}: quoteTokenProgram is required`);
191
+ }
192
+
193
+ export function routeTradeAccountsV2(trader , pool , quoteTokenProgram , programId = FLOOR_AMM_PROGRAM_ID) {
194
+ const launch = launchPda(pool.token, programId)[0];
195
+ const traderRef = pool.referred || pool.linked ? traderRefPda(trader, pool.quote, programId)[0] : null;
196
+ return {
197
+ programId, trader, launch, baseMint: pool.token, quoteMint: pool.quote,
198
+ tokenVault: tokenVault(launch, pool.token), quoteVault: quoteVault(launch, pool.quote, quoteTokenProgram),
199
+ traderBase: associatedTokenAddress(trader, pool.token, TOKEN_2022_PROGRAM_ID), traderQuote: associatedTokenAddress(trader, pool.quote, quoteTokenProgram),
200
+ quoteTokenProgram, traderRef, escrow: traderRef ? traderRefEscrow(traderRef, pool.quote, quoteTokenProgram) : null,
201
+ user: pool.linked ? trader : null,
202
+ };
203
+ }
204
+
205
+ export function routeInstructionsV2(p ) {
206
+ return hopInstructionsV2(p).flat();
207
+ }
208
+
209
+ function hopInstructionsV2(p ) {
210
+ const q = p.quote;
211
+ if (q.path.chain !== "solana") throw new RangeError("routeInstructionsV2 builds Solana routes; EVM routes are `evmRouteCallV2` / `evmHopCallsV2`");
212
+ const programId = p.programId ?? FLOOR_AMM_PROGRAM_ID;
213
+ const pools = q.hops.flatMap((h) => (h.hop.kind === "edge" ? [] : [h.hop.pool]));
214
+ const edges = [...(p.edges ?? [])];
215
+ const legs = q.hops.filter((h) => h.hop.kind === "edge" && !isWrapHopV2(h.hop)).length;
216
+ if (edges.length !== legs) throw new RangeError(`the route has ${legs} edge leg(s): pass ${legs} EdgeLeg(s), not ${edges.length}`);
217
+ const wsolAta = associatedTokenAddress(p.trader, WSOL_MINT, TOKEN_PROGRAM_ID);
218
+
219
+ const bal = (mint ) => {
220
+ const v = p.balances?.[mint];
221
+ if (v === undefined) throw new RangeError(`balances[${mint}] is required: the trader's balance of that coin BEFORE the route (0n if none)`);
222
+ return v;
223
+ };
224
+ const all = [];
225
+ q.hops.forEach((hq, i) => {
226
+ const hop = hq.hop;
227
+ const out = [];
228
+ all.push(out);
229
+ if (hop.kind === "edge") {
230
+ if (!isWrapHopV2(hop)) out.push(...edgeLegInstructions(edges.shift() ));
231
+ else if (hop.from === SOL_NATIVE) out.push(systemTransferInstruction({ from: p.trader, to: wsolAta, lamports: hq.amountIn }), syncNativeInstruction(wsolAta));
232
+ else out.push(closeAccountInstruction({ account: wsolAta, destination: p.trader, owner: p.trader, tokenProgram: TOKEN_PROGRAM_ID }));
233
+ return;
234
+ }
235
+ const pool = hop.pool;
236
+ const a = { ...routeTradeAccountsV2(p.trader, pool, quoteProgramOf(pool, pools), programId), quoteIsLaunch: pool.quoteIsLaunch ?? pools.some((x) => coinKey(x.token) === coinKey(pool.quote)) };
237
+ if (hq.hop.kind === "buy") {
238
+ out.push(i === 0 ? buyInstructionV2({ ...a, amountIn: hq.amountIn, minOut: hq.minOut }) : buyFromBalanceInstructionV2({ ...a, keep: bal(pool.quote), minOut: hq.minOut }));
239
+
240
+ const prev = i > 0 ? q.hops[i - 1].hop : null;
241
+ if (prev && isWrapHopV2(prev) && bal(WSOL_MINT) === 0n) out.push(closeAccountInstruction({ account: wsolAta, destination: p.trader, owner: p.trader, tokenProgram: TOKEN_PROGRAM_ID }));
242
+ if (i === q.hops.length - 1 && !p.hasPosition && canHoldPosition(p.trader)) out.push(openHolderPositionInstruction({ owner: p.trader, launch: a.launch, ownerBase: a.traderBase, programId }));
243
+ } else {
244
+ out.push(i === 0 ? sellInstructionV2({ ...a, tokensIn: hq.amountIn, minOut: hq.minOut }) : sellFromBalanceInstructionV2({ ...a, keep: bal(pool.token), minOut: hq.minOut }));
245
+ }
246
+ });
247
+ return all;
248
+ }
249
+
250
+ export const ATA_CREATE_CU = 16_261;
251
+
252
+ export function solPaidBuyInstructionsV2(p
253
+
254
+ ) {
255
+ if ((p.jupiter === undefined) === (p.edge === undefined)) throw new RangeError("pass the edge leg once: `edge` or `jupiter`");
256
+ const e = p.edge ?? jupiterEdgeLeg(p.jupiter );
257
+ if (!p.pool.quoteTokenProgram) throw new RangeError(`pool ${p.pool.symbol}: quoteTokenProgram is required`);
258
+ const { minOut } = p;
259
+ if (minOut < 1n) throw new RangeError("minOut must be ≥ 1");
260
+ const programId = p.programId ?? FLOOR_AMM_PROGRAM_ID;
261
+ const a = { ...routeTradeAccountsV2(p.trader, p.pool, p.pool.quoteTokenProgram, programId), quoteIsLaunch: p.pool.quoteIsLaunch ?? false };
262
+ const limit = p.computeUnitLimit
263
+ ?? (p.pool.snipeSpan || e.computeUnits === undefined || p.buyComputeUnits === undefined ? MAX_COMPUTE_UNIT_LIMIT : computeUnitLimitFor(e.computeUnits + p.buyComputeUnits + ATA_CREATE_CU));
264
+ const budget = [computeUnitLimitInstruction(limit)];
265
+ const price = p.microLamports ?? e.computeUnitPrice;
266
+ if (price !== undefined) budget.push(computeUnitPriceInstruction(price));
267
+ const rest = [
268
+ createAssociatedTokenAccountIdempotentInstruction({ payer: p.trader, owner: p.trader, mint: p.pool.token, tokenProgram: TOKEN_2022_PROGRAM_ID }),
269
+ ...e.setup,
270
+ ...e.swap,
271
+ buyFromBalanceInstructionV2({ ...a, keep: p.keep, minOut }),
272
+ ...(!p.hasPosition && canHoldPosition(p.trader) ? [openHolderPositionInstruction({ owner: p.trader, launch: a.launch, ownerBase: a.traderBase, programId })] : []),
273
+ ...e.cleanup,
274
+ ];
275
+ for (const ix of rest) if (ix.programAddress === COMPUTE_BUDGET_PROGRAM_ID) throw new RangeError("a compute budget instruction outside the budget slot");
276
+ return { instructions: [...budget, ...rest], lookupTableAddresses: [...e.lookupTableAddresses] };
277
+ }
278
+
279
+ export function routedBuyMessageV2(p ) {
280
+ const message = compileV0Message({ payer: p.trader, instructions: p.routed.instructions, recentBlockhash: p.recentBlockhash, lookupTables: p.lookupTables });
281
+ const size = transactionSize(message);
282
+ return { message, size, fits: size <= PACKET_DATA_SIZE };
283
+ }
284
+
285
+ const DUMMY_BLOCKHASH = "11111111111111111111111111111111";
286
+
287
+ export function routeTransactionsV2(p ) {
288
+ const q = p.quote;
289
+ const per = hopInstructionsV2(p);
290
+ if (p.computeUnits && p.computeUnits.length !== q.hops.length) throw new RangeError(`computeUnits: one entry per path hop (${q.hops.length}), not ${p.computeUnits.length}`);
291
+ for (const u of p.computeUnits ?? []) if (u !== undefined && (!Number.isInteger(u) || u < 0)) throw new RangeError("computeUnits must be whole numbers");
292
+ const pools = q.hops.flatMap((h) => (h.hop.kind === "edge" ? [] : [h.hop.pool]));
293
+ const edges = [...(p.edges ?? [])];
294
+
295
+ const segs = q.hops.map((hq, i) => {
296
+ const hop = hq.hop;
297
+ const given = p.computeUnits?.[i];
298
+ if (hop.kind === "edge") {
299
+ if (isWrapHopV2(hop)) return { ixs: per[i], atas: hop.from === SOL_NATIVE ? [{ mint: WSOL_MINT, tokenProgram: TOKEN_PROGRAM_ID }] : [], cu: given, luts: [], snipe: false };
300
+ const e = edges.shift() ;
301
+ return { ixs: per[i], atas: [], cu: given ?? e.computeUnits, price: e.computeUnitPrice, luts: [...e.lookupTableAddresses], snipe: false };
302
+ }
303
+ const atas = hop.kind === "buy" ? [{ mint: hop.pool.token, tokenProgram: TOKEN_2022_PROGRAM_ID }] : [{ mint: hop.pool.quote, tokenProgram: quoteProgramOf(hop.pool, pools) }];
304
+ return { ixs: per[i], atas, cu: given, luts: [], snipe: hop.pool.snipeSpan ?? false };
305
+ });
306
+ const atasOf = (ss ) => {
307
+ const atas = [];
308
+ for (const s of ss) for (const x of s.atas) if (!atas.some((y) => y.mint === x.mint && y.tokenProgram === x.tokenProgram)) atas.push(x);
309
+ return atas;
310
+ };
311
+ const known = (ss ) => ss.reduce((n, s) => n + (s.cu ?? 0), 0) + atasOf(ss).length * ATA_CREATE_CU;
312
+ const build = (ss , start ) => {
313
+ const limit = ss.some((s) => s.cu === undefined || s.snipe) ? MAX_COMPUTE_UNIT_LIMIT : computeUnitLimitFor(known(ss));
314
+ const budget = [computeUnitLimitInstruction(limit)];
315
+ const price = p.microLamports ?? ss.find((s) => s.price !== undefined)?.price;
316
+ if (price !== undefined) budget.push(computeUnitPriceInstruction(price));
317
+ const creates = atasOf(ss).map((x) => createAssociatedTokenAccountIdempotentInstruction({ payer: p.trader, owner: p.trader, mint: x.mint, tokenProgram: x.tokenProgram }));
318
+ return { instructions: [...budget, ...creates, ...ss.flatMap((s) => s.ixs)], lookupTableAddresses: [...new Set(ss.flatMap((s) => s.luts))], computeUnits: limit, hops: [start, start + ss.length] };
319
+ };
320
+ const packet = p.lookupTables !== undefined || segs.every((s) => s.luts.length === 0);
321
+ const fits = (ss , start ) => {
322
+ const units = known(ss);
323
+ if (units + Math.ceil(units / 10) > MAX_COMPUTE_UNIT_LIMIT) return false;
324
+ if (!packet) return true;
325
+ const message = compileV0Message({ payer: p.trader, instructions: build(ss, start).instructions, recentBlockhash: DUMMY_BLOCKHASH, lookupTables: p.lookupTables ?? [] });
326
+ return transactionSize(message) <= PACKET_DATA_SIZE;
327
+ };
328
+ const txs = [];
329
+ for (let start = 0; start < segs.length; ) {
330
+ let end = start;
331
+ while (end < segs.length && fits(segs.slice(start, end + 1), start)) end++;
332
+ if (end === start) throw new RangeError(`RouteTooLarge: hop ${start} alone does not fit one transaction (1.4M CU and the ${PACKET_DATA_SIZE}-byte packet); pass its lookup tables`);
333
+ txs.push(build(segs.slice(start, end), start));
334
+ start = end;
335
+ }
336
+ return txs;
337
+ }
338
+
339
+ export function routedTxMessageV2(p ) {
340
+ const message = compileV0Message({ payer: p.trader, instructions: p.tx.instructions, recentBlockhash: p.recentBlockhash, lookupTables: p.lookupTables });
341
+ const size = transactionSize(message);
342
+ return { message, size, fits: size <= PACKET_DATA_SIZE };
343
+ }
344
+
345
+ function floorHop (h ) {
346
+ if (h.kind === "edge") throw new RangeError("an EVM outside leg goes through the FloorRouter's DEX: use evmRouteCallV2 (direct FloorAmm calls take none)");
347
+ return h;
348
+ }
349
+
350
+ const v1Hop = (h ) => (h.kind === "edge" ? { ...h } : { kind: h.kind, pool: { ...h.pool, state: h.pool.launch } });
351
+
352
+ export function evmRouteCallV2(q , p ) {
353
+ if (q.path.chain !== "evm") throw new RangeError("evmRouteCallV2 builds EVM routes; Solana routes are `routeInstructionsV2`");
354
+ if (q.hops.length !== q.path.hops.length || q.hops.some((h, i) => h.hop !== q.path.hops[i])) throw new RangeError("the quote's hops are not its path's: quote the path again");
355
+ checkFloorHops(q.chainId, q.path.hops.filter((h) => h.kind !== "edge").length);
356
+
357
+ const v1 = {
358
+ path: { chain: "evm", from: q.path.from, to: q.path.to, hops: q.path.hops.map(v1Hop) },
359
+ amountIn: q.amountIn, amountOut: q.amountOut, minOut: q.minOut, slippageBps: q.slippageBps,
360
+ hops: q.hops.map((h) => ({ hop: v1Hop(h.hop), amountIn: h.amountIn, amountOut: h.amountOut, minOut: h.minOut })),
361
+ } ;
362
+ return evmRouteCall(v1, { router: p.router, to: p.to, deadline: p.deadline, chainId: q.chainId , ...(p.swapData ? { swapData: p.swapData } : {}) });
363
+ }
364
+
365
+ export function evmHopCallsV2(q , p ) {
366
+ if (q.path.chain !== "evm") throw new RangeError("evmHopCallsV2 builds EVM routes");
367
+ for (const h of q.path.hops) floorHop(h);
368
+
369
+ if (q.hops.length !== q.path.hops.length || q.hops.some((h, i) => h.hop !== q.path.hops[i])) throw new RangeError("the quote's hops are not its path's: quote the path again");
370
+ checkFloorHops(q.chainId, q.hops.length);
371
+ const calls = [];
372
+ let spend = q.amountIn;
373
+ for (const hq of q.hops) {
374
+ const hop = floorHop(hq.hop);
375
+ const pool = hop.pool;
376
+ if (pool.launchId === undefined) throw new RangeError(`pool ${pool.symbol}: an EVM pool needs its launchId`);
377
+ if (hop.kind === "buy") {
378
+ if (p.approve !== false && coinKey(pool.quote) !== EVM_NATIVE) calls.push(approveCall(pool.quote, p.floorAmm, spend));
379
+ calls.push(buyCall({ floorAmm: p.floorAmm, quote: pool.quote, launchId: pool.launchId, amountIn: spend, minTokensOut: hq.minOut, to: p.to, deadline: p.deadline }));
380
+ } else {
381
+
382
+ if (spend < EVM_TOKEN_SCALE) throw new RangeError(`SellBelowTokenScale: the sell of ${pool.symbol} would spend ${spend}, under one token (${EVM_TOKEN_SCALE}): the min-out of the hop before is too low for a direct call; lower the slippage or use the router`);
383
+ if (p.approve !== false) calls.push(approveCall(pool.token, p.floorAmm, spend));
384
+ calls.push(sellCall({ floorAmm: p.floorAmm, launchId: pool.launchId, tokensIn: spend, minQuoteOut: hq.minOut, to: p.to, deadline: p.deadline }));
385
+ }
386
+ spend = hq.minOut;
387
+ }
388
+ return calls;
389
+ }
@@ -0,0 +1,22 @@
1
+
2
+
3
+ export function isDustRefund(gross , refund , budgetHit ) {
4
+ return refund > 0n && !budgetHit && refund * 1_000_000n <= gross;
5
+ }
6
+
7
+ export function carriesNoRefund(gross , refund , budgetHit ) {
8
+ return refund === 0n || isDustRefund(gross, refund, budgetHit);
9
+ }
10
+
11
+ export const GAS_FLAT = { buy: 700_000, sell: 750_000 } ;
12
+
13
+ export const GAS_PER_STEP = { buy: 40_000, sell: 40_000 } ;
14
+
15
+ export const GAS_FLAT_STEPS = 4;
16
+
17
+ export const GAS_MAX = 1_500_000;
18
+
19
+ export function gasFor(side , steps ) {
20
+ const extra = Math.max(0, Math.trunc(steps) - GAS_FLAT_STEPS);
21
+ return Math.min(GAS_MAX, GAS_FLAT[side] + extra * GAS_PER_STEP[side]);
22
+ }