@logswap/sdk 0.5.76 → 0.5.77

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/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 means the chain. */
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
- if (q.indexer) {
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
  }
@@ -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
- const SHARED = new Set(["Transfer", "Approval", "OperatorSet", "CollectorProposed", "CollectorAccepted", "Approved", "Listed"]);
115
+ // `CollectorProposed` / `CollectorAccepted` are C 7 / F 26 and older; `TreasuryProposed` / `TreasuryAccepted` replace them (066).
116
+ const SHARED = new Set(["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 = (await c.public.getLogs({ address: Array.isArray(q.address) ? all : q.address, event: q.event, args: q.args, fromBlock, toBlock } as never)) as unknown as Array<{
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
- if (q.indexer && q.events.length > 0) {
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 = (await c.public.getLogs({ address: Array.isArray(q.address) ? all : q.address, events: q.events, fromBlock, toBlock } as never)) as unknown as Array<{
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
@@ -8,6 +8,7 @@
8
8
  export * from "./keys.js";
9
9
  export * from "./ids.js";
10
10
  export * from "./client.js";
11
+ export * from "./chains.js";
11
12
  export * from "./pools.js";
12
13
  export * from "./positions.js";
13
14
  export * from "./write.js";
package/src/indexer.ts CHANGED
@@ -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) {
package/src/pools.ts CHANGED
@@ -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 { LogswapClient } from "./client.js";
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. */
@@ -158,8 +160,8 @@ export interface DiscoveredMarket {
158
160
  * Enumerate markets from `Initialize` 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. Pass `fromBlock` as the manager's
162
- * deployment block — scanning from genesis is slow and pointless.
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,
@@ -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 ?? 0n,
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 = c.public.chain?.id ?? (await c.public.getChainId());
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
@@ -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 collector it goes through `F` to the LPs already
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
  *
@@ -275,7 +275,7 @@ async function heldIdsFromView(c: LogswapClient, indexer: string, pool: Hex, own
275
275
  }
276
276
 
277
277
  /** Every class id ever registered in `pool` (`IdRegistered`), from the indexer's table or the node. */
278
- async function registeredIds(c: LogswapClient, pool: Hex, fromBlock: bigint, indexer?: string): Promise<bigint[]> {
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
  }
@@ -290,9 +290,10 @@ async function registeredIds(c: LogswapClient, pool: Hex, fromBlock: bigint, ind
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: bigint = 0n, opts: { /** The rindexer GraphQL endpoint: the owner's held ids from its `pool_holder` view (the class registry as fallback), the node otherwise. */ indexer?: string } = {}): Promise<HeldPositionRow[]> {
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 ids = (opts.indexer ? await heldIdsFromView(c, opts.indexer, pool, owner) : null) ?? (await registeredIds(c, pool, fromBlock, opts.indexer));
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. 1337 is ganache's and hardhat's legacy id,
107
- * 31337 anvil's and hardhat's default, 31338 and 31339 the unimod and logswap devnets — both
108
- * persisted with `--state`, both documented as resettable by deleting that file.
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 here costs some RPC round
111
- * trips, while one wrongly absent silently serves a stale scale, which is the bug this exists for.
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
- export const RESETTABLE_CHAINS: ReadonlySet<number> = new Set([1337, 31337, 31338, 31339]);
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
- * collector, valued at the share value) and `pot_cut`; C `accrued` (the swap-fee tax and the mint fee
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) and Permit2's.
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))) {