@floorlaunchpad/sdk 0.4.0 → 0.4.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.
package/src/evm/zap.ts CHANGED
@@ -5,14 +5,44 @@ import { encodeFunctionData } from "./items.ts";
5
5
 
6
6
  export type ZapFamily = "uniswap-ur" | "v3-router" | "v3-router02" | "algebra" | "v2-router" | "aerodrome-v2";
7
7
 
8
+ export type ZapUrFork = "uniswap" | "aerodrome" | "pancake" | "ramses";
9
+
10
+ export const AERODROME_SLIPSTREAM_KEY = 0x100000;
11
+
8
12
  export const UR_V3_SWAP_EXACT_IN = 0x00;
9
13
  export const UR_V2_SWAP_EXACT_IN = 0x08;
10
14
  export const UR_WRAP_ETH = 0x0b;
11
15
  export const UR_UNWRAP_WETH = 0x0c;
12
16
  export const UR_SWEEP = 0x04;
17
+ export const UR_V4_SWAP = 0x10;
13
18
  export const UR_MSG_SENDER = "0x0000000000000000000000000000000000000001";
14
19
  export const UR_ADDRESS_THIS = "0x0000000000000000000000000000000000000002";
15
20
 
21
+ export const V4_SWAP_EXACT_IN_SINGLE = 0x06;
22
+ export const V4_SETTLE = 0x0b;
23
+ export const V4_TAKE = 0x0e;
24
+ export const V4_OPEN_DELTA = 0n;
25
+ export const V4_NATIVE = "0x0000000000000000000000000000000000000000";
26
+
27
+ export interface ZapV4Pool {
28
+
29
+ fee: number;
30
+
31
+ tickSpacing: number;
32
+
33
+ hooks?: string;
34
+
35
+ hookData?: string;
36
+ }
37
+
38
+ export interface V4PoolKey {
39
+ currency0: string;
40
+ currency1: string;
41
+ fee: number;
42
+ tickSpacing: number;
43
+ hooks: string;
44
+ }
45
+
16
46
  export interface ZapRoute {
17
47
 
18
48
  tokens: readonly string[];
@@ -21,6 +51,8 @@ export interface ZapRoute {
21
51
 
22
52
  stable?: readonly boolean[];
23
53
  factory?: string;
54
+
55
+ v4?: ZapV4Pool;
24
56
  }
25
57
 
26
58
  export interface ZapSwapParams {
@@ -33,6 +65,14 @@ export interface ZapSwapParams {
33
65
 
34
66
  zap: string;
35
67
  deadline: bigint;
68
+
69
+ input?: "native" | "token";
70
+
71
+ output?: "token" | "native";
72
+
73
+ router?: string;
74
+
75
+ urFork?: ZapUrFork;
36
76
  }
37
77
 
38
78
  const fn = (name: string, inputs: readonly { name: string; type: string; components?: any }[]) => ({ type: "function", name, inputs, outputs: [], stateMutability: "payable" }) as const;
@@ -57,34 +97,136 @@ export function algebraPath(tokens: readonly string[]): string {
57
97
  return "0x" + tokens.map((t) => bytesToHex(hexToBytes(t)).slice(2)).join("");
58
98
  }
59
99
 
60
- const checkRoute = (p: ZapSwapParams): void => {
100
+ const UR_FORKS: readonly ZapUrFork[] = ["uniswap", "aerodrome", "pancake", "ramses"];
101
+
102
+ interface Ends {
103
+ nativeIn: boolean;
104
+ nativeOut: boolean;
105
+ }
106
+
107
+ const isNative = (a: string): boolean => BigInt(checksumAddress(a)) === 0n;
108
+
109
+ const checkRoute = (p: ZapSwapParams): Ends => {
61
110
  if (p.amountIn <= 0n) throw new RangeError("amountIn must be > 0");
62
111
  if (p.minQuoteOut <= 0n) throw new RangeError("minQuoteOut must be > 0 (the NO_MINIMUM rule)");
63
- if (p.route.tokens.length < 2) throw new RangeError("a route is at least two tokens");
112
+ const { tokens } = p.route;
113
+ if (tokens.length < 2) throw new RangeError("a route is at least two tokens");
114
+ if (p.input !== undefined && p.input !== "native" && p.input !== "token") throw new RangeError(`input ${String(p.input)} is "native" or "token"`);
115
+ if (p.output !== undefined && p.output !== "native" && p.output !== "token") throw new RangeError(`output ${String(p.output)} is "native" or "token"`);
116
+ if (p.urFork !== undefined && (p.family !== "uniswap-ur" || !UR_FORKS.includes(p.urFork))) {
117
+ throw new RangeError(`urFork ${String(p.urFork)} names a uniswap-ur row's router: ${UR_FORKS.join(", ")}`);
118
+ }
119
+ const [first, last] = [tokens[0], tokens[tokens.length - 1]];
120
+ if (BigInt(checksumAddress(first)) === BigInt(checksumAddress(last))) throw new RangeError("a route swaps a coin into itself");
121
+ if (p.route.v4) {
122
+ if (p.family !== "uniswap-ur") throw new RangeError("a v4 route goes through the Universal Router (uniswap-ur)");
123
+ if ((p.urFork ?? "uniswap") !== "uniswap") throw new RangeError("a v4 route goes through Uniswap's own Universal Router");
124
+ const ends = { nativeIn: isNative(first), nativeOut: isNative(last) };
125
+ if (p.input !== undefined && (p.input === "native") !== ends.nativeIn) throw new RangeError(`input "${p.input}" is not the v4 route's first currency`);
126
+ if (p.output !== undefined && (p.output === "native") !== ends.nativeOut) throw new RangeError(`output "${p.output}" is not the v4 route's last currency`);
127
+ return ends;
128
+ }
129
+ 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)");
130
+ const ends = { nativeIn: (p.input ?? "native") === "native", nativeOut: (p.output ?? "token") === "native" };
131
+ if (ends.nativeIn && ends.nativeOut) throw new RangeError("a route swaps the native coin into itself");
132
+ return ends;
64
133
  };
65
134
 
66
- function universalRouter(p: ZapSwapParams): string {
67
- const wrap = bytesToHex(encodeAbi(["address", "uint256"], [UR_ADDRESS_THIS, p.amountIn]));
68
- let cmd: number;
69
- let swap: string;
135
+ export function v4PoolKey(tokenIn: string, tokenOut: string, pool: ZapV4Pool): { key: V4PoolKey; zeroForOne: boolean } {
136
+ const a = checksumAddress(tokenIn);
137
+ const b = checksumAddress(tokenOut);
138
+ if (BigInt(a) === BigInt(b)) throw new RangeError("a v4 swap is between two different currencies");
139
+ if (!Number.isInteger(pool.fee) || pool.fee < 0 || pool.fee >= 1 << 24) throw new RangeError(`fee ${pool.fee} is not a uint24`);
140
+ if (!Number.isInteger(pool.tickSpacing) || pool.tickSpacing < 1 || pool.tickSpacing > 32767) throw new RangeError(`tick spacing ${pool.tickSpacing} is not 1 ..= 32767`);
141
+ const zeroForOne = BigInt(a) < BigInt(b);
142
+ const hooks = checksumAddress(pool.hooks ?? V4_NATIVE);
143
+ return { key: { currency0: zeroForOne ? a : b, currency1: zeroForOne ? b : a, fee: pool.fee, tickSpacing: pool.tickSpacing, hooks }, zeroForOne };
144
+ }
145
+
146
+ const UINT128 = 1n << 128n;
147
+ const UR_EXECUTE = [fn("execute", [{ name: "commands", type: "bytes" }, { name: "inputs", type: "bytes[]" }, { name: "deadline", type: "uint256" }])];
148
+ const cmds = (cs: readonly number[]): string => "0x" + cs.map((c) => c.toString(16).padStart(2, "0")).join("");
149
+
150
+ function universalRouterV4(p: ZapSwapParams, pool: ZapV4Pool): string {
151
+ const { tokens } = p.route;
152
+ if (tokens.length !== 2) throw new RangeError("a v4 route is one pool: [currency in, currency out]");
153
+ if (p.route.fees || p.route.stable || p.route.factory) throw new RangeError("a v4 route names its pool in `v4` only");
154
+ if (p.amountIn >= UINT128 || p.minQuoteOut >= UINT128) throw new RangeError("a v4 amount is a uint128");
155
+ const [tokenIn, tokenOut] = tokens;
156
+ const { key, zeroForOne } = v4PoolKey(tokenIn, tokenOut, pool);
157
+ const nativeOut = isNative(tokenOut);
158
+ const swap = encodeAbi(
159
+ ["((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"],
160
+ [[[key.currency0, key.currency1, BigInt(key.fee), BigInt(key.tickSpacing), key.hooks], zeroForOne, p.amountIn, p.minQuoteOut, 0n, pool.hookData ?? "0x"]],
161
+ );
162
+ const settle = encodeAbi(["address", "uint256", "bool"], [checksumAddress(tokenIn), V4_OPEN_DELTA, false]);
163
+ const take = encodeAbi(["address", "address", "uint256"], [checksumAddress(tokenOut), nativeOut ? UR_ADDRESS_THIS : UR_MSG_SENDER, V4_OPEN_DELTA]);
164
+ const v4 = bytesToHex(encodeAbi(["bytes", "bytes[]"], [cmds([V4_SWAP_EXACT_IN_SINGLE, V4_SETTLE, V4_TAKE]), [swap, settle, take]]));
165
+
166
+ const nativeIn = isNative(tokenIn);
167
+ const sweep = (min: bigint): string => bytesToHex(encodeAbi(["address", "address", "uint256"], [V4_NATIVE, UR_MSG_SENDER, min]));
168
+ const inputs = nativeOut ? [v4, sweep(p.minQuoteOut)] : nativeIn ? [v4, sweep(0n)] : [v4];
169
+ 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 });
170
+ }
171
+
172
+ const UR_SWAP_HEAD = ["address", "uint256", "uint256", "bytes", "bool"];
173
+
174
+ function aerodromeKey(k: number): number {
175
+ if (!Number.isInteger(k) || k < 1 || k >= 1 << 24) throw new RangeError(`Aerodrome key ${k} is not a tick spacing`);
176
+ if (k < AERODROME_SLIPSTREAM_KEY) return AERODROME_SLIPSTREAM_KEY | k;
177
+ if (k >>> 20 !== 1) throw new RangeError(`Aerodrome key ${k} names another factory than Slipstream's (0x100000 | tickSpacing)`);
178
+ return k;
179
+ }
180
+
181
+ function universalRouter(p: ZapSwapParams, e: Ends): string {
182
+ const fork = p.urFork ?? "uniswap";
183
+ const to = e.nativeOut ? UR_ADDRESS_THIS : UR_MSG_SENDER;
184
+ const commands: number[] = [];
185
+ const inputs: string[] = [];
186
+ if (e.nativeIn) {
187
+ commands.push(UR_WRAP_ETH);
188
+ inputs.push(bytesToHex(encodeAbi(["address", "uint256"], [UR_ADDRESS_THIS, p.amountIn])));
189
+ }
70
190
  if (p.route.fees) {
71
- cmd = UR_V3_SWAP_EXACT_IN;
72
- swap = bytesToHex(encodeAbi(["address", "uint256", "uint256", "bytes", "bool", "uint256[]"], [UR_MSG_SENDER, p.amountIn, p.minQuoteOut, v3Path(p.route.tokens, p.route.fees), false, []]));
191
+ const keys = fork === "aerodrome" ? p.route.fees.map(aerodromeKey) : p.route.fees;
192
+ const head = [to, p.amountIn, p.minQuoteOut, v3Path(p.route.tokens, keys), false];
193
+ const swap = fork === "uniswap" ? encodeAbi([...UR_SWAP_HEAD, "uint256[]"], [...head, []])
194
+ : fork === "aerodrome" ? encodeAbi([...UR_SWAP_HEAD, "bool"], [...head, false])
195
+ : encodeAbi(UR_SWAP_HEAD, head);
196
+ commands.push(UR_V3_SWAP_EXACT_IN);
197
+ inputs.push(bytesToHex(swap));
73
198
  } else {
74
- cmd = UR_V2_SWAP_EXACT_IN;
75
- swap = bytesToHex(encodeAbi(["address", "uint256", "uint256", "address[]", "bool", "uint256[]"], [UR_MSG_SENDER, p.amountIn, p.minQuoteOut, [...p.route.tokens], false, []]));
199
+ 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)`);
200
+ commands.push(UR_V2_SWAP_EXACT_IN);
201
+ inputs.push(bytesToHex(encodeAbi(["address", "uint256", "uint256", "address[]", "bool", "uint256[]"], [to, p.amountIn, p.minQuoteOut, [...p.route.tokens], false, []])));
202
+ }
203
+ if (e.nativeOut) {
204
+ commands.push(UR_UNWRAP_WETH);
205
+ inputs.push(bytesToHex(encodeAbi(["address", "uint256"], [UR_MSG_SENDER, p.minQuoteOut])));
76
206
  }
77
- const commands = "0x" + [UR_WRAP_ETH, cmd].map((c) => c.toString(16).padStart(2, "0")).join("");
78
- const abi = [fn("execute", [{ name: "commands", type: "bytes" }, { name: "inputs", type: "bytes[]" }, { name: "deadline", type: "uint256" }])];
79
- return encodeFunctionData(abi, "execute", { commands, inputs: [wrap, swap], deadline: p.deadline });
207
+ if (e.nativeIn) {
208
+
209
+ commands.push(UR_SWEEP);
210
+ inputs.push(bytesToHex(encodeAbi(["address", "address", "uint256"], [V4_NATIVE, UR_MSG_SENDER, 0n])));
211
+ }
212
+ return encodeFunctionData(UR_EXECUTE, "execute", { commands: cmds(commands), inputs, deadline: p.deadline });
80
213
  }
81
214
 
215
+ const ADDRESS_ZERO = "0x0000000000000000000000000000000000000000";
82
216
  const REFUND_ETH = [fn("refundETH", [])];
83
217
  const REFUND_NATIVE = [fn("refundNativeToken", [])];
218
+ const UNWRAP = (name: string) => [fn(name, [{ name: "amountMinimum", type: "uint256" }, { name: "recipient", type: "address" }])];
84
219
 
85
- function v3Router(p: ZapSwapParams, v02: boolean): string {
220
+ const peripheryTail = (p: ZapSwapParams, e: Ends, refund: string, unwrap: string): string[] =>
221
+ e.nativeIn ? [encodeFunctionData(refund === "refundETH" ? REFUND_ETH : REFUND_NATIVE, refund)]
222
+ : e.nativeOut ? [encodeFunctionData(UNWRAP(unwrap), unwrap, { amountMinimum: p.minQuoteOut, recipient: p.zap })]
223
+ : [];
224
+
225
+ function v3Router(p: ZapSwapParams, v02: boolean, e: Ends): string {
86
226
  const fees = p.route.fees;
87
227
  if (!fees) throw new RangeError("a V3 router route needs its fees");
228
+ 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`");
229
+ const recipient = !e.nativeOut ? p.zap : v02 ? UR_ADDRESS_THIS : checksumAddress(p.router as string);
88
230
  const [tokenIn, tokenOut] = [p.route.tokens[0], p.route.tokens[p.route.tokens.length - 1]];
89
231
  let swap: string;
90
232
  if (p.route.tokens.length === 2) {
@@ -92,61 +234,68 @@ function v3Router(p: ZapSwapParams, v02: boolean): string {
92
234
  ? [["tokenIn", "address"], ["tokenOut", "address"], ["fee", "uint24"], ["recipient", "address"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"], ["sqrtPriceLimitX96", "uint160"]]
93
235
  : [["tokenIn", "address"], ["tokenOut", "address"], ["fee", "uint24"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"], ["sqrtPriceLimitX96", "uint160"]];
94
236
  const abi = [fn("exactInputSingle", [{ name: "params", type: "tuple", components: tup(fields) }])];
95
- 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 } });
237
+ swap = encodeFunctionData(abi, "exactInputSingle", { params: { tokenIn, tokenOut, fee: BigInt(fees[0]), recipient, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut, sqrtPriceLimitX96: 0n } });
96
238
  } else {
97
239
  const fields: [string, string][] = v02
98
240
  ? [["path", "bytes"], ["recipient", "address"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"]]
99
241
  : [["path", "bytes"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"]];
100
242
  const abi = [fn("exactInput", [{ name: "params", type: "tuple", components: tup(fields) }])];
101
- swap = encodeFunctionData(abi, "exactInput", { params: { path: v3Path(p.route.tokens, fees), recipient: p.zap, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut } });
243
+ swap = encodeFunctionData(abi, "exactInput", { params: { path: v3Path(p.route.tokens, fees), recipient, deadline: p.deadline, amountIn: p.amountIn, amountOutMinimum: p.minQuoteOut } });
102
244
  }
103
- const refund = encodeFunctionData(REFUND_ETH, "refundETH");
104
- if (v02) return encodeFunctionData([fn("multicall", [{ name: "deadline", type: "uint256" }, { name: "data", type: "bytes[]" }])], "multicall", { deadline: p.deadline, data: [swap, refund] });
105
- return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data: [swap, refund] });
245
+ const data = [swap, ...peripheryTail(p, e, "refundETH", "unwrapWETH9")];
246
+ if (v02) return encodeFunctionData([fn("multicall", [{ name: "deadline", type: "uint256" }, { name: "data", type: "bytes[]" }])], "multicall", { deadline: p.deadline, data });
247
+ return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data });
106
248
  }
107
249
 
108
- function algebra(p: ZapSwapParams): string {
250
+ function algebra(p: ZapSwapParams, e: Ends): string {
251
+ const recipient = e.nativeOut ? ADDRESS_ZERO : p.zap;
109
252
  const [tokenIn, tokenOut] = [p.route.tokens[0], p.route.tokens[p.route.tokens.length - 1]];
110
253
  let swap: string;
111
254
  if (p.route.tokens.length === 2) {
112
255
  const fields: [string, string][] = [["tokenIn", "address"], ["tokenOut", "address"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"], ["limitSqrtPrice", "uint160"]];
113
- 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 } });
256
+ 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 } });
114
257
  } else {
115
258
  const fields: [string, string][] = [["path", "bytes"], ["recipient", "address"], ["deadline", "uint256"], ["amountIn", "uint256"], ["amountOutMinimum", "uint256"]];
116
- 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 } });
259
+ 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 } });
117
260
  }
