@floorlaunchpad/sdk 0.4.0 → 0.6.0

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 (89) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/dist/abi/evm.gen.js +5 -0
  3. package/dist/abi/functions.gen.js +1 -1
  4. package/dist/client/solana/index.js +13 -8
  5. package/dist/config/generated.js +78 -1
  6. package/dist/config/registry.gen.js +1 -1
  7. package/dist/evm/chains.js +56 -18
  8. package/dist/evm/squid.js +10 -10
  9. package/dist/evm/zap.js +148 -35
  10. package/dist/index.js +1 -0
  11. package/dist/indexer/bodies.js +9 -0
  12. package/dist/indexer/client.js +2 -0
  13. package/dist/indexer/contract.js +48 -2
  14. package/dist/indexer/paths.js +26 -0
  15. package/dist/indexer/read.js +3 -0
  16. package/dist/math/v2/book.js +40 -7
  17. package/dist/math/v2/create.js +1 -1
  18. package/dist/math/v2/relay.js +201 -1
  19. package/dist/math/v2/split.js +60 -15
  20. package/dist/math/v2/trade.js +16 -8
  21. package/dist/ton/addresses.js +36 -0
  22. package/dist/ton/book-check.js +23 -0
  23. package/dist/ton/book.js +119 -0
  24. package/dist/ton/cell.js +542 -0
  25. package/dist/ton/consts.generated.js +17 -0
  26. package/dist/ton/content.js +83 -0
  27. package/dist/ton/gas.js +198 -0
  28. package/dist/ton/governance.js +401 -0
  29. package/dist/ton/index.js +18 -0
  30. package/dist/ton/messages.js +340 -0
  31. package/dist/ton/ops.js +37 -0
  32. package/dist/ton/price.js +51 -0
  33. package/dist/ton/quote-entry.js +116 -0
  34. package/dist/ton/quote.js +25 -0
  35. package/dist/ton/reader.js +378 -0
  36. package/dist/ton/types.js +43 -0
  37. package/dist/ton/wallet.js +26 -0
  38. package/dist/v2/devbuy.js +6 -4
  39. package/dist/v2/evm.js +3 -1
  40. package/dist/v2/layouts.js +5 -1
  41. package/dist/v2/presetRowEvm.js +21 -2
  42. package/dist/v2/router.js +2 -2
  43. package/dist/v2/solanaSettle.js +2 -0
  44. package/docs/ton.md +107 -0
  45. package/examples/floor-line.html +1 -1
  46. package/package.json +6 -1
  47. package/src/abi/evm.gen.ts +5 -0
  48. package/src/abi/functions.gen.ts +1 -1
  49. package/src/client/solana/index.ts +13 -8
  50. package/src/config/generated.ts +78 -1
  51. package/src/config/registry.gen.ts +1 -1
  52. package/src/evm/chains.ts +63 -17
  53. package/src/evm/squid.ts +10 -10
  54. package/src/evm/zap.ts +185 -36
  55. package/src/index.ts +1 -0
  56. package/src/indexer/bodies.ts +11 -0
  57. package/src/indexer/client.ts +5 -1
  58. package/src/indexer/contract.ts +48 -2
  59. package/src/indexer/paths.ts +47 -0
  60. package/src/indexer/read.ts +5 -2
  61. package/src/math/v2/book.ts +42 -7
  62. package/src/math/v2/create.ts +1 -1
  63. package/src/math/v2/relay.ts +208 -1
  64. package/src/math/v2/split.ts +70 -16
  65. package/src/math/v2/trade.ts +16 -8
  66. package/src/ton/addresses.ts +38 -0
  67. package/src/ton/book-check.ts +24 -0
  68. package/src/ton/book.ts +136 -0
  69. package/src/ton/cell.ts +547 -0
  70. package/src/ton/consts.generated.ts +17 -0
  71. package/src/ton/content.ts +97 -0
  72. package/src/ton/gas.ts +209 -0
  73. package/src/ton/governance.ts +452 -0
  74. package/src/ton/index.ts +18 -0
  75. package/src/ton/messages.ts +343 -0
  76. package/src/ton/ops.ts +37 -0
  77. package/src/ton/price.ts +54 -0
  78. package/src/ton/quote-entry.ts +138 -0
  79. package/src/ton/quote.ts +67 -0
  80. package/src/ton/reader.ts +420 -0
  81. package/src/ton/types.ts +201 -0
  82. package/src/ton/wallet.ts +30 -0
  83. package/src/v2/devbuy.ts +6 -4
  84. package/src/v2/evm.ts +5 -1
  85. package/src/v2/layouts.ts +5 -1
  86. package/src/v2/presetRowEvm.ts +21 -2
  87. package/src/v2/router.ts +2 -2
  88. package/src/v2/solanaSettle.ts +2 -0
  89. package/src/v2/types.ts +4 -1
package/dist/evm/zap.js CHANGED
@@ -3,14 +3,23 @@
3
3
  import { bytesToHex, checksumAddress, encodeAbi, hexToBytes } from "./abi.js";
4
4
  import { encodeFunctionData } from "./items.js";
5
5
 
6
+ export const AERODROME_SLIPSTREAM_KEY = 0x100000;
7
+
6
8
  export const UR_V3_SWAP_EXACT_IN = 0x00;
7
9
  export const UR_V2_SWAP_EXACT_IN = 0x08;
8
10
  export const UR_WRAP_ETH = 0x0b;
9
11
  export const UR_UNWRAP_WETH = 0x0c;
10
12
  export const UR_SWEEP = 0x04;
13
+ export const UR_V4_SWAP = 0x10;
11
14
  export const UR_MSG_SENDER = "0x0000000000000000000000000000000000000001";
12
15
  export const UR_ADDRESS_THIS = "0x0000000000000000000000000000000000000002";
13
16
 
17
+ export const V4_SWAP_EXACT_IN_SINGLE = 0x06;
18
+ export const V4_SETTLE = 0x0b;
19
+ export const V4_TAKE = 0x0e;
20
+ export const V4_OPEN_DELTA = 0n;
21
+ export const V4_NATIVE = "0x0000000000000000000000000000000000000000";
22
+
14
23
  const fn = (name , inputs ) => ({ type: "function", name, inputs, outputs: [], stateMutability: "payable" }) ;
15
24
  const tup = (fields ) => fields.map(([name, type]) => ({ name, type }));
16
25
 
