@logswap/sdk 0.5.102 → 0.5.104
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/README.md +14 -418
- package/dist/actions.d.ts +0 -39
- package/dist/actions.js +0 -39
- package/dist/admin.d.ts +0 -106
- package/dist/admin.js +1 -96
- package/dist/chains.d.ts +0 -49
- package/dist/chains.js +0 -30
- package/dist/claims.d.ts +0 -32
- package/dist/claims.js +0 -30
- package/dist/client.d.ts +0 -116
- package/dist/client.js +1 -231
- package/dist/fees.d.ts +1 -45
- package/dist/fees.js +0 -44
- package/dist/fpool.d.ts +4 -612
- package/dist/fpool.js +14 -490
- package/dist/generated.js +0 -30
- package/dist/history.d.ts +0 -61
- package/dist/history.js +5 -74
- package/dist/ids.d.ts +0 -30
- package/dist/ids.js +0 -31
- package/dist/index.d.ts +0 -7
- package/dist/index.js +0 -7
- package/dist/indexer.d.ts +0 -68
- package/dist/indexer.js +1 -77
- package/dist/keys.d.ts +0 -50
- package/dist/keys.js +0 -35
- package/dist/liquidity.d.ts +0 -128
- package/dist/liquidity.js +1 -107
- package/dist/onboard.d.ts +0 -52
- package/dist/onboard.js +1 -59
- package/dist/pools.d.ts +3 -157
- package/dist/pools.js +1 -164
- package/dist/positions.d.ts +0 -102
- package/dist/positions.js +1 -90
- package/dist/quote.d.ts +0 -14
- package/dist/quote.js +0 -14
- package/dist/swap.d.ts +0 -31
- package/dist/swap.js +5 -37
- package/dist/tokencache.d.ts +0 -48
- package/dist/tokencache.js +1 -73
- package/dist/write.d.ts +1 -87
- package/dist/write.js +1 -87
- package/package.json +3 -8
- package/src/actions.ts +0 -208
- package/src/admin.ts +0 -350
- package/src/chains.ts +0 -278
- package/src/claims.ts +0 -111
- package/src/client.ts +0 -436
- package/src/fees.ts +0 -138
- package/src/fpool.ts +0 -2049
- package/src/generated.ts +0 -4345
- package/src/history.ts +0 -383
- package/src/ids.ts +0 -78
- package/src/index.ts +0 -26
- package/src/indexer.ts +0 -264
- package/src/keys.ts +0 -138
- package/src/liquidity.ts +0 -456
- package/src/onboard.ts +0 -253
- package/src/pools.ts +0 -465
- package/src/positions.ts +0 -297
- package/src/quote.ts +0 -36
- package/src/swap.ts +0 -181
- package/src/tokencache.ts +0 -178
- package/src/write.ts +0 -236
package/src/indexer.ts
DELETED
|
@@ -1,264 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* indexer.ts — reads the rindexer GraphQL that state cannot answer.
|
|
3
|
-
*
|
|
4
|
-
* The division of labour matters and is not arbitrary: **the indexer enumerates, the chain
|
|
5
|
-
* values.** ERC-6909 has no enumeration, so there is no way to ask a node "which positions exist in
|
|
6
|
-
* this pool" — only the `ClassRegistered` log knows. But an indexed row is a historical fact, and `L`
|
|
7
|
-
* changes with every mint, burn and harvest afterwards. So ids come from here and the current `L`
|
|
8
|
-
* is read on-chain, rather than trusting a number that was true at index time.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import type { Address, Hex } from "viem";
|
|
12
|
-
import { managerC, lensC, type LogswapClient } from "./client.js";
|
|
13
|
-
import { managerCAbi } from "./generated.js";
|
|
14
|
-
import { getPositionClass } from "./positions.js";
|
|
15
|
-
import { discoverMarkets, type DiscoveredMarket } from "./pools.js";
|
|
16
|
-
import { poolId, type PoolKey } from "./keys.js";
|
|
17
|
-
import { NO_CAP } from "./ids.js";
|
|
18
|
-
|
|
19
|
-
export interface IndexerError {
|
|
20
|
-
message: string;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* A `bytea` column renders as `0x…` but FILTERS as `\x…`.
|
|
25
|
-
*
|
|
26
|
-
* Passing back the exact value the API just gave you returns zero rows, with no error — the query
|
|
27
|
-
* is valid, the comparison simply never matches. Every filter on a hash goes through here.
|
|
28
|
-
*
|
|
29
|
-
* The result is passed as a **variable**, never interpolated into query text: `\x` is not a legal
|
|
30
|
-
* escape inside a GraphQL string literal, so an interpolated filter fails with
|
|
31
|
-
* `Syntax Error: Invalid character escape sequence`. Variables carry the value untouched.
|
|
32
|
-
*/
|
|
33
|
-
export function bytea(hex: Hex): string {
|
|
34
|
-
return `\\x${hex.replace(/^0x/, "")}`;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** How long an indexer call may take before the caller falls back (to the chain, or an empty view). */
|
|
38
|
-
export const INDEXER_TIMEOUT_MS = 8_000;
|
|
39
|
-
|
|
40
|
-
export async function gql<T>(
|
|
41
|
-
url: string,
|
|
42
|
-
query: string,
|
|
43
|
-
variables?: Record<string, unknown>,
|
|
44
|
-
signal?: AbortSignal,
|
|
45
|
-
): Promise<T> {
|
|
46
|
-
// A hung indexer must not hang its caller: every consumer has a fallback, and it only runs when
|
|
47
|
-
// this call ends. The caller's signal, if any, still wins.
|
|
48
|
-
const res = await fetch(url, {
|
|
49
|
-
method: "POST",
|
|
50
|
-
headers: { "content-type": "application/json" },
|
|
51
|
-
body: JSON.stringify({ query, variables }),
|
|
52
|
-
signal: signal ?? AbortSignal.timeout(INDEXER_TIMEOUT_MS),
|
|
53
|
-
});
|
|
54
|
-
if (!res.ok) throw new Error(`indexer: HTTP ${res.status} from ${url}`);
|
|
55
|
-
// an Access login page or a proxy's error page answers 200 with HTML; say so, rather than
|
|
56
|
-
// "Unexpected token <"
|
|
57
|
-
const ct = res.headers.get("content-type") ?? "";
|
|
58
|
-
if (!ct.includes("json")) throw new Error(`indexer: ${url} answered ${ct || "no content-type"}, not JSON (a login page?)`);
|
|
59
|
-
const body = (await res.json()) as { data?: T; errors?: IndexerError[] };
|
|
60
|
-
if (body.errors?.length) throw new Error(`indexer: ${body.errors.map((e) => e.message).join("; ")}`);
|
|
61
|
-
if (!body.data) throw new Error("indexer: empty response");
|
|
62
|
-
return body.data;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const PAGE = 1000;
|
|
66
|
-
const MAX_PAGES = 100;
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Every row of a connection, page by page. A single `first: 1000` silently drops row 1001 onward —
|
|
70
|
-
* a pool's 1001st position class, a deployment's 1001st market — with nothing to say so. Pages by
|
|
71
|
-
* cursor in primary-key order, so rows inserted while paging cannot shift the window.
|
|
72
|
-
*/
|
|
73
|
-
export async function gqlAll<N>(
|
|
74
|
-
url: string,
|
|
75
|
-
field: string,
|
|
76
|
-
selection: string,
|
|
77
|
-
opts: { vars?: Record<string, { type: string; value: unknown }>; condition?: string; signal?: AbortSignal } = {},
|
|
78
|
-
): Promise<N[]> {
|
|
79
|
-
const vars = opts.vars ?? {};
|
|
80
|
-
const decl = Object.entries(vars).map(([k, v]) => `, $${k}: ${v.type}`).join("");
|
|
81
|
-
const cond = opts.condition ? `, condition: ${opts.condition}` : "";
|
|
82
|
-
const q = `query Page($after: Cursor${decl}) {
|
|
83
|
-
${field}(first: ${PAGE}, after: $after, orderBy: PRIMARY_KEY_ASC${cond}) {
|
|
84
|
-
pageInfo { hasNextPage endCursor } nodes { ${selection} }
|
|
85
|
-
}
|
|
86
|
-
}`;
|
|
87
|
-
const values = Object.fromEntries(Object.entries(vars).map(([k, v]) => [k, v.value]));
|
|
88
|
-
const out: N[] = [];
|
|
89
|
-
let after: string | null = null;
|
|
90
|
-
for (let i = 0; i < MAX_PAGES; i++) {
|
|
91
|
-
type Conn = { pageInfo: { hasNextPage: boolean; endCursor: string | null }; nodes: N[] };
|
|
92
|
-
const d: Record<string, Conn> = await gql<Record<string, Conn>>(url, q, { ...values, after }, opts.signal);
|
|
93
|
-
const page: Conn = d[field]!;
|
|
94
|
-
out.push(...page.nodes);
|
|
95
|
-
if (!page.pageInfo.hasNextPage || !page.pageInfo.endCursor) return out;
|
|
96
|
-
after = page.pageInfo.endCursor;
|
|
97
|
-
}
|
|
98
|
-
throw new Error(`indexer: ${field} has more than ${PAGE * MAX_PAGES} rows`);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** A position class as the chain registered it: the floor/cap geometry, fixed for the id's life. */
|
|
102
|
-
export interface RegisteredId {
|
|
103
|
-
id: bigint;
|
|
104
|
-
floor: bigint;
|
|
105
|
-
cap: bigint;
|
|
106
|
-
capped: boolean;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** Every position class ever registered in a pool. Historical — some may since have burnt to zero. */
|
|
110
|
-
export async function registeredIds(url: string, poolId: Hex, signal?: AbortSignal): Promise<RegisteredId[]> {
|
|
111
|
-
const nodes = await gqlAll<{ id: string; floor: string; cap: string; capped: boolean }>(url, "allClassRegistereds", "id floor cap capped", {
|
|
112
|
-
vars: { pool: { type: "String!", value: bytea(poolId) } },
|
|
113
|
-
condition: "{poolId: $pool}",
|
|
114
|
-
signal,
|
|
115
|
-
});
|
|
116
|
-
return nodes.map((n) => ({
|
|
117
|
-
id: BigInt(n.id),
|
|
118
|
-
floor: BigInt(n.floor),
|
|
119
|
-
cap: BigInt(n.cap),
|
|
120
|
-
capped: n.capped,
|
|
121
|
-
}));
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
export interface PoolPosition extends RegisteredId {
|
|
125
|
-
/** Total exposure across every holder, read from the chain — not from the indexed row. */
|
|
126
|
-
L: bigint;
|
|
127
|
-
shares: bigint;
|
|
128
|
-
/** Spot is inside this position's range, so it is earning fees. */
|
|
129
|
-
active: boolean;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Every live position class in a pool, split by whether it is earning.
|
|
134
|
-
*
|
|
135
|
-
* A position is **active** when spot sits at or above its floor and, if capped, below its cap —
|
|
136
|
-
* the same condition the tick ladder applies when it steps `lActive`.
|
|
137
|
-
*
|
|
138
|
-
* Classes that have burnt to `L = 0` are dropped: they are registered forever, but a list of
|
|
139
|
-
* positions should show positions, not the history of ones that existed.
|
|
140
|
-
*/
|
|
141
|
-
export async function poolPositions(
|
|
142
|
-
c: LogswapClient,
|
|
143
|
-
url: string,
|
|
144
|
-
poolId: Hex,
|
|
145
|
-
x: bigint,
|
|
146
|
-
signal?: AbortSignal,
|
|
147
|
-
): Promise<PoolPosition[]> {
|
|
148
|
-
const ids = await registeredIds(url, poolId, signal);
|
|
149
|
-
const rows = await Promise.all(
|
|
150
|
-
ids.map(async (r) => {
|
|
151
|
-
const cls = await getPositionClass(c, r.id);
|
|
152
|
-
return { ...r, L: cls.L, shares: cls.shares, active: x >= r.floor && (!r.capped || x < r.cap) };
|
|
153
|
-
}),
|
|
154
|
-
);
|
|
155
|
-
return rows.filter((r) => r.L > 0n).sort((a, b) => (b.L > a.L ? 1 : b.L < a.L ? -1 : 0));
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Is the indexer answering? Used to degrade a screen rather than fail it. */
|
|
159
|
-
export async function indexerHealthy(url: string, signal?: AbortSignal): Promise<boolean> {
|
|
160
|
-
try {
|
|
161
|
-
await gql(url, "{ __typename }", undefined, signal);
|
|
162
|
-
return true;
|
|
163
|
-
} catch {
|
|
164
|
-
return false;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Markets, from the indexer rather than a log scan.
|
|
170
|
-
*
|
|
171
|
-
* `discoverMarkets` reads `MarketCreated` logs straight from the node, which is correct until the node
|
|
172
|
-
* stops keeping them. anvil's `--prune-history` drops historical transactions and receipts beyond a
|
|
173
|
-
* window, so on a devnet that mines steadily the deployment's own logs age out and a scan from
|
|
174
|
-
* block 0 returns nothing — while the contracts remain perfectly alive. Any real chain has the same
|
|
175
|
-
* shape in a different form: archive-depth `getLogs` is exactly what public RPCs refuse.
|
|
176
|
-
*
|
|
177
|
-
* An indexer does not have that problem, because it recorded the event when it happened. This is
|
|
178
|
-
* the more durable path and should be preferred wherever an indexer is configured, with the log
|
|
179
|
-
* scan as the fallback for when it is not.
|
|
180
|
-
*
|
|
181
|
-
* `PoolCreated` (the C manager's) carries every field of the `PoolKey` (C 18: quote, base, swapFeeIdx, spacingIdx, policy, salt), so the key is rebuilt exactly and `poolId` is
|
|
182
|
-
* recomputed locally rather than trusted from the row — the same offline derivation the SDK uses
|
|
183
|
-
* everywhere else, so a wrong id fails loudly instead of addressing the wrong pool.
|
|
184
|
-
*/
|
|
185
|
-
export async function discoverMarketsIndexed(url: string, signal?: AbortSignal): Promise<DiscoveredMarket[]> {
|
|
186
|
-
type Row = {
|
|
187
|
-
poolId: Hex; base: Hex; quote: Hex; creator: Hex; salt: Hex; swapFeeIdx: string | number; spacingIdx: string | number; policy: Hex;
|
|
188
|
-
initialLogPrice: string; blockNumber: string; txHash: Hex; contractAddress: Hex;
|
|
189
|
-
};
|
|
190
|
-
const nodes = await gqlAll<Row>(url, "allCPoolManagerPoolCreateds", "poolId base quote creator salt swapFeeIdx spacingIdx policy initialLogPrice blockNumber txHash contractAddress", { signal });
|
|
191
|
-
return nodes.map((n) => {
|
|
192
|
-
// rindexer names a column after the event's field: `swapFeeIdx` / `spacingIdx` since C 18 (decision 099)
|
|
193
|
-
const key: PoolKey = { quote: n.quote as Address, base: n.base as Address, swapFeeIdx: Number(n.swapFeeIdx), spacingIdx: Number(n.spacingIdx), policy: n.policy as Address, salt: n.salt };
|
|
194
|
-
return {
|
|
195
|
-
key,
|
|
196
|
-
poolId: poolId(key),
|
|
197
|
-
creator: n.creator as Address,
|
|
198
|
-
initialLogPrice: BigInt(n.initialLogPrice),
|
|
199
|
-
blockNumber: BigInt(n.blockNumber),
|
|
200
|
-
transactionHash: n.txHash,
|
|
201
|
-
manager: n.contractAddress,
|
|
202
|
-
};
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/**
|
|
207
|
-
* Markets, preferring the indexer and falling back to a log scan.
|
|
208
|
-
*
|
|
209
|
-
* The order matters: the indexer is authoritative for history, the node is authoritative for state.
|
|
210
|
-
* A market the node can no longer tell you about is still a market.
|
|
211
|
-
*/
|
|
212
|
-
export async function discoverMarketsBest(
|
|
213
|
-
c: LogswapClient,
|
|
214
|
-
url: string | undefined = c.indexerUrl,
|
|
215
|
-
signal?: AbortSignal,
|
|
216
|
-
): Promise<{ markets: DiscoveredMarket[]; source: "indexer" | "chain" }> {
|
|
217
|
-
if (url) {
|
|
218
|
-
try {
|
|
219
|
-
const markets = await discoverMarketsIndexed(url, signal);
|
|
220
|
-
// The indexer is a CACHE and the chain is the truth. After a redeploy it keeps serving the
|
|
221
|
-
// previous deployment's markets, and calling the new manager with those keys makes every
|
|
222
|
-
// read revert, refresh-proof. Each row names the manager that emitted it, so keep only the
|
|
223
|
-
// rows of the manager this client is pointed at — no read per row. None left means the
|
|
224
|
-
// indexer has not seen this deployment: the chain scan is the answer.
|
|
225
|
-
const mine = managerC(c).toLowerCase();
|
|
226
|
-
const alive = markets.filter((m) => m.manager?.toLowerCase() === mine);
|
|
227
|
-
if (alive.length) return { markets: alive, source: "indexer" };
|
|
228
|
-
} catch {
|
|
229
|
-
/* fall through — a missing indexer must not cost you the market list */
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
return { markets: await discoverMarkets(c), source: "chain" };
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/**
|
|
236
|
-
* The UNCAPPED position classes of a pool, from the CHAIN alone: the lens enumerates live floors
|
|
237
|
-
* (one bitmap bit each), and an uncapped id is a pure function of (key, floor). No indexer.
|
|
238
|
-
* Capped classes need `ClassRegistered` replay and are absent here — callers that also want those
|
|
239
|
-
* use the indexed `poolPositions` and fall back to this when the indexer is missing or stale.
|
|
240
|
-
*/
|
|
241
|
-
export async function poolPositionsFromChain(c: LogswapClient, key: PoolKey, x: bigint): Promise<PoolPosition[]> {
|
|
242
|
-
const { lensCAbi } = await import("./generated.js");
|
|
243
|
-
const floors = (await c.public.readContract({
|
|
244
|
-
address: lensC(c),
|
|
245
|
-
abi: lensCAbi,
|
|
246
|
-
functionName: "liveTicks",
|
|
247
|
-
args: [poolId(key)],
|
|
248
|
-
} as never)) as readonly bigint[];
|
|
249
|
-
const pool = poolId(key);
|
|
250
|
-
const rows = await Promise.all(
|
|
251
|
-
[...floors].map(async (floor) => {
|
|
252
|
-
const id = (await c.public.readContract({
|
|
253
|
-
address: managerC(c),
|
|
254
|
-
abi: managerCAbi,
|
|
255
|
-
functionName: "idOf",
|
|
256
|
-
args: [pool, floor],
|
|
257
|
-
} as never)) as bigint;
|
|
258
|
-
const { L, shares } = await getPositionClass(c, id); // through extsload (C version 7)
|
|
259
|
-
if (L === 0n) return null;
|
|
260
|
-
return { id, poolId: pool, floor, cap: NO_CAP, capped: false, L, shares, active: x >= floor } as PoolPosition;
|
|
261
|
-
}),
|
|
262
|
-
);
|
|
263
|
-
return rows.filter((r): r is PoolPosition => r !== null);
|
|
264
|
-
}
|
package/src/keys.ts
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* keys.ts — market identity, computed OFFLINE.
|
|
3
|
-
*
|
|
4
|
-
* A market is a `PoolKey`, and its id is the hash of that key. Both are **tier-1 frozen**
|
|
5
|
-
* (docs/app.md): the key is in every keyed signature *and* `poolId = keccak256(abi.encode(key))`,
|
|
6
|
-
* so adding a field would change every selector and re-identify every market, orphaning all
|
|
7
|
-
* indexed history.
|
|
8
|
-
*
|
|
9
|
-
* This module reimplements `PoolKeyLib.toId` in TypeScript so a client can address a market with no
|
|
10
|
-
* RPC at all. `test/derivation.test.ts` pins it against vectors generated by the contract itself —
|
|
11
|
-
* if the two ever disagree, that test fails rather than the SDK silently addressing the wrong pool.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import { encodeAbiParameters, keccak256, type Address, type Hex } from "viem";
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* `FeeParams.FEE_LIST` in bp: the eight swap fees a C market or an F pool may be born with, one list for both managers
|
|
18
|
-
* (decisions 099, 102). A key carries the index; the list is the whole fee domain, with no fee-free entry.
|
|
19
|
-
*/
|
|
20
|
-
export const FEE_LIST_BP = [1, 2, 5, 10, 20, 50, 100, 200] as const;
|
|
21
|
-
/** {@link FEE_LIST_BP} in WAD. */
|
|
22
|
-
export const FEE_LIST: readonly bigint[] = FEE_LIST_BP.map((bp) => BigInt(bp) * 10n ** 14n);
|
|
23
|
-
|
|
24
|
-
/** The least and the most swap fee of the family, WAD: the ends of {@link FEE_LIST} (1 bp, 200 bp). */
|
|
25
|
-
export const FEE_MIN = 10n ** 14n;
|
|
26
|
-
export const FEE_MAX = 2n * 10n ** 16n;
|
|
27
|
-
|
|
28
|
-
/** The most a mint fee is, WAD (2%): the top of {@link FEE_LIST}, which a 200 bp swap fee mints at. */
|
|
29
|
-
export const MINT_FEE_MAX = 2n * 10n ** 16n;
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* `MarketParams.SPACING_LIST` (decision 099): the log-tick spacings a C market may be born on, WAD steps of log-price
|
|
33
|
-
* (0.1%, about 1% and about 10.5%). A key names one by `spacingIdx`.
|
|
34
|
-
*/
|
|
35
|
-
export const SPACING_LIST: readonly bigint[] = [10n ** 15n, 10n ** 16n, 10n ** 17n];
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* The tuple that IS the market (`PoolKeyC`, C 18, decision 099: quote, base, swapFeeIdx, spacingIdx, policy, salt). Field
|
|
39
|
-
* order is load-bearing: it is the ABI encoding order, so it must match `src/types/PoolKeyC.sol` exactly. The resolved
|
|
40
|
-
* swap fee, mint fee and tick spacing are no key fields: {@link swapFeeOfKey}, {@link mintFeeOfKey}, {@link tickSpacingOf}.
|
|
41
|
-
*/
|
|
42
|
-
export interface PoolKey {
|
|
43
|
-
quote: Address;
|
|
44
|
-
base: Address;
|
|
45
|
-
/** The swap fee, as its index into {@link FEE_LIST}; fixed for the life of the market. The mint fee is the next entry (the same at the top). */
|
|
46
|
-
swapFeeIdx: number;
|
|
47
|
-
/** The log-tick spacing (the LP-boundary ladder: position floors and caps), as its index into {@link SPACING_LIST}. */
|
|
48
|
-
spacingIdx: number;
|
|
49
|
-
/**
|
|
50
|
-
* The C policy that admits this market (`PolicyC`, decision 100): registry-approved, fixed for the market's life. Part
|
|
51
|
-
* of the id: the same pair under two policies is two markets.
|
|
52
|
-
*/
|
|
53
|
-
policy: Address;
|
|
54
|
-
/**
|
|
55
|
-
* A second market of one shape under a closed policy. Part of the id. Zero on an open policy, which refuses any other
|
|
56
|
-
* value (`NotCanonical`): a public market is canonical per exact key.
|
|
57
|
-
*/
|
|
58
|
-
salt: Hex;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function listed<T>(list: readonly T[], idx: number, what: string): T {
|
|
62
|
-
const v = Number.isInteger(idx) ? list[idx] : undefined;
|
|
63
|
-
if (v === undefined) throw new Error(`logswap: ${what} index ${idx} is off the list (0..${list.length - 1})`);
|
|
64
|
-
return v;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** The swap fee at `idx` of {@link FEE_LIST}, WAD. Throws off the list. */
|
|
68
|
-
export function feeOfIdx(idx: number): bigint {
|
|
69
|
-
return listed(FEE_LIST, idx, "swap fee");
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** The index in {@link FEE_LIST} of the mint fee a swap fee at `swapFeeIdx` goes with: the next entry, the same at the top. */
|
|
73
|
-
export function mintFeeIdxOf(swapFeeIdx: number): number {
|
|
74
|
-
feeOfIdx(swapFeeIdx);
|
|
75
|
-
return Math.min(swapFeeIdx + 1, FEE_LIST.length - 1);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** The index of `fee` (WAD) in {@link FEE_LIST}. Throws for a fee off the list. */
|
|
79
|
-
export function feeIdxOf(fee: bigint): number {
|
|
80
|
-
const idx = FEE_LIST.indexOf(fee);
|
|
81
|
-
if (idx < 0) throw new Error(`logswap: swap fee ${fee} is not on the fee list (${FEE_LIST_BP.join(", ")} bp)`);
|
|
82
|
-
return idx;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** The index of `tickSpacing` (WAD) in {@link SPACING_LIST}. Throws for a spacing off the list. */
|
|
86
|
-
export function spacingIdxOf(tickSpacing: bigint): number {
|
|
87
|
-
const idx = SPACING_LIST.indexOf(tickSpacing);
|
|
88
|
-
if (idx < 0) throw new Error(`logswap: tick spacing ${tickSpacing} is not on the spacing list (${SPACING_LIST.join(", ")})`);
|
|
89
|
-
return idx;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** A market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]`, what the manager resolves at `initialize`. */
|
|
93
|
-
export function swapFeeOfKey(key: Pick<PoolKey, "swapFeeIdx">): bigint {
|
|
94
|
-
return feeOfIdx(key.swapFeeIdx);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** A market's mint fee, WAD of newly earning L: the list's next entry after the swap fee (the same at the top). */
|
|
98
|
-
export function mintFeeOfKey(key: Pick<PoolKey, "swapFeeIdx">): bigint {
|
|
99
|
-
return feeOfIdx(mintFeeIdxOf(key.swapFeeIdx));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/** A market's log-tick spacing, WAD: `SPACING_LIST[key.spacingIdx]`. */
|
|
103
|
-
export function tickSpacingOf(key: Pick<PoolKey, "spacingIdx">): bigint {
|
|
104
|
-
return listed(SPACING_LIST, key.spacingIdx, "spacing");
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const POOL_KEY_ABI = [
|
|
108
|
-
{
|
|
109
|
-
type: "tuple",
|
|
110
|
-
components: [
|
|
111
|
-
{ name: "quote", type: "address" },
|
|
112
|
-
{ name: "base", type: "address" },
|
|
113
|
-
{ name: "swapFeeIdx", type: "uint8" },
|
|
114
|
-
{ name: "spacingIdx", type: "uint8" },
|
|
115
|
-
{ name: "policy", type: "address" },
|
|
116
|
-
{ name: "salt", type: "bytes32" },
|
|
117
|
-
],
|
|
118
|
-
},
|
|
119
|
-
] as const;
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* `poolId = keccak256(abi.encode(key))` — the primary key of the entire read model. Always address a market by the key
|
|
123
|
-
* it was initialized with. Throws for an index off its list: the manager refuses such a key (`BadParam`).
|
|
124
|
-
*/
|
|
125
|
-
export function poolId(key: PoolKey): Hex {
|
|
126
|
-
swapFeeOfKey(key);
|
|
127
|
-
tickSpacingOf(key);
|
|
128
|
-
return keccak256(
|
|
129
|
-
encodeAbiParameters(POOL_KEY_ABI, [
|
|
130
|
-
{ quote: key.quote, base: key.base, swapFeeIdx: key.swapFeeIdx, spacingIdx: key.spacingIdx, policy: key.policy, salt: key.salt },
|
|
131
|
-
]),
|
|
132
|
-
);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** Structural equality of two keys — i.e. "the same market". */
|
|
136
|
-
export function sameMarket(a: PoolKey, b: PoolKey): boolean {
|
|
137
|
-
return poolId(a) === poolId(b);
|
|
138
|
-
}
|