@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/dist/history.d.ts CHANGED
@@ -27,7 +27,7 @@ export interface HistoryLog<A = Record<string, unknown>> {
27
27
  logIndex: number;
28
28
  }
29
29
  export interface EventLogsQuery {
30
- /** The rindexer GraphQL endpoint; absent means the chain. */
30
+ /** The rindexer GraphQL endpoint; the client's `indexerUrl` when absent, the chain when neither is set. */
31
31
  indexer?: string;
32
32
  /** The emitter, or several: the four policies share one table per event (indexer phase 1). */
33
33
  address: Address | readonly Address[];
@@ -40,6 +40,7 @@ export interface EventLogsQuery {
40
40
  event: AbiEvent;
41
41
  /** Indexed arguments to match, as `getLogs` takes them; an array matches any of its values. */
42
42
  args?: Record<string, unknown>;
43
+ /** The client's `deployBlock` when absent (block 0 without one), on the chain path. */
43
44
  fromBlock?: bigint;
44
45
  toBlock?: bigint;
45
46
  /** Unix seconds: only events at or after this time. On the chain path it becomes a block search. */
@@ -72,6 +73,14 @@ export declare function tableFor(c: LogswapClient, address: Address, event: stri
72
73
  };
73
74
  /** How far back the chain path looks for a `latest` tape: a tape is recent by definition. */
74
75
  export declare const LATEST_SCAN_BLOCKS = 5000n;
76
+ /**
77
+ * `eth_getLogs` over [fromBlock, toBlock] in spans of the client's `maxLogRange` blocks, results in
78
+ * block order. Public endpoints refuse a wide range (or truncate it); a span this size they answer.
79
+ * At most {@link LOG_SPANS_IN_FLIGHT} spans are asked at once.
80
+ */
81
+ export declare function getLogsChunked<L>(c: LogswapClient, params: Record<string, unknown>, fromBlock: bigint, toBlock: bigint): Promise<L[]>;
82
+ /** `eth_getLogs` calls in flight at once in {@link getLogsChunked}. */
83
+ export declare const LOG_SPANS_IN_FLIGHT = 4;
75
84
  /** A row of {@link getEventsLogs}: one of the asked events, named. */
76
85
  export interface NamedHistoryLog extends HistoryLog {
77
86
  eventName: string;
package/dist/history.js CHANGED
@@ -14,6 +14,7 @@
14
14
  * With no indexer URL, or when the query fails, it asks the node and says so in `source`.
15
15
  */
16
16
  import { getAddress, parseAbiItem } from "viem";
17
+ import { DEFAULT_MAX_LOG_RANGE } from "./chains.js";
17
18
  import { bytea, gql } from "./indexer.js";
18
19
  import { blockAtOrAfter } from "./fees.js";
19
20
  /**
@@ -21,9 +22,10 @@ import { blockAtOrAfter } from "./fees.js";
21
22
  * indexer's own lag — a few blocks at most on the devnet (logswap-health checks it).
22
23
  */
23
24
  export async function getEventLogs(c, q) {
24
- if (q.indexer) {
25
+ const indexer = q.indexer ?? c.indexerUrl;
26
+ if (indexer) {
25
27
  try {
26
- return { logs: await fromIndexer(c, q), source: "indexer" };
28
+ return { logs: await fromIndexer(c, { ...q, indexer }), source: "indexer" };
27
29
  }
28
30
  catch {
29
31
  /* the indexer is a cache: when it cannot answer, the node can */
@@ -42,7 +44,7 @@ function contractName(c, address, event) {
42
44
  const is = (x) => x !== undefined && a === x.toLowerCase();
43
45
  const { addresses: d } = c;
44
46
  if (is(d.cPoolManager))
45
- return "LogswapManager";
47
+ return "CPoolManager";
46
48
  if (is(d.fPoolManager))
47
49
  return "FPoolManager";
48
50
  if (is(d.router))
@@ -71,7 +73,8 @@ export function indexedContractOf(kind, event) {
71
73
  return "Policy";
72
74
  }
73
75
  /** Events whose name two indexed contracts share: postgraphile prefixes their tables. */
74
- const SHARED = new Set(["Transfer", "Approval", "OperatorSet", "CollectorProposed", "CollectorAccepted", "Approved", "Listed"]);
76
+ // `CollectorProposed` / `CollectorAccepted` are C 7 / F 26 and older; `TreasuryProposed` / `TreasuryAccepted` replace them (066).
77
+ const SHARED = new Set(["Swap", "Transfer", "Approval", "OperatorSet", "CollectorProposed", "CollectorAccepted", "TreasuryProposed", "TreasuryAccepted", "Approved", "Listed"]);
75
78
  const plural = (n) => (/(s|x|ch|sh)$/.test(n) ? `${n}es` : `${n}s`);
76
79
  /** A column's GraphQL name: postgraphile camelCases the snake_case rindexer writes (`F` → `f`). */
77
80
  const column = (name) => name[0].toLowerCase() + name.slice(1);
@@ -181,8 +184,30 @@ async function fromIndexer(c, q) {
181
184
  // ─── the chain path ──────────────────────────────────────────────────────────
182
185
  /** How far back the chain path looks for a `latest` tape: a tape is recent by definition. */
183
186
  export const LATEST_SCAN_BLOCKS = 5000n;
187
+ /**
188
+ * `eth_getLogs` over [fromBlock, toBlock] in spans of the client's `maxLogRange` blocks, results in
189
+ * block order. Public endpoints refuse a wide range (or truncate it); a span this size they answer.
190
+ * At most {@link LOG_SPANS_IN_FLIGHT} spans are asked at once.
191
+ */
192
+ export async function getLogsChunked(c, params, fromBlock, toBlock) {
193
+ const span = c.maxLogRange ?? DEFAULT_MAX_LOG_RANGE;
194
+ if (span <= 0n)
195
+ throw new Error("logswap: maxLogRange must be positive");
196
+ const ranges = [];
197
+ for (let lo = fromBlock; lo <= toBlock; lo += span)
198
+ ranges.push([lo, lo + span - 1n < toBlock ? lo + span - 1n : toBlock]);
199
+ const out = [];
200
+ for (let i = 0; i < ranges.length; i += LOG_SPANS_IN_FLIGHT) {
201
+ const got = await Promise.all(ranges.slice(i, i + LOG_SPANS_IN_FLIGHT).map(([lo, hi]) => c.public.getLogs({ ...params, fromBlock: lo, toBlock: hi })));
202
+ for (const g of got)
203
+ out.push(...g);
204
+ }
205
+ return out;
206
+ }
207
+ /** `eth_getLogs` calls in flight at once in {@link getLogsChunked}. */
208
+ export const LOG_SPANS_IN_FLIGHT = 4;
184
209
  async function fromChain(c, q) {
185
- let fromBlock = q.fromBlock ?? 0n;
210
+ let fromBlock = q.fromBlock ?? c.deployBlock ?? 0n;
186
211
  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
187
212
  if (q.since !== undefined)
188
213
  fromBlock = await blockAtOrAfter(c, BigInt(q.since), fromBlock, toBlock);
@@ -191,7 +216,7 @@ async function fromChain(c, q) {
191
216
  const all = emitters(q);
192
217
  if (all.length === 0)
193
218
  return [];
194
- let logs = (await c.public.getLogs({ address: Array.isArray(q.address) ? all : q.address, event: q.event, args: q.args, fromBlock, toBlock }));
219
+ let logs = await getLogsChunked(c, { address: Array.isArray(q.address) ? all : q.address, event: q.event, args: q.args }, fromBlock, toBlock);
195
220
  if (q.transactionHashes) {
196
221
  const want = new Set(q.transactionHashes.map((h) => h.toLowerCase()));
197
222
  logs = logs.filter((l) => want.has(l.transactionHash.toLowerCase()));
@@ -214,11 +239,12 @@ async function fromChain(c, q) {
214
239
  */
215
240
  export async function getEventsLogs(c, q) {
216
241
  const order = (a, b) => (a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1);
217
- if (q.indexer && q.events.length > 0) {
242
+ const indexer = q.indexer ?? c.indexerUrl;
243
+ if (indexer && q.events.length > 0) {
218
244
  try {
219
245
  const got = await Promise.all(q.events.map(async (event) => {
220
246
  const contract = q.kind ? indexedContractOf(q.kind, event.name) : q.contract;
221
- return (await fromIndexer(c, { ...q, event, contract })).map((l) => ({ ...l, eventName: event.name }));
247
+ return (await fromIndexer(c, { ...q, indexer, event, contract })).map((l) => ({ ...l, eventName: event.name }));
222
248
  }));
223
249
  return { logs: got.flat().sort(order), source: "indexer" };
224
250
  }
@@ -229,11 +255,11 @@ export async function getEventsLogs(c, q) {
229
255
  const all = emitters(q);
230
256
  if (all.length === 0 || q.events.length === 0)
231
257
  return { logs: [], source: "chain" };
232
- let fromBlock = q.fromBlock ?? 0n;
258
+ let fromBlock = q.fromBlock ?? c.deployBlock ?? 0n;
233
259
  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
234
260
  if (q.since !== undefined)
235
261
  fromBlock = await blockAtOrAfter(c, BigInt(q.since), fromBlock, toBlock);
236
- const logs = (await c.public.getLogs({ address: Array.isArray(q.address) ? all : q.address, events: q.events, fromBlock, toBlock }));
262
+ const logs = await getLogsChunked(c, { address: Array.isArray(q.address) ? all : q.address, events: q.events }, fromBlock, toBlock);
237
263
  return {
238
264
  logs: logs
239
265
  .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/dist/index.d.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/dist/index.js 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/dist/indexer.d.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 `IdRegistered` log knows. But an indexed row is a historical fact, and `L`
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
  */
@@ -72,7 +72,7 @@ export declare function indexerHealthy(url: string, signal?: AbortSignal): Promi
72
72
  /**
73
73
  * Markets, from the indexer rather than a log scan.
74
74
  *
75
- * `discoverMarkets` reads `Initialize` logs straight from the node, which is correct until the node
75
+ * `discoverMarkets` reads `MarketCreated` logs straight from the node, which is correct until the node
76
76
  * stops keeping them. anvil's `--prune-history` drops historical transactions and receipts beyond a
77
77
  * window, so on a devnet that mines steadily the deployment's own logs age out and a scan from
78
78
  * block 0 returns nothing — while the contracts remain perfectly alive. Any real chain has the same
@@ -82,7 +82,7 @@ export declare function indexerHealthy(url: string, signal?: AbortSignal): Promi
82
82
  * the more durable path and should be preferred wherever an indexer is configured, with the log
83
83
  * scan as the fallback for when it is not.
84
84
  *
85
- * `Initialize` carries every field of the `PoolKey`, so the key is rebuilt exactly and `poolId` is
85
+ * `MarketCreated` carries every field of the `PoolKey`, so the key is rebuilt exactly and `poolId` is
86
86
  * recomputed locally rather than trusted from the row — the same offline derivation the SDK uses
87
87
  * everywhere else, so a wrong id fails loudly instead of addressing the wrong pool.
88
88
  */
@@ -93,14 +93,14 @@ export declare function discoverMarketsIndexed(url: string, signal?: AbortSignal
93
93
  * The order matters: the indexer is authoritative for history, the node is authoritative for state.
94
94
  * A market the node can no longer tell you about is still a market.
95
95
  */
96
- export declare function discoverMarketsBest(c: LogswapClient, url: string | undefined, signal?: AbortSignal): Promise<{
96
+ export declare function discoverMarketsBest(c: LogswapClient, url?: string | undefined, signal?: AbortSignal): Promise<{
97
97
  markets: DiscoveredMarket[];
98
98
  source: "indexer" | "chain";
99
99
  }>;
100
100
  /**
101
101
  * The UNCAPPED position classes of a pool, from the CHAIN alone: the lens enumerates live floors
102
102
  * (one bitmap bit each), and an uncapped id is a pure function of (key, floor). No indexer.
103
- * Capped classes need `IdRegistered` replay and are absent here — callers that also want those
103
+ * Capped classes need `ClassRegistered` replay and are absent here — callers that also want those
104
104
  * use the indexed `poolPositions` and fall back to this when the indexer is missing or stale.
105
105
  */
106
106
  export declare function poolPositionsFromChain(c: LogswapClient, key: PoolKey, x: bigint): Promise<PoolPosition[]>;
package/dist/indexer.js 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 `IdRegistered` log knows. But an indexed row is a historical fact, and `L`
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
  */
@@ -81,7 +81,7 @@ export async function gqlAll(url, field, selection, opts = {}) {
81
81
  }
82
82
  /** Every position class ever registered in a pool. Historical — some may since have burnt to zero. */
83
83
  export async function registeredIds(url, poolId, signal) {
84
- const nodes = await gqlAll(url, "allIdRegistereds", "id floor cap capped", {
84
+ const nodes = await gqlAll(url, "allClassRegistereds", "id floor cap capped", {
85
85
  vars: { pool: { type: "String!", value: bytea(poolId) } },
86
86
  condition: "{poolId: $pool}",
87
87
  signal,
@@ -123,7 +123,7 @@ export async function indexerHealthy(url, signal) {
123
123
  /**
124
124
  * Markets, from the indexer rather than a log scan.
125
125
  *
126
- * `discoverMarkets` reads `Initialize` logs straight from the node, which is correct until the node
126
+ * `discoverMarkets` reads `MarketCreated` logs straight from the node, which is correct until the node
127
127
  * stops keeping them. anvil's `--prune-history` drops historical transactions and receipts beyond a
128
128
  * window, so on a devnet that mines steadily the deployment's own logs age out and a scan from
129
129
  * block 0 returns nothing — while the contracts remain perfectly alive. Any real chain has the same
@@ -133,12 +133,12 @@ export async function indexerHealthy(url, signal) {
133
133
  * the more durable path and should be preferred wherever an indexer is configured, with the log
134
134
  * scan as the fallback for when it is not.
135
135
  *
136
- * `Initialize` carries every field of the `PoolKey`, so the key is rebuilt exactly and `poolId` is
136
+ * `MarketCreated` carries every field of the `PoolKey`, so the key is rebuilt exactly and `poolId` is
137
137
  * recomputed locally rather than trusted from the row — the same offline derivation the SDK uses
138
138
  * everywhere else, so a wrong id fails loudly instead of addressing the wrong pool.
139
139
  */
140
140
  export async function discoverMarketsIndexed(url, signal) {
141
- const nodes = await gqlAll(url, "allInitializes", "poolId base quote tickSpacing swapFee x0 blockNumber txHash contractAddress", { signal });
141
+ const nodes = await gqlAll(url, "allMarketCreateds", "poolId base quote tickSpacing swapFee x0 blockNumber txHash contractAddress", { signal });
142
142
  return nodes.map((n) => {
143
143
  const key = {
144
144
  base: n.base,
@@ -162,7 +162,7 @@ export async function discoverMarketsIndexed(url, signal) {
162
162
  * The order matters: the indexer is authoritative for history, the node is authoritative for state.
163
163
  * A market the node can no longer tell you about is still a market.
164
164
  */
165
- export async function discoverMarketsBest(c, url, signal) {
165
+ export async function discoverMarketsBest(c, url = c.indexerUrl, signal) {
166
166
  if (url) {
167
167
  try {
168
168
  const markets = await discoverMarketsIndexed(url, signal);
@@ -185,7 +185,7 @@ export async function discoverMarketsBest(c, url, signal) {
185
185
  /**
186
186
  * The UNCAPPED position classes of a pool, from the CHAIN alone: the lens enumerates live floors
187
187
  * (one bitmap bit each), and an uncapped id is a pure function of (key, floor). No indexer.
188
- * Capped classes need `IdRegistered` replay and are absent here — callers that also want those
188
+ * Capped classes need `ClassRegistered` replay and are absent here — callers that also want those
189
189
  * use the indexed `poolPositions` and fall back to this when the indexer is missing or stale.
190
190
  */
191
191
  export async function poolPositionsFromChain(c, key, x) {
package/dist/pools.d.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.** `Initialize` carries the ENTIRE
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
  *
@@ -12,7 +12,7 @@
12
12
  * conversion is. Prefer comparing in log space when precision matters.
13
13
  */
14
14
  import { type Address, type Hex } from "viem";
15
- import type { LogswapClient } from "./client.js";
15
+ import { type LogswapClient } from "./client.js";
16
16
  import { type PoolKey } from "./keys.js";
17
17
  /**
18
18
  * A market's scalar state, field-for-field with `CPoolState.PoolView` — what the manager's `getPool`
@@ -37,6 +37,8 @@ export interface PoolState {
37
37
  backstopFloor: bigint;
38
38
  /** The market's mint fee, WAD of newly-earning L: proposed at birth, the gate's answer (065). */
39
39
  mintFee: bigint;
40
+ /** The market's swap-fee tax, WAD of every fee paid out: the gate's answer at birth, fixed for life (066). */
41
+ swapFeeTax: bigint;
40
42
  }
41
43
  /** Read a market's full state by key, through the lens (`getPools`; C version 7). All zero, `initialized` false, for a market nobody opened. */
42
44
  export declare function getPool(c: LogswapClient, key: PoolKey): Promise<PoolState>;
@@ -97,7 +99,7 @@ export declare function cListable(price: number, baseDecimals: number, quoteDeci
97
99
  * Signed: negative means variation has outrun fee income over the pool's life.
98
100
  */
99
101
  export declare function lpEdge(state: Pick<PoolState, "F" | "bigSigma">): bigint;
100
- /** A market discovered from an `Initialize` log — the full key, plus where it was created. */
102
+ /** A market discovered from a `MarketCreated` log — the full key, plus where it was created. */
101
103
  export interface DiscoveredMarket {
102
104
  key: PoolKey;
103
105
  poolId: Hex;
@@ -105,21 +107,21 @@ export interface DiscoveredMarket {
105
107
  x0: bigint;
106
108
  blockNumber: bigint;
107
109
  transactionHash: Hex;
108
- /** The manager that emitted the `Initialize` — set when the row came from the indexer. */
110
+ /** The manager that emitted the `MarketCreated` — set when the row came from the indexer. */
109
111
  manager?: Address;
110
112
  }
111
113
  /**
112
- * Enumerate markets from `Initialize` logs.
114
+ * Enumerate markets from `MarketCreated` logs.
113
115
  *
114
116
  * This is the whole market registry: the event carries every key field rather than just the id,
115
- * deliberately, so nothing downstream needs a configured list. Pass `fromBlock` as the manager's
116
- * deployment block — scanning from genesis is slow and pointless.
117
+ * deliberately, so nothing downstream needs a configured list. The scan starts at the client's
118
+ * `deployBlock` unless `fromBlock` says otherwise.
117
119
  */
118
120
  export declare function discoverMarkets(c: LogswapClient, opts?: {
119
121
  fromBlock?: bigint;
120
122
  toBlock?: bigint;
121
123
  base?: Address;
122
- quote?: Address; /** The rindexer GraphQL endpoint: `Initialize` from there, the node otherwise. */
124
+ quote?: Address; /** The rindexer GraphQL endpoint: `MarketCreated` from there, the node otherwise. */
123
125
  indexer?: string;
124
126
  }): Promise<DiscoveredMarket[]>;
125
127
  /**
package/dist/pools.js 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.** `Initialize` carries the ENTIRE
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
  *
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { formatUnits } from "viem";
15
15
  import { logswapLensAbi, cPoolManagerAbi } from "./generated.js";
16
+ import { clientChainId } from "./client.js";
16
17
  import { signerFor } from "./write.js";
17
18
  import { readCachedToken, registerCacheClear, writeCachedToken } from "./tokencache.js";
18
19
  import { poolId } from "./keys.js";
@@ -102,16 +103,16 @@ export function lpEdge(state) {
102
103
  return state.F - state.bigSigma / 2n;
103
104
  }
104
105
  /**
105
- * Enumerate markets from `Initialize` logs.
106
+ * Enumerate markets from `MarketCreated` logs.
106
107
  *
107
108
  * This is the whole market registry: the event carries every key field rather than just the id,
108
- * deliberately, so nothing downstream needs a configured list. Pass `fromBlock` as the manager's
109
- * deployment block — scanning from genesis is slow and pointless.
109
+ * deliberately, so nothing downstream needs a configured list. The scan starts at the client's
110
+ * `deployBlock` unless `fromBlock` says otherwise.
110
111
  */
111
112
  export async function discoverMarkets(c, opts = {}) {
112
- const ev = cPoolManagerAbi.find((x) => x.type === "event" && x.name === "Initialize");
113
+ const ev = cPoolManagerAbi.find((x) => x.type === "event" && x.name === "MarketCreated");
113
114
  if (!ev)
114
- throw new Error("logswap: Initialize event missing from the generated ABI");
115
+ throw new Error("logswap: MarketCreated event missing from the generated ABI");
115
116
  const args = {};
116
117
  if (opts.base)
117
118
  args.base = opts.base;
@@ -122,7 +123,7 @@ export async function discoverMarkets(c, opts = {}) {
122
123
  address: c.addresses.cPoolManager,
123
124
  event: ev,
124
125
  args,
125
- fromBlock: opts.fromBlock ?? 0n,
126
+ fromBlock: opts.fromBlock, // the client's deployBlock when absent
126
127
  toBlock: opts.toBlock,
127
128
  });
128
129
  return logs.map((l) => {
@@ -204,7 +205,7 @@ export async function marketTokens(c, key) {
204
205
  { type: "function", name: "decimals", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
205
206
  { type: "function", name: "symbol", stateMutability: "view", inputs: [], outputs: [{ type: "string" }] },
206
207
  ];
207
- const chainId = c.public.chain?.id ?? (await c.public.getChainId());
208
+ const chainId = await clientChainId(c);
208
209
  const readDecimals = async (address) => {
209
210
  let last;
210
211
  for (let attempt = 0; attempt < 3; attempt++) {
@@ -56,7 +56,7 @@ export declare function getHolderPosition(c: LogswapClient, key: PoolKey, owner:
56
56
  * Resolve an id the manager already knows back to its (pool, floor, cap).
57
57
  *
58
58
  * The inverse direction — id to class — needs the registry, because the id is a HASH: it cannot be
59
- * unpacked offline the way `positionId` can be computed offline. `IdRegistered` carries the same
59
+ * unpacked offline the way `positionId` can be computed offline. `ClassRegistered` carries the same
60
60
  * information in the clear, so an indexer never needs this call.
61
61
  *
62
62
  * **Units.** The lens is inconsistent here and this wrapper hides it: `unpack` returns tick
@@ -83,7 +83,7 @@ export declare function partitionIds(ids: readonly bigint[]): {
83
83
  positions: bigint[];
84
84
  claims: bigint[];
85
85
  };
86
- /** Decode a class's floor and cap from its packed field (as carried by `IdRegistered`). */
86
+ /** Decode a class's floor and cap from its packed field (as carried by `ClassRegistered`). */
87
87
  export declare function describePacked(tickSpacing: bigint, packed: bigint): {
88
88
  floor: bigint;
89
89
  cap: bigint;
@@ -123,7 +123,7 @@ export declare function presetMintFee(swapFee: bigint): bigint;
123
123
  *
124
124
  * Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
125
125
  * capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
126
- * the protocol's (decisions 058); with no collector it goes through `F` to the LPs already
126
+ * the protocol's (decisions 058); with no treasury it goes through `F` to the LPs already
127
127
  * earning, and with none earning it is not charged. This is NOT the swap fee: that one is charged
128
128
  * per unit of |Δ log p| on swaps; this is a flat charge on L, once, at mint.
129
129
  *
@@ -141,7 +141,7 @@ export declare function mintFee(p: {
141
141
  * Every UNCAPPED position `owner` holds in a market, enumerated fully on-chain by the lens — a
142
142
  * bitmap walk plus a balance check per live floor. No indexer, no log scan. Capped classes are
143
143
  * not listed here by contract (their candidate set is quadratic in live ticks); they come from
144
- * `IdRegistered` replay when an indexer exists.
144
+ * `ClassRegistered` replay when an indexer exists.
145
145
  */
146
146
  export interface HeldPositionRow {
147
147
  id: bigint;
@@ -161,7 +161,7 @@ export declare function positionsOf(c: LogswapClient, key: PoolKey, owner: Addre
161
161
  *
162
162
  * `positionsOf` (the lens) enumerates the uncapped book from the ladder bitmap in one call and
163
163
  * cannot list capped classes: a capped id is a (floor, cap) pair, quadratic in live ticks. This
164
- * replays `IdRegistered` — every class is registered once, on first mint, with its floor and
164
+ * replays `ClassRegistered` — every class is registered once, on first mint, with its floor and
165
165
  * cap — then checks the owner's ERC-6909 balance on each and reads the class for its L, so the
166
166
  * holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
167
167
  * a read per registered class; fine for a pool's lifetime of classes.
package/dist/positions.js CHANGED
@@ -81,7 +81,7 @@ export async function getHolderPosition(c, key, owner, floor, cap = NO_CAP) {
81
81
  * Resolve an id the manager already knows back to its (pool, floor, cap).
82
82
  *
83
83
  * The inverse direction — id to class — needs the registry, because the id is a HASH: it cannot be
84
- * unpacked offline the way `positionId` can be computed offline. `IdRegistered` carries the same
84
+ * unpacked offline the way `positionId` can be computed offline. `ClassRegistered` carries the same
85
85
  * information in the clear, so an indexer never needs this call.
86
86
  *
87
87
  * **Units.** The lens is inconsistent here and this wrapper hides it: `unpack` returns tick
@@ -119,7 +119,7 @@ export function partitionIds(ids) {
119
119
  (isPosition(id) ? positions : claims).push(id);
120
120
  return { positions, claims };
121
121
  }
122
- /** Decode a class's floor and cap from its packed field (as carried by `IdRegistered`). */
122
+ /** Decode a class's floor and cap from its packed field (as carried by `ClassRegistered`). */
123
123
  export function describePacked(tickSpacing, packed) {
124
124
  return unpackFloorCap(tickSpacing, packed);
125
125
  }
@@ -160,7 +160,7 @@ export function presetMintFee(swapFee) {
160
160
  *
161
161
  * Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
162
162
  * capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
163
- * the protocol's (decisions 058); with no collector it goes through `F` to the LPs already
163
+ * the protocol's (decisions 058); with no treasury it goes through `F` to the LPs already
164
164
  * earning, and with none earning it is not charged. This is NOT the swap fee: that one is charged
165
165
  * per unit of |Δ log p| on swaps; this is a flat charge on L, once, at mint.
166
166
  *
@@ -182,7 +182,7 @@ export async function positionsOf(c, key, owner) {
182
182
  }));
183
183
  return rows.map((r) => ({ id: r.id, floor: r.floor, cap: NO_CAP, capped: false, shares: r.shares, L: r.L, fees: r.fees }));
184
184
  }
185
- const ID_REGISTERED = parseAbiItem("event IdRegistered(uint256 indexed id, bytes32 indexed poolId, int256 floor, int256 cap, bool capped)");
185
+ const ID_REGISTERED = parseAbiItem("event ClassRegistered(uint256 indexed id, bytes32 indexed poolId, int256 floor, int256 cap, bool capped)");
186
186
  /** The class ids `owner` holds in `pool`, from the indexer's `pool_holder` view; null when the indexer cannot answer. */
187
187
  async function heldIdsFromView(c, indexer, pool, owner) {
188
188
  try {
@@ -190,10 +190,10 @@ async function heldIdsFromView(c, indexer, pool, owner) {
190
190
  return rows.filter((r) => r.balance > 0n && !r.isBackstop).map((r) => r.id);
191
191
  }
192
192
  catch {
193
- return null; // the view is a cache: the IdRegistered replay below answers the same
193
+ return null; // the view is a cache: the ClassRegistered replay below answers the same
194
194
  }
195
195
  }
196
- /** Every class id ever registered in `pool` (`IdRegistered`), from the indexer's table or the node. */
196
+ /** Every class id ever registered in `pool` (`ClassRegistered`), from the indexer's table or the node. */
197
197
  async function registeredIds(c, pool, fromBlock, indexer) {
198
198
  const { logs } = await getEventLogs(c, { indexer, address: c.addresses.cPoolManager, event: ID_REGISTERED, args: { poolId: pool }, fromBlock });
199
199
  return logs.map((l) => l.args.id ?? 0n).filter((id) => id !== 0n);
@@ -203,14 +203,15 @@ async function registeredIds(c, pool, fromBlock, indexer) {
203
203
  *
204
204
  * `positionsOf` (the lens) enumerates the uncapped book from the ladder bitmap in one call and
205
205
  * cannot list capped classes: a capped id is a (floor, cap) pair, quadratic in live ticks. This
206
- * replays `IdRegistered` — every class is registered once, on first mint, with its floor and
206
+ * replays `ClassRegistered` — every class is registered once, on first mint, with its floor and
207
207
  * cap — then checks the owner's ERC-6909 balance on each and reads the class for its L, so the
208
208
  * holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
209
209
  * a read per registered class; fine for a pool's lifetime of classes.
210
210
  */
211
- export async function holdingsOf(c, key, owner, fromBlock = 0n, opts = {}) {
211
+ export async function holdingsOf(c, key, owner, fromBlock, opts = {}) {
212
212
  const pool = poolId(key);
213
- const ids = (opts.indexer ? await heldIdsFromView(c, opts.indexer, pool, owner) : null) ?? (await registeredIds(c, pool, fromBlock, opts.indexer));
213
+ const indexer = opts.indexer ?? c.indexerUrl;
214
+ const ids = (indexer ? await heldIdsFromView(c, indexer, pool, owner) : null) ?? (await registeredIds(c, pool, fromBlock, indexer));
214
215
  if (ids.length === 0)
215
216
  return [];
216
217
  // one lens call: balance, class L, fees, floor and cap for every id the owner holds
@@ -49,17 +49,9 @@ export declare const memoryStore: TokenStore;
49
49
  export declare function browserStore(prefix?: string): TokenStore;
50
50
  /** Swap the backing store. Call once at startup; `browserStore()` is the usual argument. */
51
51
  export declare function setTokenStore(s: TokenStore): void;
52
- /**
53
- * Chains whose addresses are not permanent identities: a development node can be wiped and
54
- * redeployed, and because deployment addresses are derived from a deterministic nonce sequence the
55
- * SAME address comes back holding a different contract. 1337 is ganache's and hardhat's legacy id,
56
- * 31337 anvil's and hardhat's default, 31338 and 31339 the unimod and logswap devnets — both
57
- * persisted with `--state`, both documented as resettable by deleting that file.
58
- *
59
- * Add to this set rather than removing from it: a chain wrongly listed here costs some RPC round
60
- * trips, while one wrongly absent silently serves a stale scale, which is the bug this exists for.
61
- */
62
52
  export declare const RESETTABLE_CHAINS: ReadonlySet<number>;
53
+ /** Mark a development chain the registry does not list as resettable. There is no removal. */
54
+ export declare function addResettableChain(chainId: number): void;
63
55
  /** True when a `(chainId, address)` pair cannot be trusted to name one contract forever. */
64
56
  export declare function isResettableChain(chainId: number): boolean;
65
57
  export declare function readCachedToken(chainId: number, address: Address): CachedToken | null;
@@ -28,6 +28,7 @@
28
28
  * that did would break every integration, not just this one. That is what makes an unbounded TTL
29
29
  * correct rather than merely convenient — on a chain whose addresses are permanent.
30
30
  */
31
+ import { LOGSWAP_CHAINS } from "./chains.js";
31
32
  const memory = new Map();
32
33
  /** The default: per-process, no persistence. Works in node, workers and a browser alike. */
33
34
  export const memoryStore = {
@@ -88,14 +89,21 @@ const keyOf = (chainId, address) => `${chainId}:${address.toLowerCase()}`;
88
89
  /**
89
90
  * Chains whose addresses are not permanent identities: a development node can be wiped and
90
91
  * redeployed, and because deployment addresses are derived from a deterministic nonce sequence the
91
- * SAME address comes back holding a different contract. 1337 is ganache's and hardhat's legacy id,
92
- * 31337 anvil's and hardhat's default, 31338 and 31339 the unimod and logswap devnets — both
93
- * persisted with `--state`, both documented as resettable by deleting that file.
92
+ * SAME address comes back holding a different contract. Every chain the registry flags `devnet`
93
+ * (31337 anvil's and hardhat's default, 31339 the logswap devnet), plus 1337 (ganache's and
94
+ * hardhat's legacy id) and 31338 (the unimod devnet), persisted with `--state` and documented as
95
+ * resettable by deleting that file.
94
96
  *
95
- * Add to this set rather than removing from it: a chain wrongly listed here costs some RPC round
96
- * trips, while one wrongly absent silently serves a stale scale, which is the bug this exists for.
97
+ * Add to this set rather than removing from it ({@link addResettableChain}): a chain wrongly listed
98
+ * here costs some RPC round trips, while one wrongly absent silently serves a stale scale, which is
99
+ * the bug this exists for.
97
100
  */
98
- export const RESETTABLE_CHAINS = new Set([1337, 31337, 31338, 31339]);
101
+ const resettable = new Set([1337, 31338, ...Object.values(LOGSWAP_CHAINS).filter((ch) => ch.devnet).map((ch) => ch.chainId)]);
102
+ export const RESETTABLE_CHAINS = resettable;
103
+ /** Mark a development chain the registry does not list as resettable. There is no removal. */
104
+ export function addResettableChain(chainId) {
105
+ resettable.add(chainId);
106
+ }
99
107
  /** True when a `(chainId, address)` pair cannot be trusted to name one contract forever. */
100
108
  export function isResettableChain(chainId) {
101
109
  return RESETTABLE_CHAINS.has(chainId);
package/dist/views.d.ts CHANGED
@@ -268,7 +268,7 @@ export interface PadStatusRow {
268
268
  export declare function padStatuses(url: string, q?: ViewQuery): Promise<PadStatusRow[]>;
269
269
  /**
270
270
  * Protocol revenue per UTC day, side, source and token. Sources: F `mint_fee` (shares minted to the
271
- * collector, valued at the share value) and `pot_cut`; C `accrued` (the swap-fee tax and the mint fee
271
+ * treasury, valued at the share value) and `pot_cut`; C `accrued` (the swap-fee tax and the mint fee
272
272
  * together, from the snapshots) and `collected` — basis `collected`, cash moved, not revenue on top
273
273
  * of `accrued`.
274
274
  */
package/dist/write.d.ts CHANGED
@@ -68,7 +68,8 @@ type AbiError = {
68
68
  };
69
69
  /**
70
70
  * Every custom error a router call can revert with that the router's own ABI does not declare: the
71
- * C and F managers' (a mint, a swap or a settlement bubbles them up unchanged) and Permit2's.
71
+ * C and F managers' (a mint, a swap or a settlement bubbles them up unchanged), the pad policy's
72
+ * (a launch's `NoThreshold`, `PadExists`, `OutOfRange`; a graduation's `NotGraduated`) and Permit2's.
72
73
  * Without them viem can name only the router's errors, and anything raised in the manager comes
73
74
  * back as a bare selector.
74
75
  */
package/dist/write.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * raw `minOut`/`maxIn` the contract wants. `withSlippage()` derives one from a quote when that is
13
13
  * what you have — but the bound is what ships.
14
14
  */
15
- import { cPoolManagerAbi, fPoolManagerAbi } from "./generated.js";
15
+ import { cPoolManagerAbi, fPoolManagerAbi, padPolicyAbi } from "./generated.js";
16
16
  /** Disables the deadline check. Deliberate opt-out, never a default. */
17
17
  export const NEVER = (1n << 256n) - 1n;
18
18
  /** Default deadline window: 20 minutes, the same order as every major DEX front end. */
@@ -81,14 +81,15 @@ const permit2Errors = [
81
81
  const errorKey = (e) => `${e.name}(${e.inputs.map((i) => i.type).join(",")})`;
82
82
  /**
83
83
  * Every custom error a router call can revert with that the router's own ABI does not declare: the
84
- * C and F managers' (a mint, a swap or a settlement bubbles them up unchanged) and Permit2's.
84
+ * C and F managers' (a mint, a swap or a settlement bubbles them up unchanged), the pad policy's
85
+ * (a launch's `NoThreshold`, `PadExists`, `OutOfRange`; a graduation's `NotGraduated`) and Permit2's.
85
86
  * Without them viem can name only the router's errors, and anything raised in the manager comes
86
87
  * back as a bare selector.
87
88
  */
88
89
  export const routerRevertErrors = (() => {
89
90
  const seen = new Set();
90
91
  const out = [];
91
- for (const x of [...cPoolManagerAbi, ...fPoolManagerAbi, ...permit2Errors]) {
92
+ for (const x of [...cPoolManagerAbi, ...fPoolManagerAbi, ...padPolicyAbi, ...permit2Errors]) {
92
93
  if (x.type !== "error")
93
94
  continue;
94
95
  const e = x;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logswap/sdk",
3
- "version": "0.5.76",
3
+ "version": "0.5.78",
4
4
  "description": "TypeScript SDK for Logswap, the liquidity primitive introducing the logarithmic invariant — typed wrappers over the CPoolManager / FPoolManager / Router / Lens surface.",
5
5
  "license": "GPL-2.0-or-later",
6
6
  "type": "module",