@@ -33,34 +42,131 @@ export function algebraPath(tokens ) {
33
42
  return "0x" + tokens.map((t) => bytesToHex(hexToBytes(t)).slice(2)).join("");
34
43
  }
35
44
 
45
+ const UR_FORKS = ["uniswap", "aerodrome", "pancake", "ramses"];
46
+
47
+ const isNative = (a ) => BigInt(checksumAddress(a)) === 0n;
48
+
36
49
  const checkRoute = (p ) => {
37
50
  if (p.amountIn <= 0n) throw new RangeError("amountIn must be > 0");
38
51
  if (p.minQuoteOut <= 0n) throw new RangeError("minQuoteOut must be > 0 (the NO_MINIMUM rule)");
39
- if (p.route.tokens.length < 2) throw new RangeError("a route is at least two tokens");
52
+ const { tokens } = p.route;
53
+ if (tokens.length < 2) throw new RangeError("a route is at least two tokens");
54
+ if (p.input !== undefined && p.input !== "native" && p.input !== "token") throw new RangeError(`input ${String(p.input)} is "native" or "token"`);
55
+ if (p.output !== undefined && p.output !== "native" && p.output !== "token") throw new RangeError(`output ${String(p.output)} is "native" or "token"`);
56
+ if (p.urFork !== undefined && (p.family !== "uniswap-ur" || !UR_FORKS.includes(p.urFork))) {
57
+ throw new RangeError(`urFork ${String(p.urFork)} names a uniswap-ur row's router: ${UR_FORKS.join(", ")}`);
58
+ }
59
+ const [first, last] = [tokens[0], tokens[tokens.length - 1]];
60
+ if (BigInt(checksumAddress(first)) === BigInt(checksumAddress(last))) throw new RangeError("a route swaps a coin into itself");
61
+ if (p.route.v4) {
62
+ if (p.family !== "uniswap-ur") throw new RangeError("a v4 route goes through the Universal Router (uniswap-ur)");
63
+ if ((p.urFork ?? "uniswap") !== "uniswap") throw new RangeError("a v4 route goes through Uniswap's own Universal Router");
64
+ const ends = { nativeIn: isNative(first), nativeOut: isNative(last) };
65
+ if (p.input !== undefined && (p.input === "native") !== ends.nativeIn) throw new RangeError(`input "${p.input}" is not the v4 route's first currency`);
66
+ if (p.output !== undefined && (p.output === "native") !== ends.nativeOut) throw new RangeError(`output "${p.output}" is not the v4 route's last currency`);
67
+ return ends;
68
+ }
69
+ if (tokens.some(isNative)) throw new RangeError("a V2 / V3 route names the wrapped native, never address(0) (only a v4 route holds the native coin)");
70
+ const ends = { nativeIn: (p.input ?? "native") === "native", nativeOut: (p.output ?? "token") === "native" };
71
+ if (ends.nativeIn && ends.nativeOut) throw new RangeError("a route swaps the native coin into itself");
72
+ return ends;
40
73
  };
41
74
 