118
- return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data: [swap, encodeFunctionData(REFUND_NATIVE, "refundNativeToken")] });
261
+ return encodeFunctionData([fn("multicall", [{ name: "data", type: "bytes[]" }])], "multicall", { data: [swap, ...peripheryTail(p, e, "refundNativeToken", "unwrapWNativeToken")] });
119
262
  }
120
263
 
121
- function v2Router(p: ZapSwapParams): string {
122
- const abi = [fn("swapExactETHForTokens", tup([["amountOutMin", "uint256"], ["path", "address[]"], ["to", "address"], ["deadline", "uint256"]]))];
123
- return encodeFunctionData(abi, "swapExactETHForTokens", { amountOutMin: p.minQuoteOut, path: [...p.route.tokens], to: p.zap, deadline: p.deadline });
264
+ const v2Name = (e: Ends): string => (e.nativeIn ? "swapExactETHForTokens" : e.nativeOut ? "swapExactTokensForETH" : "swapExactTokensForTokens");
265
+
266
+ function v2Router(p: ZapSwapParams, e: Ends): string {
267
+ const name = v2Name(e);
268
+ const head: [string, string][] = e.nativeIn ? [] : [["amountIn", "uint256"]];
269
+ const abi = [fn(name, tup([...head, ["amountOutMin", "uint256"], ["path", "address[]"], ["to", "address"], ["deadline", "uint256"]]))];
270
+ return encodeFunctionData(abi, name, { amountIn: p.amountIn, amountOutMin: p.minQuoteOut, path: [...p.route.tokens], to: p.zap, deadline: p.deadline });
124
271
  }
125
272
 
126
- function aerodromeV2(p: ZapSwapParams): string {
273
+ function aerodromeV2(p: ZapSwapParams, e: Ends): string {
127
274
  const { tokens, stable, factory } = p.route;
128
275
  if (!stable || stable.length !== tokens.length - 1 || !factory) throw new RangeError("an Aerodrome route needs a stable flag per hop and the factory");
129
276
  const route = { name: "routes", type: "tuple[]", components: tup([["from", "address"], ["to", "address"], ["stable", "bool"], ["factory", "address"]]) };
130
- const abi = [fn("swapExactETHForTokens", [{ name: "amountOutMin", type: "uint256" }, route, { name: "to", type: "address" }, { name: "deadline", type: "uint256" }])];
277
+ const name = v2Name(e);
278
+ const head = e.nativeIn ? [] : [{ name: "amountIn", type: "uint256" }];
279
+ const abi = [fn(name, [...head, { name: "amountOutMin", type: "uint256" }, route, { name: "to", type: "address" }, { name: "deadline", type: "uint256" }])];
131
280
  const routes = stable.map((s, i) => ({ from: tokens[i], to: tokens[i + 1], stable: s, factory }));
132
- return encodeFunctionData(abi, "swapExactETHForTokens", { amountOutMin: p.minQuoteOut, routes, to: p.zap, deadline: p.deadline });
281
+ return encodeFunctionData(abi, name, { amountIn: p.amountIn, amountOutMin: p.minQuoteOut, routes, to: p.zap, deadline: p.deadline });
133
282
  }
134
283
 
135
284
  export function zapSwapData(p: ZapSwapParams): string {
136
- checkRoute(p);
285
+ const e = checkRoute(p);
137
286
  checksumAddress(p.zap);
138
287
  switch (p.family) {
139
288
  case "uniswap-ur":
140
- return universalRouter(p);
289
+ return p.route.v4 ? universalRouterV4(p, p.route.v4) : universalRouter(p, e);
141
290
  case "v3-router":
142
- return v3Router(p, false);
291
+ return v3Router(p, false, e);
143
292
  case "v3-router02":
144
- return v3Router(p, true);
293
+ return v3Router(p, true, e);
145
294
  case "algebra":
146
- return algebra(p);
295
+ return algebra(p, e);
147
296
  case "v2-router":
148
- return v2Router(p);
297
+ return v2Router(p, e);
149
298
  case "aerodrome-v2":
150
- return aerodromeV2(p);
299
+ return aerodromeV2(p, e);
151
300
  }
152
301
  }
@@ -274,6 +274,10 @@ export const LAUNCHES = object({
274
274
  });
275
275
  export type Launches = Infer<typeof LAUNCHES>;
276
276
 
277
+ export const LAUNCH_LIST = object({ quote: str, total: int, launches: array(LISTED_LAUNCH), cursors: array(str), keys: array(nullable(str)), next: nullable(str) });
278
+ export const LAUNCH_LISTS = object({ indexed, lists: array(LAUNCH_LIST) });
279
+ export type LaunchLists = Infer<typeof LAUNCH_LISTS>;
280
+
277
281
  const SEARCH_SERVED_TIER: Decoder<0 | 1 | 2 | 3 | 4> = (v, p) => {
278
282
  const n = int(v, p);
279
283
  if (n < 0 || n > 4) throw new ShapeError(p, "a tier 0..4", v);
@@ -365,6 +369,9 @@ export const CANDLES = object({
365
369
  });
366
370
  export type Candles = Infer<typeof CANDLES>;
367
371
 
372
+ export const CANDLES_MANY = object({ indexed, interval: str, series: array(CANDLES), missing: array(str) });
373
+ export type CandlesMany = Infer<typeof CANDLES_MANY>;
374
+
368
375
  export const CANDLE_BUNDLE = object({
369
376
  indexed,
370
377
  launch: str,
@@ -4,7 +4,7 @@ import { decode } from "./decode.ts";
4
4
  import { INDEXER_CONTRACT, clampLimit, pageAsked, routeLimit } from "./contract.ts";
5
5
  import type { RouteBody, RouteName } from "./contract.ts";
6
6
  import { indexerPath, query } from "./paths.ts";
7
- import type { CandlesQuery, LaunchSearchQuery, LaunchesQuery, Page, StreamQuery, TradesQuery, WalletPage, WalletTradesQuery } from "./paths.ts";
7
+ import type { CandlesManyQuery, CandlesQuery, LaunchListsQuery, LaunchSearchQuery, LaunchesQuery, Page, StreamQuery, TradesQuery, WalletPage, WalletTradesQuery } from "./paths.ts";
8
8
  import { IndexerError } from "./read.ts";
9
9
  import type { Get } from "./read.ts";
10
10
  import type { TraderWindow } from "./bodies.ts";
@@ -21,6 +21,7 @@ export interface RouteArgs {
21
21
  floorRouted: { limit?: number; cursor?: string } | void;
22
22
  events: { fromBlock: number; toBlock: number };
23
23
  launches: LaunchesQuery | void;
24
+ launchLists: LaunchListsQuery;
24
25
  search: LaunchSearchQuery;
25
26
  launch: L;
26
27
  launchState: L;
@@ -40,6 +41,7 @@ export interface RouteArgs {
40
41
  price: L;
41
42
  highs: L & { atLeast?: bigint | string; limit?: number };
42
43
  candles: CandlesQuery;
44
+ candlesMany: CandlesManyQuery;
43
45
  candleBundle: L & { intervals?: readonly string[]; limit?: number };
44
46
  walletTrades: W & WalletTradesQuery;
45
47
  tonActivity: W & Page;
@@ -82,6 +84,7 @@ export const routePath: { [N in RouteName]: (a: RouteArgs[N]) => string } = {
82
84
  floorRouted: (a) => indexerPath.floorRouted(a ?? {}),
83
85
  events: (a) => indexerPath.events(a.fromBlock, a.toBlock),
84
86
  launches: (a) => indexerPath.launches(a ?? {}),
87
+ launchLists: (a) => indexerPath.launchLists(a),
85
88
  search: (a) => indexerPath.search(a),
86
89
  launch: (a) => indexerPath.launch(a.launch),
87
90
  launchState: (a) => indexerPath.launchState(a.launch),
@@ -101,6 +104,7 @@ export const routePath: { [N in RouteName]: (a: RouteArgs[N]) => string } = {
101
104
  price: (a) => indexerPath.price(a.launch),
102
105
  highs: ({ launch, ...q }) => indexerPath.highs(launch, q),
103
106
  candles: (a) => indexerPath.candles(a),
107
+ candlesMany: (a) => indexerPath.candlesMany(a),
104
108
  candleBundle: ({ launch, ...q }) => indexerPath.candleBundle(launch, q),
105
109
  walletTrades: ({ wallet, ...q }) => indexerPath.walletTrades(wallet, q),
106
110
  tonActivity: ({ wallet, ...q }) => indexerPath.tonActivity(wallet, q),
@@ -4,7 +4,7 @@ import type { Decoder } from "./decode.ts";
4
4
  import { unknown } from "./decode.ts";
5
5
  import * as B from "./bodies.ts";
6
6
  import * as P from "./partners.ts";
7
- 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.ts";
7
+ 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.ts";
8
8
  import { SEARCH_PAGE_DEFAULT, SEARCH_PAGE_MAX, SEARCH_Q_MAX } from "./search.ts";
9
9
 
10
10
  export const UNITS = {
@@ -211,6 +211,25 @@ export const INDEXER_CONTRACT = {
211
211
  errors: [...GATED, "bad_query"],
212
212
  body: B.LAUNCHES,
213
213
  }),
214
+
215
+ launchLists: site({
216
+ pattern: "/floor-amm/launch-lists",
217
+ v2: true,
218
+ query: {
219
+ quotes: { kind: "list", doc: "one list per quote coin, in this order (no repeat)", required: true, min: 1, max: LAUNCH_LISTS_QUOTES_MAX },
220
+ cursors: { kind: "list", doc: "parallel to quotes, one each: that list's page next (- = its first page)", max: LAUNCH_LISTS_QUOTES_MAX },
221
+ sort: { kind: "enum", doc: "the order (larger first with order=desc)", values: LAUNCH_SORTS, default: "created" },
222
+ order: { kind: "enum", doc: "asc or desc", values: ["asc", "desc"], default: "desc" },
223
+ creator: { kind: "string", doc: "launches by this creator" },
224
+ rankable: { kind: "bool", doc: "true (or 1) listed only, false (or 0) unlisted only" },
225
+ graduated: { kind: "bool", doc: "graduated or not (true / false, or 1 / 0)" },
226
+ preset: PRESETS,
227
+ limit: LIMIT(LAUNCHES_PAGE_DEFAULT, LAUNCHES_PAGE_MAX),
228
+ },
229
+ page: limit(LAUNCHES_PAGE_DEFAULT, LAUNCHES_PAGE_MAX),
230
+ errors: [...GATED, "bad_query"],
231
+ body: B.LAUNCH_LISTS,
232
+ }),
214
233
  search: site({
215
234
  pattern: "/floor-amm/search",
216
235
  v2: true,
@@ -282,6 +301,20 @@ export const INDEXER_CONTRACT = {
282
301
  errors: [...GATED, "bad_query", "unknown_launch", "not_found"],
283
302
  body: B.CANDLES,
284
303
  }),
304
+
305
+ candlesMany: site({
306
+ pattern: "/floor-amm/candles/many",
307
+ aliases: ["/floor-amm/v2/candles/many"],
308
+ query: {
309
+ 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 },
310
+ interval: { kind: "enum", doc: "the bucket", values: B.CANDLE_INTERVALS, default: "1h" },
311
+ before: { kind: "unix", doc: "the newest limit traded buckets starting before it (absent: past the indexed head)" },
312
+ limit: { kind: "int", doc: "buckets per launch", min: 1, max: B.CANDLES_MAX, default: CANDLES_MANY_LIMIT_DEFAULT },
313
+ },
314
+ page: limit(CANDLES_MANY_LIMIT_DEFAULT, B.CANDLES_MAX),
315
+ errors: [...GATED, "bad_query"],
316
+ body: B.CANDLES_MANY,
317
+ }),
285
318
  candleBundle: site({
286
319
  pattern: "/floor-amm/launches/<launch>/candle-bundle",
287
320
  v2: true,
@@ -508,6 +541,14 @@ export function queryRefusal(name: RouteName, q: URLSearchParams): string | null
508
541
  }
509
542
  }
510
543
 
544
+ const prod = ROWS_PRODUCT[name];
545
+ if (prod !== undefined) {
546
+ const n = (q.get(prod.list) ?? "").split(",").filter((s) => s !== "").length;
547
+ const raw = q.get("limit");
548
+ const lim = raw === null || raw === "" ? routeLimit(name)!.default : Number(raw);
549
+ if (n * lim > prod.max) return `${prod.list} × limit must be at most ${prod.max} (asked ${n} × ${lim})`;
550
+ }
551
+
511
552
  const pg: Pagination = INDEXER_CONTRACT[name].page;
512
553
  if (pg.kind === "cursor" && pg.optIn !== undefined && q.get(pg.cursor) !== null) {
513
554
  const raw = q.get("limit");
@@ -516,7 +557,12 @@ export function queryRefusal(name: RouteName, q: URLSearchParams): string | null
516
557
  return spanRefusal(name, q);
517
558
  }
518
559
 
519
- const TABLE_REQUIRED: ReadonlySet<RouteName> = new Set<RouteName>(["search"]);
560
+ const ROWS_PRODUCT: Partial<Record<RouteName, { list: string; max: number }>> = {
561
+ launchLists: { list: "quotes", max: LAUNCH_LISTS_ROWS_MAX },
562
+ candlesMany: { list: "ids", max: CANDLES_MANY_ROWS_MAX },
563
+ };
564
+
565
+ const TABLE_REQUIRED: ReadonlySet<RouteName> = new Set<RouteName>(["search", "launchLists", "candlesMany"]);
520
566
 
521
567
  const BOOLS: Readonly<Record<string, boolean>> = { true: true, false: false, 1: true, 0: false };
522
568
 
@@ -14,6 +14,7 @@ export const INDEXER_ROUTES = {
14
14
  floorRouted: { pattern: "/floor-amm/floor-routed", keys: ["limit", "cursor"] },
15
15
  events: { pattern: "/floor-amm/events", keys: ["fromBlock", "toBlock"] },
16
16
  launches: { pattern: "/floor-amm/launches", keys: ["sort", "order", "q", "ids", "quote", "creator", "rankable", "graduated", "preset", "limit", "cursor", "offset"] },
17
+ launchLists: { pattern: "/floor-amm/launch-lists", keys: ["quotes", "cursors", "sort", "order", "creator", "rankable", "graduated", "preset", "limit"] },
17
18
  search: { pattern: "/floor-amm/search", keys: ["q", "limit", "cursor", "rankable", "graduated", "quote", "preset"] },
18
19
  launch: { pattern: "/floor-amm/launches/<launch>", keys: [] },
19
20
  launchState: { pattern: "/floor-amm/launches/<launch>/state", keys: [] },
@@ -34,6 +35,7 @@ export const INDEXER_ROUTES = {
34
35
  highs: { pattern: "/floor-amm/launches/<launch>/highs", keys: ["atLeast", "limit"] },
35
36
  candleBundle: { pattern: "/floor-amm/launches/<launch>/candle-bundle", keys: ["intervals", "limit"] },
36
37
  candles: { pattern: "/floor-amm/candles", keys: ["launch", "interval", "from", "to", "before", "limit"] },
38
+ candlesMany: { pattern: "/floor-amm/candles/many", keys: ["ids", "interval", "before", "limit"] },
37
39
  walletTrades: { pattern: "/floor-amm/wallets/<wallet>/trades", keys: ["limit", "before", "launch"] },
38
40
  tonActivity: { pattern: "/floor-amm/wallets/<wallet>/ton-activity", keys: ["limit", "before"] },
39
41
  tonOutcome: { pattern: "/floor-amm/wallets/<wallet>/ton-outcome", keys: ["queryId"] },
@@ -62,6 +64,15 @@ export const LAUNCHES_PAGE_MAX = 1_000;
62
64
 
63
65
  export const LAUNCHES_PAGE_DEFAULT = 100;
64
66
 
67
+ export const LAUNCH_LISTS_QUOTES_MAX = 16;
68
+ export const LAUNCH_LISTS_ROWS_MAX = 1_000;
69
+
70
+ export const LAUNCH_LISTS_FIRST = "-";
71
+
72
+ export const CANDLES_MANY_IDS_MAX = 40;
73
+ export const CANDLES_MANY_LIMIT_DEFAULT = 1_000;
74
+ export const CANDLES_MANY_ROWS_MAX = 40_000;
75
+
65
76
  export const LAUNCH_CURSOR_MAX = 512;
66
77
 
67
78
  export const WALLET_PAGE_DEFAULT = 100;
@@ -121,6 +132,31 @@ export interface LaunchesQuery {
121
132
  offset?: number;
122
133
  }
123
134
 
135
+ export interface LaunchListsQuery {
136
+
137
+ quotes: readonly string[];
138
+
139
+ cursors?: readonly (string | null)[];
140
+ sort?: LaunchSort;
141
+ order?: "asc" | "desc";
142
+ creator?: string;
143
+ rankable?: boolean;
144
+ graduated?: boolean;
145
+ preset?: readonly number[];
146
+
147
+ limit?: number;
148
+ }
149
+
150
+ export interface CandlesManyQuery {
151
+
152
+ ids: readonly string[];
153
+ interval?: string;
154
+
155
+ before?: number;
156
+
157
+ limit?: number;
158
+ }
159
+
124
160
  export interface LaunchSearchQuery {
125
161
 
126
162
  q: string;
@@ -199,6 +235,13 @@ export const indexerPath = {
199
235
  if (q.preset !== undefined && q.preset.length > PRESET_FILTER_MAX) throw new RangeError(`at most ${PRESET_FILTER_MAX} presets`);
200
236
  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) })}`;
201
237
  },
238
+ launchLists: (q: LaunchListsQuery): string => {
239
+ if (q.quotes.length < 1 || q.quotes.length > LAUNCH_LISTS_QUOTES_MAX) throw new RangeError(`1..${LAUNCH_LISTS_QUOTES_MAX} quotes`);
240
+ if (q.cursors !== undefined && q.cursors.length !== q.quotes.length) throw new RangeError("one cursor per quote");
241
+ if (q.preset !== undefined && q.preset.length > PRESET_FILTER_MAX) throw new RangeError(`at most ${PRESET_FILTER_MAX} presets`);
242
+ const cursors = q.cursors?.some((c) => c !== null && c !== "") ? q.cursors.map((c) => (c === null || c === "" ? LAUNCH_LISTS_FIRST : c)) : undefined;
243
+ 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 })}`;
244
+ },
202
245
  launch: (id: string): string => launchPath(id),
203
246
  launchState: (id: string): string => launchPath(id, "/state"),
204
247
  milestones: (id: string): string => launchPath(id, "/milestones"),
@@ -224,6 +267,10 @@ export const indexerPath = {
224
267
  if (q.limit !== undefined && q.before === undefined) throw new RangeError("limit is read only with before");
225
268
  return `/floor-amm/candles${query({ launch: need(q.launch), interval: q.interval, from: q.from, to: q.to, before: q.before, limit: q.limit })}`;
226
269
  },
270
+ candlesMany: (q: CandlesManyQuery): string => {
271
+ if (q.ids.length < 1 || q.ids.length > CANDLES_MANY_IDS_MAX) throw new RangeError(`1..${CANDLES_MANY_IDS_MAX} ids`);
272
+ return `/floor-amm/candles/many${query({ ids: q.ids, interval: q.interval, before: q.before, limit: q.limit })}`;
273
+ },
227
274
  walletTrades: (w: string, q: WalletTradesQuery = {}): string => walletPath(w, `/trades${query({ limit: q.limit, before: q.before, launch: q.launch })}`),
228
275
 
229
276
  tonActivity: (w: string, q: Page = {}): string => walletPath(w, `/ton-activity${query({ limit: q.limit, before: q.before })}`),
@@ -6,7 +6,7 @@ import * as B from "./bodies.ts";
6
6
  import { indexerPath } from "./paths.ts";
7
7
  import { errorCode } from "./contract.ts";
8
8
  import type { IndexerErrorCode } from "./contract.ts";
9
- import type { CandlesQuery, LaunchSearchQuery, LaunchesQuery, Page, TradesQuery, WalletPage, WalletTradesQuery } from "./paths.ts";
9
+ import type { CandlesManyQuery, CandlesQuery, LaunchListsQuery, LaunchSearchQuery, LaunchesQuery, Page, TradesQuery, WalletPage, WalletTradesQuery } from "./paths.ts";
10
10
 
11
11
  export * from "./bodies.ts";
12
12
  export { ShapeError, decode } from "./decode.ts";
@@ -20,7 +20,7 @@ export { INDEXER_CONTRACT, INDEXER_ERROR_CODES, LIMITS, OPEN_ROUTES, ROUTE_NAMES
20
20
  export type { IndexerErrorCode, Pagination, PathParam, QueryKey, RouteBody, RouteContract, RouteName, Served, ServedBody, ServedKeys, Units } from "./contract.ts";
21
21
  export { DRAIN_NAMES, createIndexerClient, routePath } from "./client.ts";
22
22
  export type { DrainName, IndexerClient, IndexerClientOptions, ReadName, RouteArgs } from "./client.ts";
23
- export type { CandlesQuery, IndexerRoute, IndexerRouteName, LaunchSearchQuery, LaunchSort, LaunchesQuery, Page, StreamQuery, TradesQuery, WalletPage, WalletTradesQuery } from "./paths.ts";
23
+ export type { CandlesManyQuery, CandlesQuery, LaunchListsQuery, IndexerRoute, IndexerRouteName, LaunchSearchQuery, LaunchSort, LaunchesQuery, Page, StreamQuery, TradesQuery, WalletPage, WalletTradesQuery } from "./paths.ts";
24
24
 
25
25
  export type LaunchId = string;
26
26
 
@@ -66,6 +66,7 @@ export const readFloorRouted = (get: Get): Promise<B.FloorRouted> => readRoute(g
66
66
 
67
67
  export const readEvents = (get: Get, fromBlock: number, toBlock: number): Promise<B.Events> => readRoute(get, indexerPath.events(fromBlock, toBlock), B.EVENTS);
68
68
 
69
+ export const readLaunchLists = (get: Get, q: LaunchListsQuery): Promise<B.LaunchLists> => readRoute(get, indexerPath.launchLists(q), B.LAUNCH_LISTS);
69
70
  export const readLaunches = (get: Get, q: LaunchesQuery = {}): Promise<B.Launches> => readRoute(get, indexerPath.launches(q), B.LAUNCHES);
70
71
 
71
72
  export const readLaunchSearch = (get: Get, q: LaunchSearchQuery): Promise<B.LaunchSearch> => readRoute(get, indexerPath.search(q), B.LAUNCH_SEARCH);
@@ -103,6 +104,8 @@ export const readMarks = (get: Get, id: LaunchId, q: Page = {}): Promise<B.Marks
103
104
  export const readPrice = (get: Get, id: LaunchId): Promise<B.Price> => readRoute(get, indexerPath.price(id), B.PRICE);
104
105
 
105
106
  export const readCandles = (get: Get, q: CandlesQuery): Promise<B.Candles> => readRoute(get, indexerPath.candles(q), B.CANDLES);
107
+
108
+ export const readCandlesMany = (get: Get, q: CandlesManyQuery): Promise<B.CandlesMany> => readRoute(get, indexerPath.candlesMany(q), B.CANDLES_MANY);
106
109
  export const readCandleBundle = (get: Get, id: LaunchId, q: { intervals?: readonly string[]; limit?: number } = {}): Promise<B.CandleBundle> => readRoute(get, indexerPath.candleBundle(id, q), B.CANDLE_BUNDLE);
107
110
  export const readHighs = (get: Get, id: LaunchId, q: { atLeast?: bigint | string; limit?: number } = {}): Promise<B.Highs> => readRoute(get, indexerPath.highs(id, q), B.HIGHS);
108
111
 
package/src/v2/devbuy.ts CHANGED
@@ -36,18 +36,20 @@ export function teamSlotWallets(slot: DevTeam["teamSlot"]): string[] {
36
36
 
37
37
  export const impactBps = (before: bigint, after: bigint): bigint => (before === 0n ? 0n : ((after - before) * 10_000n) / before);
38
38
 
39
- export function devBuyFromTrade(t: TradeEventV2, team: DevTeam, ctx: { teamBuy?: boolean; teamShareBuy?: boolean } = {}): DevBuy | null {
39
+ export function devBuyFromTrade(t: TradeEventV2, team: DevTeam, ctx: { teamBuy?: boolean; teamShareBuy?: boolean; buyer?: string } = {}): DevBuy | null {
40
40
  if (!t.isBuy) return null;
41
+
42
+ const person = ctx.buyer ?? t.trader;
41
43
  let role: DevBuyRole | null = null;
42
44
  if (t.kind === TRADE_KIND_TEAM_BUY || ctx.teamBuy) role = "team_buy";
43
45
  else if (t.kind === TRADE_KIND_TEAM_SHARE_BUY || ctx.teamShareBuy) role = "team_share_buy";
44
- else if (t.trader === team.creator) role = "creator";
45
- else if (teamSlotWallets(team.teamSlot).includes(t.trader)) role = "team_member";
46
+ else if (person === team.creator) role = "creator";
47
+ else if (teamSlotWallets(team.teamSlot).includes(person)) role = "team_member";
46
48
  if (role === null) return null;
47
49
  const priceBeforeX64 = priceX64(t.sqrtBefore);
48
50
  const priceAfterX64 = priceX64(t.sqrtAfter);
49
51
  return {
50
- launch: t.launch, trader: t.trader, role, quoteIn: t.quoteGross - t.refund, tokens: t.tokens, priceBeforeX64, priceAfterX64,
52
+ launch: t.launch, trader: person, role, quoteIn: t.quoteGross - t.refund, tokens: t.tokens, priceBeforeX64, priceAfterX64,
51
53
  impactBps: impactBps(priceBeforeX64, priceAfterX64), slot: t.slot,
52
54
  };
53
55
  }