@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/history.ts
DELETED
|
@@ -1,383 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* history.ts — event history from the indexer, shaped like viem's `getLogs`, with the chain as the
|
|
3
|
-
* fallback.
|
|
4
|
-
*
|
|
5
|
-
* Every history read used to be a node `getLogs` from a pool's birth (or block 0) to the head: a
|
|
6
|
-
* full re-download on every page load, seconds each against a distant node, and silently partial
|
|
7
|
-
* once the node pruned its history. rindexer holds the same events with their block timestamps, so
|
|
8
|
-
* a window is a filter rather than a block search and a scan is one paged query.
|
|
9
|
-
*
|
|
10
|
-
* `getEventLogs` takes the ABI event exactly as `getLogs` does and derives the rest from it: the
|
|
11
|
-
* table (`all<Name>s`, or the manager-prefixed name where two contracts share an event name, as the
|
|
12
|
-
* ERC-6909 `Transfer` does), the columns (the inputs' names, camelCased as postgraphile does), and
|
|
13
|
-
* the decoding (the inputs' types — numbers as bigint, addresses checksummed, arrays from JSON).
|
|
14
|
-
* With no indexer URL, or when the query fails, it asks the node and says so in `source`.
|
|
15
|
-
*/
|
|
16
|
-
import { getAddress, parseAbiItem, type AbiEvent, type Address, type Hex } from "viem";
|
|
17
|
-
import type { LogswapClient } from "./client.js";
|
|
18
|
-
import { DEFAULT_MAX_LOG_RANGE } from "./chains.js";
|
|
19
|
-
import type { FPoolKind } from "./fpool.js";
|
|
20
|
-
import { bytea, gql } from "./indexer.js";
|
|
21
|
-
import { blockAtOrAfter } from "./fees.js";
|
|
22
|
-
|
|
23
|
-
/** One event, as `getLogs` returns it plus its block's timestamp (unix seconds). */
|
|
24
|
-
export interface HistoryLog<A = Record<string, unknown>> {
|
|
25
|
-
address: Address;
|
|
26
|
-
args: A;
|
|
27
|
-
blockNumber: bigint;
|
|
28
|
-
/** Unix seconds. Always set from the indexer; set on the chain path only when a window asked for it. */
|
|
29
|
-
blockTimestamp?: number;
|
|
30
|
-
transactionHash: Hex;
|
|
31
|
-
logIndex: number;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export interface EventLogsQuery {
|
|
35
|
-
/** The rindexer GraphQL endpoint; the client's `indexerUrl` when absent, the chain when neither is set. */
|
|
36
|
-
indexer?: string;
|
|
37
|
-
/** The emitter, or several: the four policies share one table per event (indexer phase 1). */
|
|
38
|
-
address: Address | readonly Address[];
|
|
39
|
-
/**
|
|
40
|
-
* The emitter's name in the indexer's config, for an event two indexed contracts share — only
|
|
41
|
-
* needed when the address is not in the client's artifact (a policy the registry approved later):
|
|
42
|
-
* see {@link indexedContractOf}.
|
|
43
|
-
*/
|
|
44
|
-
contract?: string;
|
|
45
|
-
event: AbiEvent;
|
|
46
|
-
/** Indexed arguments to match, as `getLogs` takes them; an array matches any of its values. */
|
|
47
|
-
args?: Record<string, unknown>;
|
|
48
|
-
/** The client's `deployBlock` when absent (block 0 without one), on the chain path. */
|
|
49
|
-
fromBlock?: bigint;
|
|
50
|
-
toBlock?: bigint;
|
|
51
|
-
/** Unix seconds: only events at or after this time. On the chain path it becomes a block search. */
|
|
52
|
-
since?: number;
|
|
53
|
-
/**
|
|
54
|
-
* Only the newest `latest` events (still returned oldest first) — a pool's tape, not its history.
|
|
55
|
-
* On the chain path the node is asked for the last {@link LATEST_SCAN_BLOCKS} blocks only.
|
|
56
|
-
*/
|
|
57
|
-
latest?: number;
|
|
58
|
-
/** Only events from these transactions — e.g. the other events of a page of swaps. */
|
|
59
|
-
transactionHashes?: Hex[];
|
|
60
|
-
signal?: AbortSignal;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* The events, oldest first, and where they came from. `"indexer"` rows lag the head by the
|
|
65
|
-
* indexer's own lag — a few blocks at most on the devnet (logswap-health checks it).
|
|
66
|
-
*/
|
|
67
|
-
export async function getEventLogs<A = Record<string, unknown>>(
|
|
68
|
-
c: LogswapClient,
|
|
69
|
-
q: EventLogsQuery,
|
|
70
|
-
): Promise<{ logs: HistoryLog<A>[]; source: "indexer" | "chain" }> {
|
|
71
|
-
const indexer = q.indexer ?? c.indexerUrl;
|
|
72
|
-
if (indexer) {
|
|
73
|
-
try {
|
|
74
|
-
return { logs: await fromIndexer<A>(c, { ...q, indexer }), source: "indexer" };
|
|
75
|
-
} catch {
|
|
76
|
-
/* the indexer is a cache: when it cannot answer, the node can */
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return { logs: await fromChain<A>(c, q), source: "chain" };
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// ─── the indexer path ────────────────────────────────────────────────────────
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* What the rindexer deployment calls each contract — the prefix of a table two contracts share
|
|
86
|
-
* (logswap-be `devnet/indexer/rindexer.yaml`). Every policy is one factory-tracked contract, `Policy`: the four F policies are
|
|
87
|
-
* one contract (`PolicyF`, F 41) and share its events, so no policy event needs a prefix.
|
|
88
|
-
*/
|
|
89
|
-
function contractName(c: LogswapClient, address: Address, event: string): string | null {
|
|
90
|
-
const a = address.toLowerCase();
|
|
91
|
-
const is = (x?: Address) => x !== undefined && a === x.toLowerCase();
|
|
92
|
-
const { addresses: d } = c;
|
|
93
|
-
// the indexer's own labels for the contracts (its `rindexer.yaml`), not the contracts' names (decision 096): ManagerC / ManagerF / RouterC / RouterF
|
|
94
|
-
if (is(d.managerC)) return "CPoolManager";
|
|
95
|
-
if (is(d.managerF)) return "FPoolManager";
|
|
96
|
-
if (is(d.routerF) || is(d.routerC)) return "LogswapRouter";
|
|
97
|
-
if (is(d.policyRegistry)) return "PolicyRegistry";
|
|
98
|
-
if (is(d.tokenFactory)) return "TokenFactory";
|
|
99
|
-
if (is(d.publicPolicy) || is(d.privatePolicy) || is(d.polPolicy) || is(d.padPolicy)) return indexedContractOf("public", event);
|
|
100
|
-
if (is(d.publicPolicyC)) return indexedContractOf("public", event);
|
|
101
|
-
return null;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* A policy's name in the indexer for one of its events: `Policy`. Pass it as {@link EventLogsQuery.contract} for a policy outside the artifact.
|
|
106
|
-
*/
|
|
107
|
-
export function indexedContractOf(kind: FPoolKind, event: string): string {
|
|
108
|
-
void kind; // one contract serves every F kind (F 41) and `PolicyC` emits the same set (C 18): every policy event is unshared
|
|
109
|
-
return "Policy";
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** Events whose name two indexed contracts share: postgraphile prefixes their tables. */
|
|
113
|
-
// `CollectorProposed` / `CollectorAccepted` are C 7 / F 26 and older; `TreasuryProposed` / `TreasuryAccepted` replace them (066).
|
|
114
|
-
// `SwapState` (was `CSwapState` / `FSwapState`) and `GatesSet` (`PermissionsSet` before decision 098) are `ManagerBase`'s: declared once, emitted by both managers (decisions 096, #112).
|
|
115
|
-
const SHARED = new Set(["PoolCreated", "Swap", "SwapState", "GatesSet", "Transfer", "Approval", "OperatorSet", "CollectorProposed", "CollectorAccepted", "TreasuryProposed", "TreasuryAccepted", "Approved"]);
|
|
116
|
-
|
|
117
|
-
const plural = (n: string) => (/(s|x|ch|sh)$/.test(n) ? `${n}es` : `${n}s`);
|
|
118
|
-
/** A column's GraphQL name: postgraphile camelCases the snake_case rindexer writes (`F` → `f`). */
|
|
119
|
-
const column = (name: string) => name[0]!.toLowerCase() + name.slice(1);
|
|
120
|
-
|
|
121
|
-
export function tableFor(c: LogswapClient, address: Address, event: string, contract?: string): { field: string; type: string } {
|
|
122
|
-
const prefix = SHARED.has(event) ? (contract ?? contractName(c, address, event)) : "";
|
|
123
|
-
if (prefix === null) throw new Error(`history: no indexed contract at ${address}`);
|
|
124
|
-
const type = `${prefix}${event}`;
|
|
125
|
-
return { field: `all${plural(type)}`, type };
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
const emitters = (q: { address: Address | readonly Address[] }): Address[] => (Array.isArray(q.address) ? [...q.address] : [q.address as Address]);
|
|
129
|
-
|
|
130
|
-
/** An ABI parameter as far as decoding needs it: its type and, for a tuple, its components. */
|
|
131
|
-
type Param = { readonly name?: string; readonly type: string; readonly components?: readonly Param[] };
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* A column as the indexer serves it, typed by the ABI: numbers are strings, addresses lowercase, an
|
|
135
|
-
* array a JSON array, and a tuple a JSON object keyed by component name with the same conventions
|
|
136
|
-
* inside (`LiquidityDeployed.baseAssets`, F 38: `{base, amount, priceX36}[]` with string amounts).
|
|
137
|
-
* Decoding recurses into the components, so a tuple's numbers come out as bigints like the node's.
|
|
138
|
-
*/
|
|
139
|
-
function decode(p: Param, v: unknown): unknown {
|
|
140
|
-
if (v === null || v === undefined) return v;
|
|
141
|
-
const { type } = p;
|
|
142
|
-
if (type.endsWith("[]")) return (v as unknown[]).map((x) => decode({ ...p, type: type.slice(0, -2) }, x));
|
|
143
|
-
if (type === "tuple") {
|
|
144
|
-
const o = v as Record<string, unknown>;
|
|
145
|
-
return Object.fromEntries((p.components ?? []).map((c) => [c.name!, decode(c, o[c.name!])]));
|
|
146
|
-
}
|
|
147
|
-
if (type.startsWith("uint") || type.startsWith("int")) return BigInt(v as string);
|
|
148
|
-
if (type === "address") return getAddress(v as string);
|
|
149
|
-
return v; // bool, bytes32 (hex string), string
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
const PAGE = 1000; // postgraphile's cap
|
|
153
|
-
const MAX_PAGES = 200;
|
|
154
|
-
/** Pages in flight at once, after the first. */
|
|
155
|
-
const PARALLEL_PAGES = 8;
|
|
156
|
-
|
|
157
|
-
async function fromIndexer<A>(c: LogswapClient, q: EventLogsQuery): Promise<HistoryLog<A>[]> {
|
|
158
|
-
const all = emitters(q);
|
|
159
|
-
if (all.length === 0) return [];
|
|
160
|
-
const { field, type } = tableFor(c, all[0]!, q.event.name, q.contract);
|
|
161
|
-
const inputs = q.event.inputs;
|
|
162
|
-
const condition: Record<string, unknown> = {};
|
|
163
|
-
const filter: Record<string, unknown> = {};
|
|
164
|
-
for (const [k, v] of Object.entries(q.args ?? {})) {
|
|
165
|
-
const input = inputs.find((i) => i.name === k);
|
|
166
|
-
if (!input || v === undefined || v === null) continue;
|
|
167
|
-
const enc = (x: unknown) => (input.type === "bytes32" ? bytea(x as Hex) : typeof x === "string" ? x.toLowerCase() : String(x));
|
|
168
|
-
if (Array.isArray(v)) {
|
|
169
|
-
// postgraphile's filter cannot match a bytea column; an OR over one leaves this to the chain
|
|
170
|
-
if (input.type === "bytes32") throw new Error("history: OR over a bytes32 argument");
|
|
171
|
-
filter[column(k)] = { in: v.map(enc) };
|
|
172
|
-
} else {
|
|
173
|
-
condition[column(k)] = enc(v);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
const range: Record<string, string> = {};
|
|
177
|
-
if (q.fromBlock !== undefined) range.greaterThanOrEqualTo = q.fromBlock.toString();
|
|
178
|
-
if (q.toBlock !== undefined) range.lessThanOrEqualTo = q.toBlock.toString();
|
|
179
|
-
if (Object.keys(range).length) filter.blockNumber = range;
|
|
180
|
-
if (q.since !== undefined) filter.blockTimestamp = { greaterThanOrEqualTo: new Date(q.since * 1000).toISOString() };
|
|
181
|
-
if (q.transactionHashes) filter.txHash = { in: q.transactionHashes.map((h) => h.toLowerCase()) };
|
|
182
|
-
// a tape is one page from the head, newest first; history is every page from the start
|
|
183
|
-
const pageSize = q.latest ?? PAGE;
|
|
184
|
-
const order = q.latest !== undefined ? "[BLOCK_NUMBER_DESC, LOG_INDEX_DESC]" : "PRIMARY_KEY_ASC";
|
|
185
|
-
|
|
186
|
-
const selection = [...inputs.map((i) => column(i.name!)), "contractAddress", "blockNumber", "blockTimestamp", "txHash", "logIndex"].join(" ");
|
|
187
|
-
// postgraphile refuses a null or an empty filter, so each argument appears only when it has content
|
|
188
|
-
const hasCondition = Object.keys(condition).length > 0;
|
|
189
|
-
const hasFilter = Object.keys(filter).length > 0;
|
|
190
|
-
const decl = `$offset: Int${hasCondition ? `, $condition: ${type}Condition` : ""}${hasFilter ? `, $filter: ${type}Filter` : ""}`;
|
|
191
|
-
const argsOf = `first: ${pageSize}, offset: $offset, orderBy: ${order}${hasCondition ? ", condition: $condition" : ""}${hasFilter ? ", filter: $filter" : ""}`;
|
|
192
|
-
const query = `query History(${decl}) {
|
|
193
|
-
${field}(${argsOf}) {
|
|
194
|
-
totalCount nodes { ${selection} }
|
|
195
|
-
}
|
|
196
|
-
}`;
|
|
197
|
-
type Row = Record<string, unknown>;
|
|
198
|
-
type Conn = { totalCount: number; nodes: Row[] };
|
|
199
|
-
const page = async (offset: number): Promise<Conn> =>
|
|
200
|
-
(await gql<Record<string, Conn>>(q.indexer!, query, { offset, ...(hasCondition ? { condition } : {}), ...(hasFilter ? { filter } : {}) }, q.signal))[field]!;
|
|
201
|
-
// The first page says how many rows there are; the rest are fetched in parallel by offset, not
|
|
202
|
-
// one cursor after another: a day of a busy pool is a few pages, and a round trip to a distant
|
|
203
|
-
// indexer costs more than the page. Ascending by key, rows that land meanwhile append at the end
|
|
204
|
-
// and shift no earlier offset.
|
|
205
|
-
const first = await page(0);
|
|
206
|
-
const rows: Row[] = [...first.nodes];
|
|
207
|
-
if (q.latest === undefined && first.totalCount > first.nodes.length) {
|
|
208
|
-
const pages = Math.ceil(first.totalCount / PAGE);
|
|
209
|
-
if (pages > MAX_PAGES) throw new Error(`history: ${field} has more than ${PAGE * MAX_PAGES} rows`);
|
|
210
|
-
const offsets = Array.from({ length: pages - 1 }, (_, i) => (i + 1) * PAGE);
|
|
211
|
-
for (let i = 0; i < offsets.length; i += PARALLEL_PAGES) {
|
|
212
|
-
const got = await Promise.all(offsets.slice(i, i + PARALLEL_PAGES).map(page));
|
|
213
|
-
for (const g of got) rows.push(...g.nodes);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
// a table can hold a previous deployment's rows (an indexer not yet reset): keep this contract's
|
|
217
|
-
const want = new Map(all.map((a) => [a.toLowerCase(), a]));
|
|
218
|
-
return rows
|
|
219
|
-
.filter((r) => want.has(String(r.contractAddress).toLowerCase()))
|
|
220
|
-
.map((r) => ({
|
|
221
|
-
address: want.get(String(r.contractAddress).toLowerCase())!,
|
|
222
|
-
args: Object.fromEntries(inputs.map((i) => [i.name!, decode(i, r[column(i.name!)])])) as A,
|
|
223
|
-
blockNumber: BigInt(r.blockNumber as string),
|
|
224
|
-
blockTimestamp: Math.floor(Date.parse(r.blockTimestamp as string) / 1000),
|
|
225
|
-
transactionHash: r.txHash as Hex,
|
|
226
|
-
logIndex: Number(r.logIndex),
|
|
227
|
-
}))
|
|
228
|
-
.sort((a, b) => (a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1));
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// ─── the chain path ──────────────────────────────────────────────────────────
|
|
232
|
-
|
|
233
|
-
/** How far back the chain path looks for a `latest` tape: a tape is recent by definition. */
|
|
234
|
-
export const LATEST_SCAN_BLOCKS = 5_000n;
|
|
235
|
-
|
|
236
|
-
/**
|
|
237
|
-
* `eth_getLogs` over [fromBlock, toBlock] in spans of the client's `maxLogRange` blocks, results in
|
|
238
|
-
* block order. Public endpoints refuse a wide range (or truncate it); a span this size they answer.
|
|
239
|
-
* At most {@link LOG_SPANS_IN_FLIGHT} spans are asked at once.
|
|
240
|
-
*/
|
|
241
|
-
export async function getLogsChunked<L>(c: LogswapClient, params: Record<string, unknown>, fromBlock: bigint, toBlock: bigint): Promise<L[]> {
|
|
242
|
-
const span = c.maxLogRange ?? DEFAULT_MAX_LOG_RANGE;
|
|
243
|
-
if (span <= 0n) throw new Error("logswap: maxLogRange must be positive");
|
|
244
|
-
const ranges: Array<[bigint, bigint]> = [];
|
|
245
|
-
for (let lo = fromBlock; lo <= toBlock; lo += span) ranges.push([lo, lo + span - 1n < toBlock ? lo + span - 1n : toBlock]);
|
|
246
|
-
const out: L[] = [];
|
|
247
|
-
for (let i = 0; i < ranges.length; i += LOG_SPANS_IN_FLIGHT) {
|
|
248
|
-
const got = await Promise.all(
|
|
249
|
-
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[]>),
|
|
250
|
-
);
|
|
251
|
-
for (const g of got) out.push(...g);
|
|
252
|
-
}
|
|
253
|
-
return out;
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/** `eth_getLogs` calls in flight at once in {@link getLogsChunked}. */
|
|
257
|
-
export const LOG_SPANS_IN_FLIGHT = 4;
|
|
258
|
-
|
|
259
|
-
async function fromChain<A>(c: LogswapClient, q: EventLogsQuery): Promise<HistoryLog<A>[]> {
|
|
260
|
-
let fromBlock = q.fromBlock ?? c.deployBlock ?? 0n;
|
|
261
|
-
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
|
|
262
|
-
if (q.since !== undefined) fromBlock = await blockAtOrAfter(c, BigInt(q.since), fromBlock, toBlock);
|
|
263
|
-
if (q.latest !== undefined && toBlock - fromBlock > LATEST_SCAN_BLOCKS) fromBlock = toBlock - LATEST_SCAN_BLOCKS;
|
|
264
|
-
const all = emitters(q);
|
|
265
|
-
if (all.length === 0) return [];
|
|
266
|
-
let logs = await getLogsChunked<{
|
|
267
|
-
address?: Address;
|
|
268
|
-
args: A;
|
|
269
|
-
blockNumber: bigint;
|
|
270
|
-
transactionHash: Hex;
|
|
271
|
-
logIndex: number;
|
|
272
|
-
}>(c, { address: Array.isArray(q.address) ? all : q.address, event: q.event, args: q.args }, fromBlock, toBlock);
|
|
273
|
-
if (q.transactionHashes) {
|
|
274
|
-
const want = new Set(q.transactionHashes.map((h) => h.toLowerCase()));
|
|
275
|
-
logs = logs.filter((l) => want.has(l.transactionHash.toLowerCase()));
|
|
276
|
-
}
|
|
277
|
-
if (q.latest !== undefined) logs = logs.slice(-q.latest);
|
|
278
|
-
return logs.map((l) => ({
|
|
279
|
-
address: l.address ? getAddress(l.address) : all[0]!,
|
|
280
|
-
args: l.args,
|
|
281
|
-
blockNumber: l.blockNumber,
|
|
282
|
-
transactionHash: l.transactionHash,
|
|
283
|
-
logIndex: l.logIndex,
|
|
284
|
-
}));
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// ─── several events, and the token factory ────────────────────────────────────
|
|
288
|
-
|
|
289
|
-
/** A row of {@link getEventsLogs}: one of the asked events, named. */
|
|
290
|
-
export interface NamedHistoryLog extends HistoryLog {
|
|
291
|
-
eventName: string;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Several events of one contract (or of several emitters sharing them), merged oldest first and
|
|
296
|
-
* tagged with `eventName` — the shape of viem's multi-event `getLogs`, which is what the chain path
|
|
297
|
-
* runs. One indexer table per event; if any of them cannot answer, the whole read goes to the node,
|
|
298
|
-
* so a history is never half the indexer's and half the node's.
|
|
299
|
-
*/
|
|
300
|
-
export async function getEventsLogs(
|
|
301
|
-
c: LogswapClient,
|
|
302
|
-
q: Omit<EventLogsQuery, "event" | "args" | "latest" | "contract" | "transactionHashes"> & {
|
|
303
|
-
events: readonly AbiEvent[];
|
|
304
|
-
/** The emitters' policy kind, to name a shared event's table for a policy outside the artifact. */
|
|
305
|
-
kind?: FPoolKind;
|
|
306
|
-
/** The emitter's name in the indexer (e.g. `PolicyRegistry`), for a contract outside the artifact; `kind` wins for a policy. */
|
|
307
|
-
contract?: string;
|
|
308
|
-
},
|
|
309
|
-
): Promise<{ logs: NamedHistoryLog[]; source: "indexer" | "chain" }> {
|
|
310
|
-
const order = (a: HistoryLog, b: HistoryLog) => (a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1);
|
|
311
|
-
const indexer = q.indexer ?? c.indexerUrl;
|
|
312
|
-
if (indexer && q.events.length > 0) {
|
|
313
|
-
try {
|
|
314
|
-
const got = await Promise.all(
|
|
315
|
-
q.events.map(async (event) => {
|
|
316
|
-
const contract = q.kind ? indexedContractOf(q.kind, event.name) : q.contract;
|
|
317
|
-
return (await fromIndexer<Record<string, unknown>>(c, { ...q, indexer, event, contract })).map((l) => ({ ...l, eventName: event.name }));
|
|
318
|
-
}),
|
|
319
|
-
);
|
|
320
|
-
return { logs: got.flat().sort(order), source: "indexer" };
|
|
321
|
-
} catch {
|
|
322
|
-
/* the indexer is a cache: the node holds the same events */
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
const all = emitters(q);
|
|
326
|
-
if (all.length === 0 || q.events.length === 0) return { logs: [], source: "chain" };
|
|
327
|
-
let fromBlock = q.fromBlock ?? c.deployBlock ?? 0n;
|
|
328
|
-
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
|
|
329
|
-
if (q.since !== undefined) fromBlock = await blockAtOrAfter(c, BigInt(q.since), fromBlock, toBlock);
|
|
330
|
-
const logs = await getLogsChunked<{
|
|
331
|
-
eventName: string;
|
|
332
|
-
address?: Address;
|
|
333
|
-
args: Record<string, unknown>;
|
|
334
|
-
blockNumber: bigint;
|
|
335
|
-
transactionHash: Hex;
|
|
336
|
-
logIndex: number;
|
|
337
|
-
}>(c, { address: Array.isArray(q.address) ? all : q.address, events: q.events }, fromBlock, toBlock);
|
|
338
|
-
return {
|
|
339
|
-
logs: logs
|
|
340
|
-
.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 }))
|
|
341
|
-
.sort(order),
|
|
342
|
-
source: "chain",
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/** The devnet's token factory event (`src/mocks/TokenFactory.sol`): provenance for every launchable token. */
|
|
347
|
-
export const TOKEN_CREATED = parseAbiItem("event TokenCreated(address indexed creator, address indexed token, string name, string symbol, uint256 supply)");
|
|
348
|
-
|
|
349
|
-
export interface CreatedToken {
|
|
350
|
-
creator: Address;
|
|
351
|
-
token: Address;
|
|
352
|
-
name: string;
|
|
353
|
-
symbol: string;
|
|
354
|
-
supply: bigint;
|
|
355
|
-
blockNumber: bigint;
|
|
356
|
-
/** Unix seconds; set when the indexer answered. */
|
|
357
|
-
blockTimestamp?: number;
|
|
358
|
-
transactionHash: Hex;
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
/**
|
|
362
|
-
* Every token the deployment's factory created, oldest first — the token list's provenance (a token
|
|
363
|
-
* named like a factory token but deployed elsewhere is not in it). Optionally one creator's.
|
|
364
|
-
*/
|
|
365
|
-
export async function tokensCreated(
|
|
366
|
-
c: LogswapClient,
|
|
367
|
-
q: { indexer?: string; creator?: Address; fromBlock?: bigint; signal?: AbortSignal },
|
|
368
|
-
): Promise<{ tokens: CreatedToken[]; source: "indexer" | "chain" }> {
|
|
369
|
-
const factory = c.addresses.tokenFactory;
|
|
370
|
-
if (!factory) throw new Error("logswap: tokensCreated needs addresses.tokenFactory");
|
|
371
|
-
const { logs, source } = await getEventLogs<{ creator: Address; token: Address; name: string; symbol: string; supply: bigint }>(c, {
|
|
372
|
-
indexer: q.indexer,
|
|
373
|
-
address: factory,
|
|
374
|
-
event: TOKEN_CREATED,
|
|
375
|
-
args: q.creator ? { creator: q.creator } : undefined,
|
|
376
|
-
fromBlock: q.fromBlock,
|
|
377
|
-
signal: q.signal,
|
|
378
|
-
});
|
|
379
|
-
return {
|
|
380
|
-
tokens: logs.map((l) => ({ ...l.args, blockNumber: l.blockNumber, ...(l.blockTimestamp !== undefined ? { blockTimestamp: l.blockTimestamp } : {}), transactionHash: l.transactionHash })),
|
|
381
|
-
source,
|
|
382
|
-
};
|
|
383
|
-
}
|
package/src/ids.ts
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ids.ts — the ERC-6909 id namespace, computed OFFLINE.
|
|
3
|
-
*
|
|
4
|
-
* Two kinds of id share one ERC-6909 space, split on **bit 255**:
|
|
5
|
-
*
|
|
6
|
-
* bit 255 SET a position class: (1 << 255) | (keccak256(poolId ‖ packed) >> 1)
|
|
7
|
-
* bit 255 CLEAR a token claim: uint160(tokenAddress)
|
|
8
|
-
*
|
|
9
|
-
* Both are **tier-1 frozen** (docs/app.md). The namespace bit is what lets a wallet UI, a lender, or
|
|
10
|
-
* an indexer tell an LP position from a bearer IOU — and an indexer that ignores it will report
|
|
11
|
-
* phantom LP positions for market makers parking inventory.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import { concatHex, keccak256, pad, toHex, type Address, type Hex } from "viem";
|
|
15
|
-
|
|
16
|
-
/** Packing offset for the signed tick index `k`, so it fits an unsigned 32-bit field. */
|
|
17
|
-
const ID_OFFSET = 1n << 31n;
|
|
18
|
-
/** Sentinel meaning "no cap" — `type(int256).min`. */
|
|
19
|
-
export const NO_CAP = -(2n ** 255n);
|
|
20
|
-
const BIT_255 = 1n << 255n;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* `packed` — the class's (floor, cap) as two 32-bit fields: `kFloor + 2^31` in the low half,
|
|
24
|
-
* `kCap + 2^31` in the high half, or zero there when uncapped.
|
|
25
|
-
*
|
|
26
|
-
* Throws on an off-grid floor or cap rather than producing an id the manager would reject, so a
|
|
27
|
-
* client fails at the call site instead of at the transaction.
|
|
28
|
-
*/
|
|
29
|
-
export function packFloorCap(tickSpacing: bigint, floor: bigint, cap: bigint = NO_CAP): bigint {
|
|
30
|
-
if (tickSpacing <= 0n) throw new Error("tickSpacing must be positive");
|
|
31
|
-
if (floor % tickSpacing !== 0n) throw new Error(`floor ${floor} is off-grid for spacing ${tickSpacing}`);
|
|
32
|
-
let packed = BigInt.asUintN(64, floor / tickSpacing + ID_OFFSET);
|
|
33
|
-
if (cap !== NO_CAP) {
|
|
34
|
-
if (cap <= floor) throw new Error("cap must be strictly above floor");
|
|
35
|
-
if (cap % tickSpacing !== 0n) throw new Error(`cap ${cap} is off-grid for spacing ${tickSpacing}`);
|
|
36
|
-
packed |= BigInt.asUintN(64, cap / tickSpacing + ID_OFFSET) << 32n;
|
|
37
|
-
}
|
|
38
|
-
return packed;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Inverse of {@link packFloorCap}. `capped === false` means the cap field is unset. */
|
|
42
|
-
export function unpackFloorCap(
|
|
43
|
-
tickSpacing: bigint,
|
|
44
|
-
packed: bigint,
|
|
45
|
-
): { floor: bigint; cap: bigint; capped: boolean } {
|
|
46
|
-
const kf = (packed & 0xffffffffn) - ID_OFFSET;
|
|
47
|
-
const hi = packed >> 32n;
|
|
48
|
-
const capped = hi !== 0n;
|
|
49
|
-
return { floor: kf * tickSpacing, cap: capped ? (hi - ID_OFFSET) * tickSpacing : NO_CAP, capped };
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* The position-class id: `(1 << 255) | (keccak256(poolId ‖ packed) >> 1)`.
|
|
54
|
-
*
|
|
55
|
-
* The `>> 1` is what frees bit 255 for the namespace flag, so the hash contributes 255 bits.
|
|
56
|
-
* `abi.encodePacked(bytes32, uint64)` is 40 bytes — 32 for the pool id, 8 for `packed`.
|
|
57
|
-
*/
|
|
58
|
-
export function positionId(poolId_: Hex, tickSpacing: bigint, floor: bigint, cap: bigint = NO_CAP): bigint {
|
|
59
|
-
const packed = packFloorCap(tickSpacing, floor, cap);
|
|
60
|
-
const h = BigInt(keccak256(concatHex([poolId_, pad(toHex(packed), { size: 8 })])));
|
|
61
|
-
return BIT_255 | (h >> 1n);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** A token claim's id is just the token address. */
|
|
65
|
-
export function claimId(token: Address): bigint {
|
|
66
|
-
return BigInt(token);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** True for a position class, false for a token claim. Split every 6909 `Transfer` on this. */
|
|
70
|
-
export function isPosition(id: bigint): boolean {
|
|
71
|
-
return (id & BIT_255) !== 0n;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** The token an id refers to, or `null` if the id is a position rather than a claim. */
|
|
75
|
-
export function claimToken(id: bigint): Address | null {
|
|
76
|
-
if (isPosition(id)) return null;
|
|
77
|
-
return pad(toHex(id), { size: 20 }) as Address;
|
|
78
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* log(swap) SDK — typed, offline-first helpers over the ManagerF / ManagerC, RouterF / RouterC and LensF / LensC surface.
|
|
3
|
-
*
|
|
4
|
-
* The manager/router/lens split is hidden here: callers address markets by `PoolKey` (C) and pool id (F) and
|
|
5
|
-
* never choose a contract. What a caller does choose is the SIDE (`"F"` or `"C"`) where a router is the
|
|
6
|
-
* spender (decision 096: one router per manager, each its own Permit2 spender) — see `onboard.ts`.
|
|
7
|
-
*/
|
|
8
|
-
export * from "./keys.js";
|
|
9
|
-
export * from "./ids.js";
|
|
10
|
-
export * from "./client.js";
|
|
11
|
-
export * from "./chains.js";
|
|
12
|
-
export * from "./pools.js";
|
|
13
|
-
export * from "./positions.js";
|
|
14
|
-
export * from "./write.js";
|
|
15
|
-
export * from "./swap.js";
|
|
16
|
-
export * from "./liquidity.js";
|
|
17
|
-
export * from "./actions.js";
|
|
18
|
-
export * from "./claims.js";
|
|
19
|
-
export * from "./onboard.js";
|
|
20
|
-
export * from "./indexer.js";
|
|
21
|
-
export * from "./tokencache.js";
|
|
22
|
-
export * from "./fpool.js";
|
|
23
|
-
export * from "./fees.js";
|
|
24
|
-
export * from "./history.js";
|
|
25
|
-
export { managerCAbi, managerFAbi, lensCAbi, lensFAbi, routerCAbi, routerFAbi, routerActionsAbi, policyFAbi, policyCAbi, policyRegistryAbi } from "./generated.js";
|
|
26
|
-
export * from "./admin.js";
|