@logswap/sdk 0.5.76 → 0.5.78
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 +62 -4
- package/dist/admin.d.ts +117 -40
- package/dist/admin.js +152 -60
- package/dist/chains.d.ts +155 -0
- package/dist/chains.js +186 -0
- package/dist/client.d.ts +39 -5
- package/dist/client.js +53 -5
- package/dist/fees.js +3 -2
- package/dist/fpool.d.ts +74 -48
- package/dist/fpool.js +84 -54
- package/dist/generated.d.ts +692 -553
- package/dist/generated.js +613 -458
- package/dist/history.d.ts +10 -1
- package/dist/history.js +36 -10
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/indexer.d.ts +5 -5
- package/dist/indexer.js +7 -7
- package/dist/pools.d.ts +10 -8
- package/dist/pools.js +9 -8
- package/dist/positions.d.ts +5 -5
- package/dist/positions.js +10 -9
- package/dist/tokencache.d.ts +2 -10
- package/dist/tokencache.js +14 -6
- package/dist/views.d.ts +1 -1
- package/dist/write.d.ts +2 -1
- package/dist/write.js +4 -3
- package/package.json +1 -1
- package/src/admin.ts +183 -74
- package/src/chains.ts +259 -0
- package/src/client.ts +77 -8
- package/src/fees.ts +3 -2
- package/src/fpool.ts +127 -84
- package/src/generated.ts +613 -458
- package/src/history.ts +41 -13
- package/src/index.ts +1 -0
- package/src/indexer.ts +7 -7
- package/src/pools.ts +16 -14
- package/src/positions.ts +12 -11
- package/src/tokencache.ts +15 -6
- package/src/views.ts +1 -1
- package/src/write.ts +4 -3
package/src/history.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import { getAddress, parseAbiItem, type AbiEvent, type Address, type Hex } from "viem";
|
|
17
17
|
import type { LogswapClient } from "./client.js";
|
|
18
|
+
import { DEFAULT_MAX_LOG_RANGE } from "./chains.js";
|
|
18
19
|
import type { FPoolKind } from "./fpool.js";
|
|
19
20
|
import { bytea, gql } from "./indexer.js";
|
|
20
21
|
import { blockAtOrAfter } from "./fees.js";
|
|
@@ -31,7 +32,7 @@ export interface HistoryLog<A = Record<string, unknown>> {
|
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
export interface EventLogsQuery {
|
|
34
|
-
/** The rindexer GraphQL endpoint; absent
|
|
35
|
+
/** The rindexer GraphQL endpoint; the client's `indexerUrl` when absent, the chain when neither is set. */
|
|
35
36
|
indexer?: string;
|
|
36
37
|
/** The emitter, or several: the four policies share one table per event (indexer phase 1). */
|
|
37
38
|
address: Address | readonly Address[];
|
|
@@ -44,6 +45,7 @@ export interface EventLogsQuery {
|
|
|
44
45
|
event: AbiEvent;
|
|
45
46
|
/** Indexed arguments to match, as `getLogs` takes them; an array matches any of its values. */
|
|
46
47
|
args?: Record<string, unknown>;
|
|
48
|
+
/** The client's `deployBlock` when absent (block 0 without one), on the chain path. */
|
|
47
49
|
fromBlock?: bigint;
|
|
48
50
|
toBlock?: bigint;
|
|
49
51
|
/** Unix seconds: only events at or after this time. On the chain path it becomes a block search. */
|
|
@@ -66,9 +68,10 @@ export async function getEventLogs<A = Record<string, unknown>>(
|
|
|
66
68
|
c: LogswapClient,
|
|
67
69
|
q: EventLogsQuery,
|
|
68
70
|
): Promise<{ logs: HistoryLog<A>[]; source: "indexer" | "chain" }> {
|
|
69
|
-
|
|
71
|
+
const indexer = q.indexer ?? c.indexerUrl;
|
|
72
|
+
if (indexer) {
|
|
70
73
|
try {
|
|
71
|
-
return { logs: await fromIndexer<A>(c, q), source: "indexer" };
|
|
74
|
+
return { logs: await fromIndexer<A>(c, { ...q, indexer }), source: "indexer" };
|
|
72
75
|
} catch {
|
|
73
76
|
/* the indexer is a cache: when it cannot answer, the node can */
|
|
74
77
|
}
|
|
@@ -87,7 +90,7 @@ function contractName(c: LogswapClient, address: Address, event: string): string
|
|
|
87
90
|
const a = address.toLowerCase();
|
|
88
91
|
const is = (x?: Address) => x !== undefined && a === x.toLowerCase();
|
|
89
92
|
const { addresses: d } = c;
|
|
90
|
-
if (is(d.cPoolManager)) return "
|
|
93
|
+
if (is(d.cPoolManager)) return "CPoolManager";
|
|
91
94
|
if (is(d.fPoolManager)) return "FPoolManager";
|
|
92
95
|
if (is(d.router)) return "LogswapRouter";
|
|
93
96
|
if (is(d.policyRegistry)) return "PolicyRegistry";
|
|
@@ -109,7 +112,8 @@ export function indexedContractOf(kind: FPoolKind, event: string): string {
|
|
|
109
112
|
}
|
|
110
113
|
|
|
111
114
|
/** Events whose name two indexed contracts share: postgraphile prefixes their tables. */
|
|
112
|
-
|
|
115
|
+
// `CollectorProposed` / `CollectorAccepted` are C 7 / F 26 and older; `TreasuryProposed` / `TreasuryAccepted` replace them (066).
|
|
116
|
+
const SHARED = new Set(["Swap", "Transfer", "Approval", "OperatorSet", "CollectorProposed", "CollectorAccepted", "TreasuryProposed", "TreasuryAccepted", "Approved", "Listed"]);
|
|
113
117
|
|
|
114
118
|
const plural = (n: string) => (/(s|x|ch|sh)$/.test(n) ? `${n}es` : `${n}s`);
|
|
115
119
|
/** A column's GraphQL name: postgraphile camelCases the snake_case rindexer writes (`F` → `f`). */
|
|
@@ -216,20 +220,43 @@ async function fromIndexer<A>(c: LogswapClient, q: EventLogsQuery): Promise<Hist
|
|
|
216
220
|
/** How far back the chain path looks for a `latest` tape: a tape is recent by definition. */
|
|
217
221
|
export const LATEST_SCAN_BLOCKS = 5_000n;
|
|
218
222
|
|
|
223
|
+
/**
|
|
224
|
+
* `eth_getLogs` over [fromBlock, toBlock] in spans of the client's `maxLogRange` blocks, results in
|
|
225
|
+
* block order. Public endpoints refuse a wide range (or truncate it); a span this size they answer.
|
|
226
|
+
* At most {@link LOG_SPANS_IN_FLIGHT} spans are asked at once.
|
|
227
|
+
*/
|
|
228
|
+
export async function getLogsChunked<L>(c: LogswapClient, params: Record<string, unknown>, fromBlock: bigint, toBlock: bigint): Promise<L[]> {
|
|
229
|
+
const span = c.maxLogRange ?? DEFAULT_MAX_LOG_RANGE;
|
|
230
|
+
if (span <= 0n) throw new Error("logswap: maxLogRange must be positive");
|
|
231
|
+
const ranges: Array<[bigint, bigint]> = [];
|
|
232
|
+
for (let lo = fromBlock; lo <= toBlock; lo += span) ranges.push([lo, lo + span - 1n < toBlock ? lo + span - 1n : toBlock]);
|
|
233
|
+
const out: L[] = [];
|
|
234
|
+
for (let i = 0; i < ranges.length; i += LOG_SPANS_IN_FLIGHT) {
|
|
235
|
+
const got = await Promise.all(
|
|
236
|
+
ranges.slice(i, i + LOG_SPANS_IN_FLIGHT).map(([lo, hi]) => c.public.getLogs({ ...params, fromBlock: lo, toBlock: hi } as never) as unknown as Promise<L[]>),
|
|
237
|
+
);
|
|
238
|
+
for (const g of got) out.push(...g);
|
|
239
|
+
}
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** `eth_getLogs` calls in flight at once in {@link getLogsChunked}. */
|
|
244
|
+
export const LOG_SPANS_IN_FLIGHT = 4;
|
|
245
|
+
|
|
219
246
|
async function fromChain<A>(c: LogswapClient, q: EventLogsQuery): Promise<HistoryLog<A>[]> {
|
|
220
|
-
let fromBlock = q.fromBlock ?? 0n;
|
|
247
|
+
let fromBlock = q.fromBlock ?? c.deployBlock ?? 0n;
|
|
221
248
|
const toBlock = q.toBlock ?? (await c.public.getBlockNumber({ cacheTime: 0 })); // uncached: viem caches the head, and a scan bounded by a stale one misses the block just mined
|
|
222
249
|
if (q.since !== undefined) fromBlock = await blockAtOrAfter(c, BigInt(q.since), fromBlock, toBlock);
|
|
223
250
|
if (q.latest !== undefined && toBlock - fromBlock > LATEST_SCAN_BLOCKS) fromBlock = toBlock - LATEST_SCAN_BLOCKS;
|
|
224
251
|
const all = emitters(q);
|
|
225
252
|
if (all.length === 0) return [];
|
|
226
|
-
let logs =
|
|
253
|
+
let logs = await getLogsChunked<{
|
|
227
254
|
address?: Address;
|
|
228
255
|
args: A;
|
|
229
256
|
blockNumber: bigint;
|
|
230
257
|
transactionHash: Hex;
|
|
231
258
|
logIndex: number;
|
|
232
|
-
}
|
|
259
|
+
}>(c, { address: Array.isArray(q.address) ? all : q.address, event: q.event, args: q.args }, fromBlock, toBlock);
|
|
233
260
|
if (q.transactionHashes) {
|
|
234
261
|
const want = new Set(q.transactionHashes.map((h) => h.toLowerCase()));
|
|
235
262
|
logs = logs.filter((l) => want.has(l.transactionHash.toLowerCase()));
|
|
@@ -268,12 +295,13 @@ export async function getEventsLogs(
|
|
|
268
295
|
},
|
|
269
296
|
): Promise<{ logs: NamedHistoryLog[]; source: "indexer" | "chain" }> {
|
|
270
297
|
const order = (a: HistoryLog, b: HistoryLog) => (a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1);
|
|
271
|
-
|
|
298
|
+
const indexer = q.indexer ?? c.indexerUrl;
|
|
299
|
+
if (indexer && q.events.length > 0) {
|
|
272
300
|
try {
|
|
273
301
|
const got = await Promise.all(
|
|
274
302
|
q.events.map(async (event) => {
|
|
275
303
|
const contract = q.kind ? indexedContractOf(q.kind, event.name) : q.contract;
|
|
276
|
-
return (await fromIndexer<Record<string, unknown>>(c, { ...q, event, contract })).map((l) => ({ ...l, eventName: event.name }));
|
|
304
|
+
return (await fromIndexer<Record<string, unknown>>(c, { ...q, indexer, event, contract })).map((l) => ({ ...l, eventName: event.name }));
|
|
277
305
|
}),
|
|
278
306
|
);
|
|
279
307
|
return { logs: got.flat().sort(order), source: "indexer" };
|
|
@@ -283,17 +311,17 @@ export async function getEventsLogs(
|
|
|
283
311
|
}
|
|
284
312
|
const all = emitters(q);
|
|
285
313
|
if (all.length === 0 || q.events.length === 0) return { logs: [], source: "chain" };
|
|
286
|
-
let fromBlock = q.fromBlock ?? 0n;
|
|
314
|
+
let fromBlock = q.fromBlock ?? c.deployBlock ?? 0n;
|
|
287
315
|
const toBlock = q.toBlock ?? (await c.public.getBlockNumber({ cacheTime: 0 })); // uncached: viem caches the head, and a scan bounded by a stale one misses the block just mined
|
|
288
316
|
if (q.since !== undefined) fromBlock = await blockAtOrAfter(c, BigInt(q.since), fromBlock, toBlock);
|
|
289
|
-
const logs =
|
|
317
|
+
const logs = await getLogsChunked<{
|
|
290
318
|
eventName: string;
|
|
291
319
|
address?: Address;
|
|
292
320
|
args: Record<string, unknown>;
|
|
293
321
|
blockNumber: bigint;
|
|
294
322
|
transactionHash: Hex;
|
|
295
323
|
logIndex: number;
|
|
296
|
-
}
|
|
324
|
+
}>(c, { address: Array.isArray(q.address) ? all : q.address, events: q.events }, fromBlock, toBlock);
|
|
297
325
|
return {
|
|
298
326
|
logs: logs
|
|
299
327
|
.map((l) => ({ eventName: l.eventName, address: l.address ? getAddress(l.address) : all[0]!, args: l.args, blockNumber: l.blockNumber, transactionHash: l.transactionHash, logIndex: l.logIndex }))
|
package/src/index.ts
CHANGED
package/src/indexer.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* The division of labour matters and is not arbitrary: **the indexer enumerates, the chain
|
|
5
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 `
|
|
6
|
+
* this pool" — only the `ClassRegistered` log knows. But an indexed row is a historical fact, and `L`
|
|
7
7
|
* changes with every mint, burn and harvest afterwards. So ids come from here and the current `L`
|
|
8
8
|
* is read on-chain, rather than trusting a number that was true at index time.
|
|
9
9
|
*/
|
|
@@ -108,7 +108,7 @@ export interface RegisteredId {
|
|
|
108
108
|
|
|
109
109
|
/** Every position class ever registered in a pool. Historical — some may since have burnt to zero. */
|
|
110
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, "
|
|
111
|
+
const nodes = await gqlAll<{ id: string; floor: string; cap: string; capped: boolean }>(url, "allClassRegistereds", "id floor cap capped", {
|
|
112
112
|
vars: { pool: { type: "String!", value: bytea(poolId) } },
|
|
113
113
|
condition: "{poolId: $pool}",
|
|
114
114
|
signal,
|
|
@@ -168,7 +168,7 @@ export async function indexerHealthy(url: string, signal?: AbortSignal): Promise
|
|
|
168
168
|
/**
|
|
169
169
|
* Markets, from the indexer rather than a log scan.
|
|
170
170
|
*
|
|
171
|
-
* `discoverMarkets` reads `
|
|
171
|
+
* `discoverMarkets` reads `MarketCreated` logs straight from the node, which is correct until the node
|
|
172
172
|
* stops keeping them. anvil's `--prune-history` drops historical transactions and receipts beyond a
|
|
173
173
|
* window, so on a devnet that mines steadily the deployment's own logs age out and a scan from
|
|
174
174
|
* block 0 returns nothing — while the contracts remain perfectly alive. Any real chain has the same
|
|
@@ -178,7 +178,7 @@ export async function indexerHealthy(url: string, signal?: AbortSignal): Promise
|
|
|
178
178
|
* the more durable path and should be preferred wherever an indexer is configured, with the log
|
|
179
179
|
* scan as the fallback for when it is not.
|
|
180
180
|
*
|
|
181
|
-
* `
|
|
181
|
+
* `MarketCreated` carries every field of the `PoolKey`, so the key is rebuilt exactly and `poolId` is
|
|
182
182
|
* recomputed locally rather than trusted from the row — the same offline derivation the SDK uses
|
|
183
183
|
* everywhere else, so a wrong id fails loudly instead of addressing the wrong pool.
|
|
184
184
|
*/
|
|
@@ -187,7 +187,7 @@ export async function discoverMarketsIndexed(url: string, signal?: AbortSignal):
|
|
|
187
187
|
poolId: Hex; base: Hex; quote: Hex; tickSpacing: string; swapFee: string;
|
|
188
188
|
x0: string; blockNumber: string; txHash: Hex; contractAddress: Hex;
|
|
189
189
|
};
|
|
190
|
-
const nodes = await gqlAll<Row>(url, "
|
|
190
|
+
const nodes = await gqlAll<Row>(url, "allMarketCreateds", "poolId base quote tickSpacing swapFee x0 blockNumber txHash contractAddress", { signal });
|
|
191
191
|
return nodes.map((n) => {
|
|
192
192
|
const key: PoolKey = {
|
|
193
193
|
base: n.base as Address,
|
|
@@ -214,7 +214,7 @@ export async function discoverMarketsIndexed(url: string, signal?: AbortSignal):
|
|
|
214
214
|
*/
|
|
215
215
|
export async function discoverMarketsBest(
|
|
216
216
|
c: LogswapClient,
|
|
217
|
-
url: string | undefined,
|
|
217
|
+
url: string | undefined = c.indexerUrl,
|
|
218
218
|
signal?: AbortSignal,
|
|
219
219
|
): Promise<{ markets: DiscoveredMarket[]; source: "indexer" | "chain" }> {
|
|
220
220
|
if (url) {
|
|
@@ -238,7 +238,7 @@ export async function discoverMarketsBest(
|
|
|
238
238
|
/**
|
|
239
239
|
* The UNCAPPED position classes of a pool, from the CHAIN alone: the lens enumerates live floors
|
|
240
240
|
* (one bitmap bit each), and an uncapped id is a pure function of (key, floor). No indexer.
|
|
241
|
-
* Capped classes need `
|
|
241
|
+
* Capped classes need `ClassRegistered` replay and are absent here — callers that also want those
|
|
242
242
|
* use the indexed `poolPositions` and fall back to this when the indexer is missing or stale.
|
|
243
243
|
*/
|
|
244
244
|
export async function poolPositionsFromChain(c: LogswapClient, key: PoolKey, x: bigint): Promise<PoolPosition[]> {
|
package/src/pools.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Two things worth knowing before reading further.
|
|
5
5
|
*
|
|
6
|
-
* **Markets are discovered from logs, not configuration.** `
|
|
6
|
+
* **Markets are discovered from logs, not configuration.** `MarketCreated` carries the ENTIRE
|
|
7
7
|
* `PoolKey` in the clear, so a client can reconstruct any market's key — and therefore call any
|
|
8
8
|
* keyed function — having never been told the market exists. There is no registry to maintain.
|
|
9
9
|
*
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import { formatUnits, type Address, type Hex } from "viem";
|
|
16
16
|
import { logswapLensAbi, cPoolManagerAbi } from "./generated.js";
|
|
17
|
-
import type
|
|
17
|
+
import { clientChainId, type LogswapClient } from "./client.js";
|
|
18
18
|
import { signerFor } from "./write.js";
|
|
19
19
|
import { readCachedToken, registerCacheClear, writeCachedToken } from "./tokencache.js";
|
|
20
20
|
import { poolId, type PoolKey } from "./keys.js";
|
|
@@ -44,6 +44,8 @@ export interface PoolState {
|
|
|
44
44
|
backstopFloor: bigint;
|
|
45
45
|
/** The market's mint fee, WAD of newly-earning L: proposed at birth, the gate's answer (065). */
|
|
46
46
|
mintFee: bigint;
|
|
47
|
+
/** The market's swap-fee tax, WAD of every fee paid out: the gate's answer at birth, fixed for life (066). */
|
|
48
|
+
swapFeeTax: bigint;
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
/** Read a market's full state by key, through the lens (`getPools`; C version 7). All zero, `initialized` false, for a market nobody opened. */
|
|
@@ -142,7 +144,7 @@ export function lpEdge(state: Pick<PoolState, "F" | "bigSigma">): bigint {
|
|
|
142
144
|
return state.F - state.bigSigma / 2n;
|
|
143
145
|
}
|
|
144
146
|
|
|
145
|
-
/** A market discovered from
|
|
147
|
+
/** A market discovered from a `MarketCreated` log — the full key, plus where it was created. */
|
|
146
148
|
export interface DiscoveredMarket {
|
|
147
149
|
key: PoolKey;
|
|
148
150
|
poolId: Hex;
|
|
@@ -150,26 +152,26 @@ export interface DiscoveredMarket {
|
|
|
150
152
|
x0: bigint;
|
|
151
153
|
blockNumber: bigint;
|
|
152
154
|
transactionHash: Hex;
|
|
153
|
-
/** The manager that emitted the `
|
|
155
|
+
/** The manager that emitted the `MarketCreated` — set when the row came from the indexer. */
|
|
154
156
|
manager?: Address;
|
|
155
157
|
}
|
|
156
158
|
|
|
157
159
|
/**
|
|
158
|
-
* Enumerate markets from `
|
|
160
|
+
* Enumerate markets from `MarketCreated` logs.
|
|
159
161
|
*
|
|
160
162
|
* This is the whole market registry: the event carries every key field rather than just the id,
|
|
161
|
-
* deliberately, so nothing downstream needs a configured list.
|
|
162
|
-
*
|
|
163
|
+
* deliberately, so nothing downstream needs a configured list. The scan starts at the client's
|
|
164
|
+
* `deployBlock` unless `fromBlock` says otherwise.
|
|
163
165
|
*/
|
|
164
166
|
export async function discoverMarkets(
|
|
165
167
|
c: LogswapClient,
|
|
166
|
-
opts: { fromBlock?: bigint; toBlock?: bigint; base?: Address; quote?: Address; /** The rindexer GraphQL endpoint: `
|
|
168
|
+
opts: { fromBlock?: bigint; toBlock?: bigint; base?: Address; quote?: Address; /** The rindexer GraphQL endpoint: `MarketCreated` from there, the node otherwise. */ indexer?: string } = {},
|
|
167
169
|
): Promise<DiscoveredMarket[]> {
|
|
168
|
-
// Narrow the const ABI to the
|
|
170
|
+
// Narrow the const ABI to the MarketCreated entry while KEEPING its literal type, so viem can infer
|
|
169
171
|
// the log shape. `as never` would compile but collapse every arg to `never` at the call site.
|
|
170
|
-
type Ev = Extract<(typeof cPoolManagerAbi)[number], { type: "event"; name: "
|
|
171
|
-
const ev = cPoolManagerAbi.find((x): x is Ev => x.type === "event" && x.name === "
|
|
172
|
-
if (!ev) throw new Error("logswap:
|
|
172
|
+
type Ev = Extract<(typeof cPoolManagerAbi)[number], { type: "event"; name: "MarketCreated" }>;
|
|
173
|
+
const ev = cPoolManagerAbi.find((x): x is Ev => x.type === "event" && x.name === "MarketCreated");
|
|
174
|
+
if (!ev) throw new Error("logswap: MarketCreated event missing from the generated ABI");
|
|
173
175
|
|
|
174
176
|
const args: Record<string, unknown> = {};
|
|
175
177
|
if (opts.base) args.base = opts.base;
|
|
@@ -179,7 +181,7 @@ export async function discoverMarkets(
|
|
|
179
181
|
address: c.addresses.cPoolManager,
|
|
180
182
|
event: ev,
|
|
181
183
|
args,
|
|
182
|
-
fromBlock: opts.fromBlock
|
|
184
|
+
fromBlock: opts.fromBlock, // the client's deployBlock when absent
|
|
183
185
|
toBlock: opts.toBlock,
|
|
184
186
|
});
|
|
185
187
|
|
|
@@ -280,7 +282,7 @@ export async function marketTokens(
|
|
|
280
282
|
{ type: "function", name: "symbol", stateMutability: "view", inputs: [], outputs: [{ type: "string" }] },
|
|
281
283
|
] as const;
|
|
282
284
|
|
|
283
|
-
const chainId =
|
|
285
|
+
const chainId = await clientChainId(c);
|
|
284
286
|
|
|
285
287
|
const readDecimals = async (address: Address): Promise<number> => {
|
|
286
288
|
let last: unknown;
|
package/src/positions.ts
CHANGED
|
@@ -121,7 +121,7 @@ export async function getHolderPosition(
|
|
|
121
121
|
* Resolve an id the manager already knows back to its (pool, floor, cap).
|
|
122
122
|
*
|
|
123
123
|
* The inverse direction — id to class — needs the registry, because the id is a HASH: it cannot be
|
|
124
|
-
* unpacked offline the way `positionId` can be computed offline. `
|
|
124
|
+
* unpacked offline the way `positionId` can be computed offline. `ClassRegistered` carries the same
|
|
125
125
|
* information in the clear, so an indexer never needs this call.
|
|
126
126
|
*
|
|
127
127
|
* **Units.** The lens is inconsistent here and this wrapper hides it: `unpack` returns tick
|
|
@@ -170,7 +170,7 @@ export function partitionIds(ids: readonly bigint[]): { positions: bigint[]; cla
|
|
|
170
170
|
return { positions, claims };
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
-
/** Decode a class's floor and cap from its packed field (as carried by `
|
|
173
|
+
/** Decode a class's floor and cap from its packed field (as carried by `ClassRegistered`). */
|
|
174
174
|
export function describePacked(tickSpacing: bigint, packed: bigint) {
|
|
175
175
|
return unpackFloorCap(tickSpacing, packed);
|
|
176
176
|
}
|
|
@@ -216,7 +216,7 @@ export function presetMintFee(swapFee: bigint): bigint {
|
|
|
216
216
|
*
|
|
217
217
|
* Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
|
|
218
218
|
* capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
|
|
219
|
-
* the protocol's (decisions 058); with no
|
|
219
|
+
* the protocol's (decisions 058); with no treasury it goes through `F` to the LPs already
|
|
220
220
|
* earning, and with none earning it is not charged. This is NOT the swap fee: that one is charged
|
|
221
221
|
* per unit of |Δ log p| on swaps; this is a flat charge on L, once, at mint.
|
|
222
222
|
*
|
|
@@ -237,7 +237,7 @@ export function mintFee(
|
|
|
237
237
|
* Every UNCAPPED position `owner` holds in a market, enumerated fully on-chain by the lens — a
|
|
238
238
|
* bitmap walk plus a balance check per live floor. No indexer, no log scan. Capped classes are
|
|
239
239
|
* not listed here by contract (their candidate set is quadratic in live ticks); they come from
|
|
240
|
-
* `
|
|
240
|
+
* `ClassRegistered` replay when an indexer exists.
|
|
241
241
|
*/
|
|
242
242
|
export interface HeldPositionRow {
|
|
243
243
|
id: bigint;
|
|
@@ -262,7 +262,7 @@ export async function positionsOf(c: LogswapClient, key: PoolKey, owner: Address
|
|
|
262
262
|
return rows.map((r) => ({ id: r.id, floor: r.floor, cap: NO_CAP, capped: false, shares: r.shares, L: r.L, fees: r.fees }));
|
|
263
263
|
}
|
|
264
264
|
|
|
265
|
-
const ID_REGISTERED = parseAbiItem("event
|
|
265
|
+
const ID_REGISTERED = parseAbiItem("event ClassRegistered(uint256 indexed id, bytes32 indexed poolId, int256 floor, int256 cap, bool capped)");
|
|
266
266
|
|
|
267
267
|
/** The class ids `owner` holds in `pool`, from the indexer's `pool_holder` view; null when the indexer cannot answer. */
|
|
268
268
|
async function heldIdsFromView(c: LogswapClient, indexer: string, pool: Hex, owner: Address): Promise<bigint[] | null> {
|
|
@@ -270,12 +270,12 @@ async function heldIdsFromView(c: LogswapClient, indexer: string, pool: Hex, own
|
|
|
270
270
|
const rows = await poolHolders(indexer, { condition: { side: "C", poolId: pool.toLowerCase(), holder: owner.toLowerCase(), manager: c.addresses.cPoolManager.toLowerCase() } });
|
|
271
271
|
return rows.filter((r) => r.balance > 0n && !r.isBackstop).map((r) => r.id);
|
|
272
272
|
} catch {
|
|
273
|
-
return null; // the view is a cache: the
|
|
273
|
+
return null; // the view is a cache: the ClassRegistered replay below answers the same
|
|
274
274
|
}
|
|
275
275
|
}
|
|
276
276
|
|
|
277
|
-
/** Every class id ever registered in `pool` (`
|
|
278
|
-
async function registeredIds(c: LogswapClient, pool: Hex, fromBlock
|
|
277
|
+
/** Every class id ever registered in `pool` (`ClassRegistered`), from the indexer's table or the node. */
|
|
278
|
+
async function registeredIds(c: LogswapClient, pool: Hex, fromBlock?: bigint, indexer?: string): Promise<bigint[]> {
|
|
279
279
|
const { logs } = await getEventLogs<{ id?: bigint }>(c, { indexer, address: c.addresses.cPoolManager, event: ID_REGISTERED, args: { poolId: pool }, fromBlock });
|
|
280
280
|
return logs.map((l) => l.args.id ?? 0n).filter((id) => id !== 0n);
|
|
281
281
|
}
|
|
@@ -285,14 +285,15 @@ async function registeredIds(c: LogswapClient, pool: Hex, fromBlock: bigint, ind
|
|
|
285
285
|
*
|
|
286
286
|
* `positionsOf` (the lens) enumerates the uncapped book from the ladder bitmap in one call and
|
|
287
287
|
* cannot list capped classes: a capped id is a (floor, cap) pair, quadratic in live ticks. This
|
|
288
|
-
* replays `
|
|
288
|
+
* replays `ClassRegistered` — every class is registered once, on first mint, with its floor and
|
|
289
289
|
* cap — then checks the owner's ERC-6909 balance on each and reads the class for its L, so the
|
|
290
290
|
* holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
|
|
291
291
|
* a read per registered class; fine for a pool's lifetime of classes.
|
|
292
292
|
*/
|
|
293
|
-
export async function holdingsOf(c: LogswapClient, key: PoolKey, owner: Address, fromBlock
|
|
293
|
+
export async function holdingsOf(c: LogswapClient, key: PoolKey, owner: Address, fromBlock?: bigint, opts: { /** The rindexer GraphQL endpoint: the owner's held ids from its `pool_holder` view (the class registry as fallback), the node otherwise. Defaults to the client's. */ indexer?: string } = {}): Promise<HeldPositionRow[]> {
|
|
294
294
|
const pool = poolId(key);
|
|
295
|
-
const
|
|
295
|
+
const indexer = opts.indexer ?? c.indexerUrl;
|
|
296
|
+
const ids = (indexer ? await heldIdsFromView(c, indexer, pool, owner) : null) ?? (await registeredIds(c, pool, fromBlock, indexer));
|
|
296
297
|
if (ids.length === 0) return [];
|
|
297
298
|
// one lens call: balance, class L, fees, floor and cap for every id the owner holds
|
|
298
299
|
const rows = (await c.public.readContract({
|
package/src/tokencache.ts
CHANGED
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
* correct rather than merely convenient — on a chain whose addresses are permanent.
|
|
30
30
|
*/
|
|
31
31
|
|
|
32
|
+
import { LOGSWAP_CHAINS } from "./chains.js";
|
|
32
33
|
import type { Address } from "viem";
|
|
33
34
|
|
|
34
35
|
export interface CachedToken {
|
|
@@ -103,14 +104,22 @@ const keyOf = (chainId: number, address: Address) => `${chainId}:${address.toLow
|
|
|
103
104
|
/**
|
|
104
105
|
* Chains whose addresses are not permanent identities: a development node can be wiped and
|
|
105
106
|
* redeployed, and because deployment addresses are derived from a deterministic nonce sequence the
|
|
106
|
-
* SAME address comes back holding a different contract.
|
|
107
|
-
* 31337 anvil's and hardhat's default,
|
|
108
|
-
* persisted with `--state
|
|
107
|
+
* SAME address comes back holding a different contract. Every chain the registry flags `devnet`
|
|
108
|
+
* (31337 anvil's and hardhat's default, 31339 the logswap devnet), plus 1337 (ganache's and
|
|
109
|
+
* hardhat's legacy id) and 31338 (the unimod devnet), persisted with `--state` and documented as
|
|
110
|
+
* resettable by deleting that file.
|
|
109
111
|
*
|
|
110
|
-
* Add to this set rather than removing from it: a chain wrongly listed
|
|
111
|
-
* trips, while one wrongly absent silently serves a stale scale, which is
|
|
112
|
+
* Add to this set rather than removing from it ({@link addResettableChain}): a chain wrongly listed
|
|
113
|
+
* here costs some RPC round trips, while one wrongly absent silently serves a stale scale, which is
|
|
114
|
+
* the bug this exists for.
|
|
112
115
|
*/
|
|
113
|
-
|
|
116
|
+
const resettable = new Set<number>([1337, 31338, ...Object.values(LOGSWAP_CHAINS).filter((ch) => ch.devnet).map((ch) => ch.chainId)]);
|
|
117
|
+
export const RESETTABLE_CHAINS: ReadonlySet<number> = resettable;
|
|
118
|
+
|
|
119
|
+
/** Mark a development chain the registry does not list as resettable. There is no removal. */
|
|
120
|
+
export function addResettableChain(chainId: number): void {
|
|
121
|
+
resettable.add(chainId);
|
|
122
|
+
}
|
|
114
123
|
|
|
115
124
|
/** True when a `(chainId, address)` pair cannot be trusted to name one contract forever. */
|
|
116
125
|
export function isResettableChain(chainId: number): boolean {
|
package/src/views.ts
CHANGED
|
@@ -462,7 +462,7 @@ export async function padStatuses(url: string, q: ViewQuery = {}): Promise<PadSt
|
|
|
462
462
|
|
|
463
463
|
/**
|
|
464
464
|
* Protocol revenue per UTC day, side, source and token. Sources: F `mint_fee` (shares minted to the
|
|
465
|
-
*
|
|
465
|
+
* treasury, valued at the share value) and `pot_cut`; C `accrued` (the swap-fee tax and the mint fee
|
|
466
466
|
* together, from the snapshots) and `collected` — basis `collected`, cash moved, not revenue on top
|
|
467
467
|
* of `accrued`.
|
|
468
468
|
*/
|
package/src/write.ts
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
import type { Address, Hash, Hex } from "viem";
|
|
17
17
|
import type { LogswapClient } from "./client.js";
|
|
18
|
-
import { cPoolManagerAbi, fPoolManagerAbi } from "./generated.js";
|
|
18
|
+
import { cPoolManagerAbi, fPoolManagerAbi, padPolicyAbi } from "./generated.js";
|
|
19
19
|
|
|
20
20
|
/** Disables the deadline check. Deliberate opt-out, never a default. */
|
|
21
21
|
export const NEVER = (1n << 256n) - 1n;
|
|
@@ -102,14 +102,15 @@ const errorKey = (e: AbiError) => `${e.name}(${e.inputs.map((i) => i.type).join(
|
|
|
102
102
|
|
|
103
103
|
/**
|
|
104
104
|
* Every custom error a router call can revert with that the router's own ABI does not declare: the
|
|
105
|
-
* C and F managers' (a mint, a swap or a settlement bubbles them up unchanged)
|
|
105
|
+
* C and F managers' (a mint, a swap or a settlement bubbles them up unchanged), the pad policy's
|
|
106
|
+
* (a launch's `NoThreshold`, `PadExists`, `OutOfRange`; a graduation's `NotGraduated`) and Permit2's.
|
|
106
107
|
* Without them viem can name only the router's errors, and anything raised in the manager comes
|
|
107
108
|
* back as a bare selector.
|
|
108
109
|
*/
|
|
109
110
|
export const routerRevertErrors: readonly AbiError[] = (() => {
|
|
110
111
|
const seen = new Set<string>();
|
|
111
112
|
const out: AbiError[] = [];
|
|
112
|
-
for (const x of [...cPoolManagerAbi, ...fPoolManagerAbi, ...permit2Errors] as readonly { type: string }[]) {
|
|
113
|
+
for (const x of [...cPoolManagerAbi, ...fPoolManagerAbi, ...padPolicyAbi, ...permit2Errors] as readonly { type: string }[]) {
|
|
113
114
|
if (x.type !== "error") continue;
|
|
114
115
|
const e = x as AbiError;
|
|
115
116
|
if (!seen.has(errorKey(e))) {
|