42
- function universalRouter(p ) {
43
- const wrap = bytesToHex(encodeAbi(["address", "uint256"], [UR_ADDRESS_THIS, p.amountIn]));
44
- let cmd ;
45
- let swap ;
75
+ export function v4PoolKey(tokenIn , tokenOut , pool ) {
76
+ const a = checksumAddress(tokenIn);
77
+ const b = checksumAddress(tokenOut);
78
+ if (BigInt(a) === BigInt(b)) throw new RangeError("a v4 swap is between two different currencies");
79
+ if (!Number.isInteger(pool.fee) || pool.fee < 0 || pool.fee >= 1 << 24) throw new RangeError(`fee ${pool.fee} is not a uint24`);
80
+ if (!Number.isInteger(pool.tickSpacing) || pool.tickSpacing < 1 || pool.tickSpacing > 32767) throw new RangeError(`tick spacing ${pool.tickSpacing} is not 1 ..= 32767`);
81
+ const zeroForOne = BigInt(a) < BigInt(b);
82
+ const hooks = checksumAddress(pool.hooks ?? V4_NATIVE);
83
+ return { key: { currency0: zeroForOne ? a : b, currency1: zeroForOne ? b : a, fee: pool.fee, tickSpacing: pool.tickSpacing, hooks }, zeroForOne };
84
+ }
85
+
86
+ const UINT128 = 1n << 128n;
87
+ const UR_EXECUTE = [fn("execute", [{ name: "commands", type: "bytes" }, { name: "inputs", type: "bytes[]" }, { name: "deadline", type: "uint256" }])];
88
+ const cmds = (cs ) => "0x" + cs.map((c) => c.toString(16).padStart(2, "0")).join("");
89
+
90
+ function universalRouterV4(p , pool ) {
91
+ const { tokens } = p.route;
92
+ if (tokens.length !== 2) throw new RangeError("a v4 route is one pool: [currency in, currency out]");
93
+ if (p.route.fees || p.route.stable || p.route.factory) throw new RangeError("a v4 route names its pool in `v4` only");
94
+ if (p.amountIn >= UINT128 || p.minQuoteOut >= UINT128) throw new RangeError("a v4 amount is a uint128");
95
+ const [tokenIn, tokenOut] = tokens;
96
+ const { key, zeroForOne } = v4PoolKey(tokenIn, tokenOut, pool);
97
+ const nativeOut = isNative(tokenOut);
98
+ const swap = encodeAbi(
99
+ ["((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"],
100
+ [[[key.currency0, key.currency1, BigInt(key.fee), BigInt(key.tickSpacing), key.hooks], zeroForOne, p.amountIn, p.minQuoteOut, 0n, pool.hookData ?? "0x"]],
101
+ );
102
+ const settle = encodeAbi(["address", "uint256", "bool"], [checksumAddress(tokenIn), V4_OPEN_DELTA, false]);
103
+ const take = encodeAbi(["address", "address", "uint256"], [checksumAddress(tokenOut), nativeOut ? UR_ADDRESS_THIS : UR_MSG_SENDER, V4_OPEN_DELTA]);
104
+ const v4 = bytesToHex(encodeAbi(["bytes", "bytes[]"], [cmds([V4_SWAP_EXACT_IN_SINGLE, V4_SETTLE, V4_TAKE]), [swap, settle, take]]));
105
+
106
+ const nativeIn = isNative(tokenIn);
107
+ const sweep = (min ) => bytesToHex(encodeAbi(["address", "address", "uint256"], [V4_NATIVE, UR_MSG_SENDER, min]));
108
+ const inputs = nativeOut ? [v4, sweep(p.minQuoteOut)] : nativeIn ? [v4, sweep(0n)] : [v4];
109
+ return encodeFunctionData(UR_EXECUTE, "execute", { commands: cmds(nativeOut ? [UR_V4_SWAP, UR_SWEEP] : nativeIn ? [UR_V4_SWAP, UR_SWEEP] : [UR_V4_SWAP]), inputs, deadline: p.deadline });
110
+ }
111
+
112
+ const UR_SWAP_HEAD = ["address", "uint256", "uint256", "bytes", "bool"];
113
+
114
+ function aerodromeKey(k ) {
115
+ if (!Number.isInteger(k) || k < 1 || k >= 1 << 24) throw new RangeError(`Aerodrome key ${k} is not a tick spacing`);
116
+ if (k < AERODROME_SLIPSTREAM_KEY) return AERODROME_SLIPSTREAM_KEY | k;
117
+ if (k >>> 20 !== 1) throw new RangeError(`Aerodrome key ${k} names another factory than Slipstream's (0x100000 | tickSpacing)`);
118
+ return k;
119
+ }
120
+
121
+ function universalRouter(p , e ) {
122
+ const fork = p.urFork ?? "uniswap";
123
+ const to = e.nativeOut ? UR_ADDRESS_THIS : UR_MSG_SENDER;
124
+ const commands = [];
125
+ const inputs = [];
126
+ if (e.nativeIn) {
127
+ commands.push(UR_WRAP_ETH);
128
+ inputs.push(bytesToHex(encodeAbi(["address", "uint256"], [UR_ADDRESS_THIS, p.amountIn])));
129
+ }
46
130
  if (p.route.fees) {
47
- cmd = UR_V3_SWAP_EXACT_IN;
48
- swap = bytesToHex(encodeAbi(["address", "uint256", "uint256", "bytes", "bool", "uint256[]"], [UR_MSG_SENDER, p.amountIn, p.minQuoteOut, v3Path(p.route.tokens, p.route.fees), false, []]));
131
+ const keys = fork === "aerodrome" ? p.route.fees.map(aerodromeKey) : p.route.fees;
132
+ const head = [to, p.amountIn, p.minQuoteOut, v3Path(p.route.tokens, keys), false];
133
+ const swap = fork === "uniswap" ? encodeAbi([...UR_SWAP_HEAD, "uint256[]"], [...head, []])
134
+ : fork === "aerodrome" ? encodeAbi([...UR_SWAP_HEAD, "bool"], [...head, false])
135
+ : encodeAbi(UR_SWAP_HEAD, head);
136
+ commands.push(UR_V3_SWAP_EXACT_IN);
137
+ inputs.push(bytesToHex(swap));
49
138
  } else {
50
- cmd = UR_V2_SWAP_EXACT_IN;
51
- swap = bytesToHex(encodeAbi(["address", "uint256", "uint256", "address[]", "bool", "uint256[]"], [UR_MSG_SENDER, p.amountIn, p.minQuoteOut, [...p.route.tokens], false, []]));
139
+ if (fork !== "uniswap") throw new RangeError(`a V2 leg through ${fork}'s Universal Router is not spelled (its V2_SWAP_EXACT_IN input is its own)`);
140
+ commands.push(UR_V2_SWAP_EXACT_IN);
141
+ inputs.push(bytesToHex(encodeAbi(["address", "uint256", "uint256", "address[]", "bool", "uint256[]"], [to, p.amountIn, p.minQuoteOut, [...p.route.tokens], false, []])));
52
142
  }
53
- const commands = "0x" + [UR_WRAP_ETH, cmd].map((c) => c.toString(16).padStart(2, "0")).join("");
54
- const abi = [fn("execute", [{ name: "commands", type: "bytes" }, { name: "inputs", type: "bytes[]" }, { name: "deadline", type: "uint256" }])];
55
- return encodeFunctionData(abi, "execute", { commands, inputs: [wrap, swap], deadline: p.deadline });
143
+ if (e.nativeOut) {
144
+ commands.push(UR_UNWRAP_WETH);
145
+ inputs.push(bytesToHex(encodeAbi(["address", "uint256"], [UR_MSG_SENDER, p.minQuoteOut])));
146
+ }
147
+ if (e.nativeIn) {
148
+
149
+ commands.push(UR_SWEEP);
150
+ inputs.push(bytesToHex(encodeAbi(["address", "address", "uint256"], [V4_NATIVE, UR_MSG_SENDER, 0n])));
151
+ }
152
+ return encodeFunctionData(UR_EXECUTE, "execute", { commands: cmds(commands), inputs, deadline: p.deadline });
56
153
  }
57
154
 
155
+ const ADDRESS_ZERO = "0x0000000000000000000000000000000000000000";
58
156
  const REFUND_ETH = [fn("refundETH", [])];
59
157
  const REFUND_NATIVE = [fn("refundNativeToken", [])];
158
+ const UNWRAP = (name ) => [fn(name, [{ name: "amountMinimum", type: "uint256" }, { name: "recipient", type: "address" }])];
60
159
 
61
- function v3Router(p , v02 ) {
160
+ const peripheryTail = (p , e , refund , unwrap ) =>
161
+ e.nativeIn ? [encodeFunctionData(refund === "refundETH" ? REFUND_ETH : REFUND_NATIVE, refund)]
162
+ : e.nativeOut ? [encodeFunctionData(UNWRAP(unwrap), unwrap, { amountMinimum: p.minQuoteOut, recipient: p.zap })]
163
+ : [];
164
+
165
+ function v3Router(p , v02 , e ) {
62
166
  const fees = p.route.fees;
63
167
  if (!fees) throw new RangeError("a V3 router route needs its fees");
168
+ if (e.nativeOut && !v02 && !p.router) throw new RangeError("a SwapRouter v1 native out is paid to the router, then unwrapped: pass the zap's `router`");
169
+ const recipient = !e.nativeOut ? p.zap : v02 ? UR_ADDRESS_THIS : checksumAddress(p.router );
64
170
  const [tokenIn, tokenOut] = [p.route.tokens[0], p.route.tokens[p.route.tokens.length - 1]];
65
171
  let swap ;
66
172
  if (p.route.tokens.length === 2) {
@@ -68,61 +174,68 @@ function v3Router(p , v02 ) {
68
174
  ? [["tokenIn", "address"], ["tokenOut", "address"], ["fee", "uint24"], ["recipient", "address"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"], ["sqrtPriceLimitX96", "uint160"]]
69
175
  : [["tokenIn", "address"], ["tokenOut", "address"], ["fee", "uint24"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"], ["sqrtPriceLimitX96", "uint160"]];
70
176
  const abi = [fn("exactInputSingle", [{ name: "params", type: "tuple", components: tup(fields) }])];
71
- swap = encodeFunctionData(abi, "exactInputSingle", { params: { tokenIn, tokenOut, fee: BigInt(fees[0]), recipient: p.zap, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut, sqrtPriceLimitX96: 0n } });
177
+ swap = encodeFunctionData(abi, "exactInputSingle", { params: { tokenIn, tokenOut, fee: BigInt(fees[0]), recipient, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut, sqrtPriceLimitX96: 0n } });
72
178
  } else {
73
179
  const fields = v02
74
180
  ? [["path", "bytes"], ["recipient", "address"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"]]
75
181
  : [["path", "bytes"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"]];
76
182
  const abi = [fn("exactInput", [{ name: "params", type: "tuple", components: tup(fields) }])];
77
- swap = encodeFunctionData(abi, "exactInput", { params: { path: v3Path(p.route.tokens, fees), recipient: p.zap, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut } });
183
+ swap = encodeFunctionData(abi, "exactInput", { params: { path: v3Path(p.route.tokens, fees), recipient, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut } });
78
184
  }
79
- const refund = encodeFunctionData(REFUND_ETH, "refundETH");
80
- if (v02) return encodeFunctionData([fn("multicall", [{ name: "deadline", type: "uint256" }, { name: "data", type: "bytes[]" }])], "multicall", { deadline: p.deadline, data: [swap, refund] });
81
- return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data: [swap, refund] });
185
+ const data = [swap, ...peripheryTail(p, e, "refundETH", "unwrapWETH9")];
186
+ if (v02) return encodeFunctionData([fn("multicall", [{ name: "deadline", type: "uint256" }, { name: "data", type: "bytes[]" }])], "multicall", { deadline: p.deadline, data });
187
+ return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data });
82
188
  }
83
189
 
84
- function algebra(p ) {
190
+ function algebra(p , e ) {
191
+ const recipient = e.nativeOut ? ADDRESS_ZERO : p.zap;
85
192
  const [tokenIn, tokenOut] = [p.route.tokens[0], p.route.tokens[p.route.tokens.length - 1]];
86
193
  let swap ;
87
194
  if (p.route.tokens.length === 2) {
88
195
  const fields = [["tokenIn", "address"], ["tokenOut", "address"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"], ["limitSqrtPrice", "uint160"]];
89
- swap = encodeFunctionData([fn("exactInputSingle", [{ name: "params", type: "tuple", components: tup(fields) }])], "exactInputSingle", { params: { tokenIn, tokenOut, recipient: p.zap, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut, limitSqrtPrice: 0n } });
196
+ swap = encodeFunctionData([fn("exactInputSingle", [{ name: "params", type: "tuple", components: tup(fields) }])], "exactInputSingle", { params: { tokenIn, tokenOut, recipient, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut, limitSqrtPrice: 0n } });
90
197
  } else {
91
198
  const fields = [["path", "bytes"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"]];
92
- swap = encodeFunctionData([fn("exactInput", [{ name: "params", type: "tuple", components: tup(fields) }])], "exactInput", { params: { path: algebraPath(p.route.tokens), recipient: p.zap, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut } });
199
+ swap = encodeFunctionData([fn("exactInput", [{ name: "params", type: "tuple", components: tup(fields) }])], "exactInput", { params: { path: algebraPath(p.route.tokens), recipient, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut } });
93
200
  }
94
- return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data: [swap, encodeFunctionData(REFUND_NATIVE, "refundNativeToken")] });
201
+ return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data: [swap, ...peripheryTail(p, e, "refundNativeToken", "unwrapWNativeToken")] });
95
202
  }
96
203
 
97
- function v2Router(p ) {
98
- const abi = [fn("swapExactETHForTokens", tup([["amountOutMin", "uint256"], ["path", "address[]"], ["to", "address"], ["deadline", "uint256"]]))];
99
- return encodeFunctionData(abi, "swapExactETHForTokens", { amountOutMin: p.minQuoteOut, path: [...p.route.tokens], to: p.zap, deadline: p.deadline });
204
+ const v2Name = (e ) => (e.nativeIn ? "swapExactETHForTokens" : e.nativeOut ? "swapExactTokensForETH" : "swapExactTokensForTokens");
205
+
206
+ function v2Router(p , e ) {
207
+ const name = v2Name(e);
208
+ const head = e.nativeIn ? [] : [["amountIn", "uint256"]];
209
+ const abi = [fn(name, tup([...head, ["amountOutMin", "uint256"], ["path", "address[]"], ["to", "address"], ["deadline", "uint256"]]))];
210
+ return encodeFunctionData(abi, name, { amountIn: p.amountIn, amountOutMin: p.minQuoteOut, path: [...p.route.tokens], to: p.zap, deadline: p.deadline });
100
211
  }
101
212
 
102
- function aerodromeV2(p ) {
213
+ function aerodromeV2(p , e ) {
103
214
  const { tokens, stable, factory } = p.route;
104
215
  if (!stable || stable.length !== tokens.length - 1 || !factory) throw new RangeError("an Aerodrome route needs a stable flag per hop and the factory");
105
216
  const route = { name: "routes", type: "tuple[]", components: tup([["from", "address"], ["to", "address"], ["stable", "bool"], ["factory", "address"]]) };
106
- const abi = [fn("swapExactETHForTokens", [{ name: "amountOutMin", type: "uint256" }, route, { name: "to", type: "address" }, { name: "deadline", type: "uint256" }])];
217
+ const name = v2Name(e);
218
+ const head = e.nativeIn ? [] : [{ name: "amountIn", type: "uint256" }];
219
+ const abi = [fn(name, [...head, { name: "amountOutMin", type: "uint256" }, route, { name: "to", type: "address" }, { name: "deadline", type: "uint256" }])];
107
220
  const routes = stable.map((s, i) => ({ from: tokens[i], to: tokens[i + 1], stable: s, factory }));
108
- return encodeFunctionData(abi, "swapExactETHForTokens", { amountOutMin: p.minQuoteOut, routes, to: p.zap, deadline: p.deadline });
221
+ return encodeFunctionData(abi, name, { amountIn: p.amountIn, amountOutMin: p.minQuoteOut, routes, to: p.zap, deadline: p.deadline });
109
222
  }
110
223
 
111
224
  export function zapSwapData(p ) {
112
- checkRoute(p);
225
+ const e = checkRoute(p);
113
226
  checksumAddress(p.zap);
114
227
  switch (p.family) {
115
228
  case "uniswap-ur":
116
- return universalRouter(p);
229
+ return p.route.v4 ? universalRouterV4(p, p.route.v4) : universalRouter(p, e);
117
230
  case "v3-router":
118
- return v3Router(p, false);
231
+ return v3Router(p, false, e);
119
232
  case "v3-router02":
120
- return v3Router(p, true);
233
+ return v3Router(p, true, e);
121
234
  case "algebra":
122
- return algebra(p);
235
+ return algebra(p, e);
123
236
  case "v2-router":
124
- return v2Router(p);
237
+ return v2Router(p, e);
125
238
  case "aerodrome-v2":
126
- return aerodromeV2(p);
239
+ return aerodromeV2(p, e);
127
240
  }
128
241
  }
package/dist/index.js CHANGED
@@ -87,6 +87,7 @@ export * as abi from "./abi/index.js";
87
87
  export * as v2Press from "./v2/press.js";
88
88
  export * as v2ReceiptTx from "./v2/receipt-tx.js";
89
89
  export * as config from "./config/index.js";
90
+ export * as ton from "./ton/index.js";
90
91
  export * as fixtures from "./fixtures.js";
91
92
  export * as client from "./client/index.js";
92
93
  export * as errors from "./errors.js";
@@ -123,6 +123,10 @@ const LISTED_FIELDS = {
123
123
  volume24hGross: nullable(big),
124
124
  holders: int,
125
125
 
126
+ newHolders1h: optional(nullable(int)),
127
+
128
+ newHolders24h: optional(nullable(int)),
129
+
126
130
  maxLossPpm: optional(nullable(int)),
127
131
 
128
132
  backedPpm: nullable(int),
@@ -251,6 +255,9 @@ export const LAUNCHES = object({
251
255
  cursors: perRow(str), keys: perRow(nullable(str)), next: optional(nullable(str)),
252
256
  });
253
257
 
258
+ export const LAUNCH_LIST = object({ quote: str, total: int, launches: array(LISTED_LAUNCH), cursors: array(str), keys: array(nullable(str)), next: nullable(str) });
259
+ export const LAUNCH_LISTS = object({ indexed, lists: array(LAUNCH_LIST) });
260
+
254
261
  const SEARCH_SERVED_TIER = (v, p) => {
255
262
  const n = int(v, p);
256
263
  if (n < 0 || n > 4) throw new ShapeError(p, "a tier 0..4", v);
@@ -330,6 +337,8 @@ export const CANDLES = object({
330
337
  candles: array(CANDLE),
331
338
  });
332
339
 
340
+ export const CANDLES_MANY = object({ indexed, interval: str, series: array(CANDLES), missing: array(str) });
341
+
333
342
  export const CANDLE_BUNDLE = object({
334
343
  indexed,
335
344
  launch: str,
@@ -21,6 +21,7 @@ export const routePath = {
21
21
  floorRouted: (a) => indexerPath.floorRouted(a ?? {}),
22
22
  events: (a) => indexerPath.events(a.fromBlock, a.toBlock),
23
23
  launches: (a) => indexerPath.launches(a ?? {}),
24
+ launchLists: (a) => indexerPath.launchLists(a),
24
25
  search: (a) => indexerPath.search(a),
25
26
  launch: (a) => indexerPath.launch(a.launch),
26
27
  launchState: (a) => indexerPath.launchState(a.launch),
@@ -40,6 +41,7 @@ export const routePath = {
40
41
  price: (a) => indexerPath.price(a.launch),
41
42
  highs: ({ launch, ...q }) => indexerPath.highs(launch, q),
42
43
  candles: (a) => indexerPath.candles(a),
44
+ candlesMany: (a) => indexerPath.candlesMany(a),
43
45
  candleBundle: ({ launch, ...q }) => indexerPath.candleBundle(launch, q),
44
46
  walletTrades: ({ wallet, ...q }) => indexerPath.walletTrades(wallet, q),
45
47
  tonActivity: ({ wallet, ...q }) => indexerPath.tonActivity(wallet, q),
@@ -3,7 +3,7 @@
3
3
  import { unknown } from "./decode.js";
4
4
  import * as B from "./bodies.js";
5
5
  import * as P from "./partners.js";
6
- import { FIRSTS_MAX, IDS_MAX, INBOX_PAGE_DEFAULT, INBOX_PAGE_MAX, LAUNCHES_PAGE_DEFAULT, LAUNCHES_PAGE_MAX, LAUNCH_CURSOR_MAX, LAUNCH_SORTS, PRESET_FILTER_MAX, STREAM_STATE_MAX, WALLET_CURSOR_MAX, WALLET_PAGE_DEFAULT, WALLET_PAGE_MAX } from "./paths.js";
6
+ import { CANDLES_MANY_IDS_MAX, CANDLES_MANY_LIMIT_DEFAULT, CANDLES_MANY_ROWS_MAX, FIRSTS_MAX, IDS_MAX, LAUNCH_LISTS_QUOTES_MAX, LAUNCH_LISTS_ROWS_MAX, INBOX_PAGE_DEFAULT, INBOX_PAGE_MAX, LAUNCHES_PAGE_DEFAULT, LAUNCHES_PAGE_MAX, LAUNCH_CURSOR_MAX, LAUNCH_SORTS, PRESET_FILTER_MAX, STREAM_STATE_MAX, WALLET_CURSOR_MAX, WALLET_PAGE_DEFAULT, WALLET_PAGE_MAX } from "./paths.js";
7
7
  import { SEARCH_PAGE_DEFAULT, SEARCH_PAGE_MAX, SEARCH_Q_MAX } from "./search.js";
8
8
 
9
9
  export const UNITS = {
@@ -148,6 +148,25 @@ export const INDEXER_CONTRACT = {
148
148
  errors: [...GATED, "bad_query"],
149
149
  body: B.LAUNCHES,
150
150
  }),
151
+
152
+ launchLists: site({
153
+ pattern: "/floor-amm/launch-lists",
154
+ v2: true,
155
+ query: {
156
+ quotes: { kind: "list", doc: "one list per quote coin, in this order (no repeat)", required: true, min: 1, max: LAUNCH_LISTS_QUOTES_MAX },
157
+ cursors: { kind: "list", doc: "parallel to quotes, one each: that list's page next (- = its first page)", max: LAUNCH_LISTS_QUOTES_MAX },
158
+ sort: { kind: "enum", doc: "the order (larger first with order=desc)", values: LAUNCH_SORTS, default: "created" },
159
+ order: { kind: "enum", doc: "asc or desc", values: ["asc", "desc"], default: "desc" },
160
+ creator: { kind: "string", doc: "launches by this creator" },
161
+ rankable: { kind: "bool", doc: "true (or 1) listed only, false (or 0) unlisted only" },
162
+ graduated: { kind: "bool", doc: "graduated or not (true / false, or 1 / 0)" },
163
+ preset: PRESETS,
164
+ limit: LIMIT(LAUNCHES_PAGE_DEFAULT, LAUNCHES_PAGE_MAX),
165
+ },
166
+ page: limit(LAUNCHES_PAGE_DEFAULT, LAUNCHES_PAGE_MAX),
167
+ errors: [...GATED, "bad_query"],
168
+ body: B.LAUNCH_LISTS,
169
+ }),
151
170
  search: site({
152
171
  pattern: "/floor-amm/search",
153
172
  v2: true,
@@ -219,6 +238,20 @@ export const INDEXER_CONTRACT = {
219
238
  errors: [...GATED, "bad_query", "unknown_launch", "not_found"],
220
239
  body: B.CANDLES,
221
240
  }),
241
+
242
+ candlesMany: site({
243
+ pattern: "/floor-amm/candles/many",
244
+ aliases: ["/floor-amm/v2/candles/many"],
245
+ query: {
246
+ ids: { kind: "list", doc: "these launches (ids or tokens), one series each in the order asked", required: true, min: 1, max: CANDLES_MANY_IDS_MAX },
247
+ interval: { kind: "enum", doc: "the bucket", values: B.CANDLE_INTERVALS, default: "1h" },
248
+ before: { kind: "unix", doc: "the newest limit traded buckets starting before it (absent: past the indexed head)" },
249
+ limit: { kind: "int", doc: "buckets per launch", min: 1, max: B.CANDLES_MAX, default: CANDLES_MANY_LIMIT_DEFAULT },
250
+ },
251
+ page: limit(CANDLES_MANY_LIMIT_DEFAULT, B.CANDLES_MAX),
252
+ errors: [...GATED, "bad_query"],
253
+ body: B.CANDLES_MANY,
254
+ }),
222
255
  candleBundle: site({
223
256
  pattern: "/floor-amm/launches/<launch>/candle-bundle",
224
257
  v2: true,
@@ -429,6 +462,14 @@ export function queryRefusal(name , q )
429
462
  }
430
463
  }
431
464
 
465
+ const prod = ROWS_PRODUCT[name];
466
+ if (prod !== undefined) {
467
+ const n = (q.get(prod.list) ?? "").split(",").filter((s) => s !== "").length;
468
+ const raw = q.get("limit");
469
+ const lim = raw === null || raw === "" ? routeLimit(name) .default : Number(raw);
470
+ if (n * lim > prod.max) return `${prod.list} × limit must be at most ${prod.max} (asked ${n} × ${lim})`;
471
+ }
472
+
432
473
  const pg = INDEXER_CONTRACT[name].page;
433
474
  if (pg.kind === "cursor" && pg.optIn !== undefined && q.get(pg.cursor) !== null) {
434
475
  const raw = q.get("limit");
@@ -437,7 +478,12 @@ export function queryRefusal(name , q )
437
478
  return spanRefusal(name, q);
438
479
  }
439
480
 
440
- const TABLE_REQUIRED = new Set (["search"]);
481
+ const ROWS_PRODUCT = {
482
+ launchLists: { list: "quotes", max: LAUNCH_LISTS_ROWS_MAX },
483
+ candlesMany: { list: "ids", max: CANDLES_MANY_ROWS_MAX },
484
+ };
485
+
486
+ const TABLE_REQUIRED = new Set (["search", "launchLists", "candlesMany"]);
441
487
 
442
488
  const BOOLS = { true: true, false: false, 1: true, 0: false };
443
489
 
@@ -9,6 +9,7 @@ export const INDEXER_ROUTES = {
9
9
  floorRouted: { pattern: "/floor-amm/floor-routed", keys: ["limit", "cursor"] },
10
10
  events: { pattern: "/floor-amm/events", keys: ["fromBlock", "toBlock"] },
11
11
  launches: { pattern: "/floor-amm/launches", keys: ["sort", "order", "q", "ids", "quote", "creator", "rankable", "graduated", "preset", "limit", "cursor", "offset"] },
12
+ launchLists: { pattern: "/floor-amm/launch-lists", keys: ["quotes", "cursors", "sort", "order", "creator", "rankable", "graduated", "preset", "limit"] },
12
13
  search: { pattern: "/floor-amm/search", keys: ["q", "limit", "cursor", "rankable", "graduated", "quote", "preset"] },
13
14
  launch: { pattern: "/floor-amm/launches/<launch>", keys: [] },
14
15
  launchState: { pattern: "/floor-amm/launches/<launch>/state", keys: [] },
@@ -29,6 +30,7 @@ export const INDEXER_ROUTES = {
29
30
  highs: { pattern: "/floor-amm/launches/<launch>/highs", keys: ["atLeast", "limit"] },
30
31
  candleBundle: { pattern: "/floor-amm/launches/<launch>/candle-bundle", keys: ["intervals", "limit"] },
31
32
  candles: { pattern: "/floor-amm/candles", keys: ["launch", "interval", "from", "to", "before", "limit"] },
33
+ candlesMany: { pattern: "/floor-amm/candles/many", keys: ["ids", "interval", "before", "limit"] },
32
34
  walletTrades: { pattern: "/floor-amm/wallets/<wallet>/trades", keys: ["limit", "before", "launch"] },
33
35
  tonActivity: { pattern: "/floor-amm/wallets/<wallet>/ton-activity", keys: ["limit", "before"] },
34
36
  tonOutcome: { pattern: "/floor-amm/wallets/<wallet>/ton-outcome", keys: ["queryId"] },
@@ -54,6 +56,15 @@ export const LAUNCHES_PAGE_MAX = 1_000;
54
56
 
55
57
  export const LAUNCHES_PAGE_DEFAULT = 100;
56
58
 
59
+ export const LAUNCH_LISTS_QUOTES_MAX = 16;
60
+ export const LAUNCH_LISTS_ROWS_MAX = 1_000;
61
+
62
+ export const LAUNCH_LISTS_FIRST = "-";
63
+
64
+ export const CANDLES_MANY_IDS_MAX = 40;
65
+ export const CANDLES_MANY_LIMIT_DEFAULT = 1_000;
66
+ export const CANDLES_MANY_ROWS_MAX = 40_000;
67
+
57
68
  export const LAUNCH_CURSOR_MAX = 512;
58
69
 
59
70
  export const WALLET_PAGE_DEFAULT = 100;
@@ -90,6 +101,10 @@ const presets = (p )
90
101
  const launchPath = (id , tail = "") => `/floor-amm/launches/${seg(id)}${tail}`;
91
102
  const walletPath = (w , tail ) => `/floor-amm/wallets/${seg(w)}${tail}`;
92
103
 
104
+    
105
+
106
+    
107
+
93
108
  export const indexerPath = {
94
109
  head: () => "/floor-amm/head",
95
110
  latestBlock: () => "/floor-amm/latest-block",
@@ -113,6 +128,13 @@ export const indexerPath = {
113
128
  if (q.preset !== undefined && q.preset.length > PRESET_FILTER_MAX) throw new RangeError(`at most ${PRESET_FILTER_MAX} presets`);
114
129
  return `/floor-amm/search${query({ q: q.q, limit: q.limit, cursor: q.cursor, rankable: q.rankable, graduated: q.graduated, quote: q.quote, preset: presets(q.preset) })}`;
115
130
  },
131
+ launchLists: (q ) => {
132
+ if (q.quotes.length < 1 || q.quotes.length > LAUNCH_LISTS_QUOTES_MAX) throw new RangeError(`1..${LAUNCH_LISTS_QUOTES_MAX} quotes`);
133
+ if (q.cursors !== undefined && q.cursors.length !== q.quotes.length) throw new RangeError("one cursor per quote");
134
+ if (q.preset !== undefined && q.preset.length > PRESET_FILTER_MAX) throw new RangeError(`at most ${PRESET_FILTER_MAX} presets`);
135
+ const cursors = q.cursors?.some((c) => c !== null && c !== "") ? q.cursors.map((c) => (c === null || c === "" ? LAUNCH_LISTS_FIRST : c)) : undefined;
136
+ return `/floor-amm/launch-lists${query({ quotes: q.quotes, cursors, sort: q.sort, order: q.order, creator: q.creator, rankable: q.rankable, graduated: q.graduated, preset: presets(q.preset), limit: q.limit })}`;
137
+ },
116
138
  launch: (id ) => launchPath(id),
117
139
  launchState: (id ) => launchPath(id, "/state"),
118
140
  milestones: (id ) => launchPath(id, "/milestones"),
@@ -138,6 +160,10 @@ export const indexerPath = {
138
160
  if (q.limit !== undefined && q.before === undefined) throw new RangeError("limit is read only with before");
139
161
  return `/floor-amm/candles${query({ launch: need(q.launch), interval: q.interval, from: q.from, to: q.to, before: q.before, limit: q.limit })}`;
140
162
  },
163
+ candlesMany: (q ) => {
164
+ if (q.ids.length < 1 || q.ids.length > CANDLES_MANY_IDS_MAX) throw new RangeError(`1..${CANDLES_MANY_IDS_MAX} ids`);
165
+ return `/floor-amm/candles/many${query({ ids: q.ids, interval: q.interval, before: q.before, limit: q.limit })}`;
166
+ },
141
167
  walletTrades: (w , q = {}) => walletPath(w, `/trades${query({ limit: q.limit, before: q.before, launch: q.launch })}`),
142
168
 
143
169
  tonActivity: (w , q = {}) => walletPath(w, `/ton-activity${query({ limit: q.limit, before: q.before })}`),
@@ -56,6 +56,7 @@ export const readFloorRouted = (get ) => readRoute(g
56
56
 
57
57
  export const readEvents = (get , fromBlock , toBlock ) => readRoute(get, indexerPath.events(fromBlock, toBlock), B.EVENTS);
58
58
 
59
+ export const readLaunchLists = (get , q ) => readRoute(get, indexerPath.launchLists(q), B.LAUNCH_LISTS);
59
60
  export const readLaunches = (get , q = {}) => readRoute(get, indexerPath.launches(q), B.LAUNCHES);
60
61
 
61
62
  export const readLaunchSearch = (get , q ) => readRoute(get, indexerPath.search(q), B.LAUNCH_SEARCH);
@@ -93,6 +94,8 @@ export const readMarks = (get , id , q = {})
93
94
  export const readPrice = (get , id ) => readRoute(get, indexerPath.price(id), B.PRICE);
94
95
 
95
96
  export const readCandles = (get , q ) => readRoute(get, indexerPath.candles(q), B.CANDLES);
97
+
98
+ export const readCandlesMany = (get , q ) => readRoute(get, indexerPath.candlesMany(q), B.CANDLES_MANY);
96
99
  export const readCandleBundle = (get , id , q = {}) => readRoute(get, indexerPath.candleBundle(id, q), B.CANDLE_BUNDLE);
97
100
  export const readHighs = (get , id , q = {}) => readRoute(get, indexerPath.highs(id, q), B.HIGHS);
98
101
 
@@ -31,6 +31,10 @@ export const KIND_TAIL = 5;
31
31
 
32
32
   
33
33
 
34
+  
35
+
36
+  
37
+
34
38
  const ov = (x ) => (x === null ? fail("Overflow") : x);
35
39
  const u64 = (x ) => (x < 0n || x > U64_MAX ? fail("Overflow") : x);
36
40
  const u128 = (x ) => (x < 0n || x > U128_MAX ? fail("Overflow") : x);
@@ -72,7 +76,7 @@ export function emptyBook(sqrtP , feePpm ) {
72
76
  return {
73
77
  sqrtP, sqrtF: 0n, sqrtLMax: 0n, floor: 0n, floorTokens: 0n, nBands: 0, nC: 0,
74
78
  bandEdge: new Array(BIDS_MAX + 1).fill(0n), bandMoney: new Array(BIDS_MAX).fill(0n), bandTokens: new Array(BIDS_MAX).fill(0n),
75
- bandF: new Array(BIDS_MAX).fill(0n), bandFClaim: new Array(BIDS_MAX).fill(0n), ckAtF: 0n, ckFloorTokens: 0n, feePpm: [...feePpm], feeStartPpm: [0, 0, 0, 0, 0], sqrtFeeA: 0n, sqrtFeeB: 0n, graduated: false, nRanges: 0, ranges: Array.from({ length: RANGES_MAX }, emptyRange),
79
+ bandF: new Array(BIDS_MAX).fill(0n), bandFClaim: new Array(BIDS_MAX).fill(0n), ckAtF: 0n, ckFloorTokens: 0n, kpot: true, kAtF: 0n, kFloorTokens: 0n, feePpm: [...feePpm], feeStartPpm: [0, 0, 0, 0, 0], sqrtFeeA: 0n, sqrtFeeB: 0n, graduated: false, nRanges: 0, ranges: Array.from({ length: RANGES_MAX }, emptyRange),
76
80
  };
77
81
  }
78
82
 
@@ -196,6 +200,21 @@ export const ckMoney = (b ) => sum(b.bandMoney, b.nBands) - sum(b.b
196
200
 
197
201
  export const ckHeld = (b ) => sum(b.bandTokens, b.nBands) + b.ckFloorTokens;
198
202
 
203
+ export const kSeg = (b ) => (b.kpot && b.nBands === b.nC + 1 ? b.nC : null);
204
+
205
+ export const cMoney = (b ) => sum(b.bandMoney, b.nC) - sum(b.bandF, b.nC) + (b.ckAtF - b.kAtF);
206
+
207
+ export const kMoney = (b ) => ckMoney(b) - cMoney(b);
208
+
209
+ export const cHeld = (b ) => sum(b.bandTokens, b.nC) + (b.ckFloorTokens - b.kFloorTokens);
210
+
211
+ export const kHeld = (b ) => ckHeld(b) - cHeld(b);
212
+
213
+ export function kHolds(b ) {
214
+ const k = kSeg(b);
215
+ return k !== null && (b.bandTokens[k] > 0n || b.bandFClaim[k] > 0n);
216
+ }
217
+
199
218
  const bidMoneySum = (b ) => b.floor + sum(b.bandMoney, b.nBands);
200
219
 
201
220
  export const placeMoney = (b ) => {
@@ -259,6 +278,8 @@ export function checkBook(b ) {
259
278
  }
260
279
  }
261
280
  if (b.ckAtF > b.floor || b.ckFloorTokens > b.floorTokens) fail("Overflow");
281
+ if (b.kAtF > b.ckAtF || b.kFloorTokens > b.ckFloorTokens) fail("Overflow");
282
+ if (b.kpot && b.nBands > b.nC + 1) fail("SqrtRange");
262
283
  }
263
284
 
264
285
  function flatUp(b ) {
@@ -343,6 +364,14 @@ function floorRebuy(b , take , cost ) {
343
364
  if (xe > 0n) {
344
365
  const back = (cost * xe) / x0;
345
366
  const gone = min((take * xe + x0 - 1n) / x0, xe);
367
+
368
+ const xk = b.kFloorTokens;
369
+ if (xk > 0n) {
370
+ const backK = (back * xk) / xe;
371
+ const goneK = min(min((gone * xk + xe - 1n) / xe, xk), gone);
372
+ b.kAtF = u128(b.kAtF + backK);
373
+ b.kFloorTokens -= goneK;
374
+ }
346
375
  b.ckAtF = u128(b.ckAtF + back);
347
376
  b.ckFloorTokens -= gone;
348
377
  }
@@ -534,12 +563,14 @@ export function walkDownAcc(b , tokens , acc , u = new
534
563
  charge(b, acc, q);
535
564
  if (fp.t === "floor") {
536
565
 
537
- const ce = min(q, b.ckAtF);
538
- if (ce > 0n) {
539
- const xe = min(ov(flatTokensForMoney(s, ce, DOWN)), take);
540
- b.ckAtF -= ce;
541
- b.ckFloorTokens = u64(b.ckFloorTokens + xe);
542
- }
566
+ const ce = min(q, b.ckAtF - b.kAtF);
567
+ const ke = min(q - ce, b.kAtF);
568
+ const xc = ce > 0n ? min(ov(flatTokensForMoney(s, ce, DOWN)), take) : 0n;
569
+ const xk = ke > 0n ? min(ov(flatTokensForMoney(s, ke, DOWN)), take - xc) : 0n;
570
+ b.ckAtF -= ce + ke;
571
+ b.kAtF -= ke;
572
+ b.ckFloorTokens = u64(b.ckFloorTokens + xc + xk);
573
+ b.kFloorTokens = u64(b.kFloorTokens + xk);
543
574
  b.floor -= q;
544
575
  b.floorTokens = u64(b.floorTokens + take);
545
576
  w.fromF += q;
@@ -585,6 +616,8 @@ export function walkDownAcc(b , tokens , acc , u = new
585
616
 
586
617
  b.floor = u128(b.floor + b.bandMoney[j]);
587
618
  b.ckAtF = u128(b.ckAtF + b.bandMoney[j] - b.bandF[j]);
619
+
620
+ if (kSeg(b) === j) b.kAtF = u128(b.kAtF + b.bandMoney[j] - b.bandF[j]);
588
621
  b.bandMoney[j] = 0n;
589
622
  b.bandF[j] = 0n;
590
623
  }
@@ -115,7 +115,7 @@ export function teamBuyV2(book , gross , max ) {
115
115
  const take = gross < max ? gross : max;
116
116
  if (take === 0n) {
117
117
  return { gross, net: 0n, refund: gross, tokens: 0n, fees: [0n, 0n, 0n, 0n, 0n], fromResale: 0n, fromFirst: 0n, steps: 0, budgetHit: false, graduatedNow: false, sqrtBefore: book.sqrtP, sqrtAfter: book.sqrtP,
118
- split: { dF: 0n, ckAdd: 0n, ckTake: 0n, ms: 0n, booked: [0n, 0n, 0n, 0n], sqrtFNew: 0n }, relay: { nC: 0, nK: 0, laidC: 0n, laidK: 0n, atF: 0n, kept: 0 } };
118
+ split: { dF: 0n, ckAdd: 0n, ckTake: 0n, cAdd: 0n, kAdd: 0n, cTake: 0n, kTake: 0n, ms: 0n, booked: [0n, 0n, 0n, 0n], sqrtFNew: 0n }, relay: { nC: 0, nK: 0, laidC: 0n, laidK: 0n, atF: 0n, kAtF: 0n, kept: 0 } };
119
119
  }
120
120
  const r = bookBuy(book, take, 0n);
121
121
  return { ...r, refund: r.refund + gross - take, gross };