@logswap/sdk 0.5.75 → 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/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 */
@@ -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(["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";
@@ -21,5 +22,6 @@ export * from "./tokencache.js";
21
22
  export * from "./fpool.js";
22
23
  export * from "./fees.js";
23
24
  export * from "./history.js";
25
+ export * from "./views.js";
24
26
  export { cPoolManagerAbi, fPoolManagerAbi, logswapLensAbi, logswapRouterAbi, padPolicyAbi, polPolicyAbi, policyRegistryAbi, privatePolicyAbi, publicPolicyAbi } from "./generated.js";
25
27
  export * from "./admin.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";
@@ -21,5 +22,6 @@ export * from "./tokencache.js";
21
22
  export * from "./fpool.js";
22
23
  export * from "./fees.js";
23
24
  export * from "./history.js";
25
+ export * from "./views.js";
24
26
  export { cPoolManagerAbi, fPoolManagerAbi, logswapLensAbi, logswapRouterAbi, padPolicyAbi, polPolicyAbi, policyRegistryAbi, privatePolicyAbi, publicPolicyAbi } from "./generated.js";
25
27
  export * from "./admin.js";
package/dist/indexer.d.ts CHANGED
@@ -93,7 +93,7 @@ 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
  }>;
package/dist/indexer.js CHANGED
@@ -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);
package/dist/pools.d.ts CHANGED
@@ -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>;
@@ -112,8 +114,8 @@ export interface DiscoveredMarket {
112
114
  * Enumerate markets from `Initialize` 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;
package/dist/pools.js CHANGED
@@ -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";
@@ -105,8 +106,8 @@ export function lpEdge(state) {
105
106
  * Enumerate markets from `Initialize` 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
113
  const ev = cPoolManagerAbi.find((x) => x.type === "event" && x.name === "Initialize");
@@ -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++) {
@@ -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
  *
package/dist/positions.js CHANGED
@@ -13,6 +13,7 @@ const C_POSITIONS_SLOT = 4n;
13
13
  const U128 = (1n << 128n) - 1n;
14
14
  import { isPosition, NO_CAP, positionId, unpackFloorCap } from "./ids.js";
15
15
  import { getEventLogs } from "./history.js";
16
+ import { poolHolders } from "./views.js";
16
17
  /**
17
18
  * A class's aggregate state, read through `extsload` (C version 7: the manager's public
18
19
  * `positions` mapping is gone behind it, decisions 065). The slot is `CPoolState`'s:
@@ -159,7 +160,7 @@ export function presetMintFee(swapFee) {
159
160
  *
160
161
  * Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
161
162
  * capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
162
- * 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
163
164
  * earning, and with none earning it is not charged. This is NOT the swap fee: that one is charged
164
165
  * per unit of |Δ log p| on swaps; this is a flat charge on L, once, at mint.
165
166
  *
@@ -182,6 +183,21 @@ export async function positionsOf(c, key, owner) {
182
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 }));
183
184
  }
184
185
  const ID_REGISTERED = parseAbiItem("event IdRegistered(uint256 indexed id, bytes32 indexed poolId, int256 floor, int256 cap, bool capped)");
186
+ /** The class ids `owner` holds in `pool`, from the indexer's `pool_holder` view; null when the indexer cannot answer. */
187
+ async function heldIdsFromView(c, indexer, pool, owner) {
188
+ try {
189
+ const rows = await poolHolders(indexer, { condition: { side: "C", poolId: pool.toLowerCase(), holder: owner.toLowerCase(), manager: c.addresses.cPoolManager.toLowerCase() } });
190
+ return rows.filter((r) => r.balance > 0n && !r.isBackstop).map((r) => r.id);
191
+ }
192
+ catch {
193
+ return null; // the view is a cache: the IdRegistered replay below answers the same
194
+ }
195
+ }
196
+ /** Every class id ever registered in `pool` (`IdRegistered`), from the indexer's table or the node. */
197
+ async function registeredIds(c, pool, fromBlock, indexer) {
198
+ const { logs } = await getEventLogs(c, { indexer, address: c.addresses.cPoolManager, event: ID_REGISTERED, args: { poolId: pool }, fromBlock });
199
+ return logs.map((l) => l.args.id ?? 0n).filter((id) => id !== 0n);
200
+ }
185
201
  /**
186
202
  * EVERY class this owner holds in a pool, capped ones included — the complete book.
187
203
  *
@@ -192,10 +208,10 @@ const ID_REGISTERED = parseAbiItem("event IdRegistered(uint256 indexed id, bytes
192
208
  * holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
193
209
  * a read per registered class; fine for a pool's lifetime of classes.
194
210
  */
195
- export async function holdingsOf(c, key, owner, fromBlock = 0n, opts = {}) {
211
+ export async function holdingsOf(c, key, owner, fromBlock, opts = {}) {
196
212
  const pool = poolId(key);
197
- const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.cPoolManager, event: ID_REGISTERED, args: { poolId: pool }, fromBlock });
198
- const ids = logs.map((l) => l.args.id ?? 0n).filter((id) => id !== 0n);
213
+ const indexer = opts.indexer ?? c.indexerUrl;
214
+ const ids = (indexer ? await heldIdsFromView(c, indexer, pool, owner) : null) ?? (await registeredIds(c, pool, fromBlock, indexer));
199
215
  if (ids.length === 0)
200
216
  return [];
201
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);
@@ -0,0 +1,285 @@
1
+ /**
2
+ * views.ts — the indexer's derived views (indexing phase 2, logswap-be `devnet/VIEWS.md`).
3
+ *
4
+ * The indexer records events and the snapshotter samples state; these views join the two in
5
+ * Postgres: holders, a wallet's positions and flows, per-swap volume and fee, price points and
6
+ * candles, TVL by the hour, the pools table's 24 h / 7 d figures, the generation steps and pad
7
+ * status, protocol revenue by day, and who did each routed action. Each reader returns typed rows:
8
+ *
9
+ * - **amounts** (Postgres `numeric`, GraphQL BigFloat strings) as `bigint`. The views floor every
10
+ * amount they compute, so the integer part is the value;
11
+ * - **prices, APYs, progress** (`double precision`) as `number`. `priceRaw` is quote wei per base
12
+ * wei: scale by 10^(baseDecimals − quoteDecimals) to display;
13
+ * - **times** as unix seconds (`number`), **addresses** checksummed, pool ids lowercase `0x…`.
14
+ *
15
+ * A view is a cache like any indexed table: the readers throw when the indexer cannot answer, and
16
+ * the SDK functions that use them ({@link holdingsOf}, {@link swapFees}, {@link fPoolShareHolders})
17
+ * keep their node path as the fallback.
18
+ */
19
+ import { type Address, type Hex } from "viem";
20
+ /** What a view query takes: postgraphile's `condition` (equality), `filter` (the connection-filter plugin's operators), an `orderBy` of the view's enum names, a row cap. */
21
+ export interface ViewQuery {
22
+ condition?: Record<string, unknown>;
23
+ filter?: Record<string, unknown>;
24
+ /** e.g. `["BLOCK_NUMBER_ASC"]`, `["VOLUME_24H_DESC"]`: the column's CONSTANT_CASE name and a direction. */
25
+ orderBy?: string[];
26
+ /** At most this many rows (one page up to 1000). All rows when omitted. */
27
+ first?: number;
28
+ signal?: AbortSignal;
29
+ }
30
+ export type Side = "C" | "F";
31
+ /** A pool of either manager: C markets are kind `market`; F pools carry their policy's registry name (`public`, `private`, `pol`, `pad`). */
32
+ export interface PoolDirectoryRow {
33
+ side: Side;
34
+ poolId: Hex;
35
+ manager: Address;
36
+ kind: string;
37
+ quote: Address;
38
+ bases: Address[];
39
+ swapFee: bigint;
40
+ /** C only. */
41
+ tickSpacing: bigint | null;
42
+ /** F only. */
43
+ policy: Address | null;
44
+ creator: Address | null;
45
+ birthBlock: bigint;
46
+ birthTime: number;
47
+ /** F only: the pool's share-id key (the id's bits above the generation). */
48
+ shareKey: bigint | null;
49
+ }
50
+ export declare function poolDirectory(url: string, q?: ViewQuery): Promise<PoolDirectoryRow[]>;
51
+ /** A manager event and who did it: the router's caller when the transaction went through the router (`viaRouter`), else the address the event names (`actor`). */
52
+ export interface EventUserRow {
53
+ side: Side;
54
+ /** `Swap` `Mint` `Burn` `Update` `Claim` (C); `FSwap` `FMint` `FBurn` `Harvest` `DividendClaimed` `Redeem` (F). */
55
+ event: string;
56
+ poolId: Hex;
57
+ actor: Address;
58
+ viaRouter: boolean;
59
+ user: Address;
60
+ txHash: Hex;
61
+ logIndex: number;
62
+ blockNumber: bigint;
63
+ blockTimestamp: number;
64
+ manager: Address;
65
+ }
66
+ export declare function eventUsers(url: string, q?: ViewQuery): Promise<EventUserRow[]>;
67
+ /** A current ERC-6909 balance: C ids resolve to their class (floor, cap), F ids to their pool and generation. C's backstop lock is held by address(0) (`isBackstop`), F's dead shares by 0xdead (`isDead`). */
68
+ export interface PoolHolderRow {
69
+ side: Side;
70
+ manager: Address;
71
+ id: bigint;
72
+ poolId: Hex | null;
73
+ /** F only. */
74
+ gen: number | null;
75
+ /** C only. */
76
+ floor: bigint | null;
77
+ cap: bigint | null;
78
+ capped: boolean | null;
79
+ holder: Address;
80
+ balance: bigint;
81
+ isBackstop: boolean;
82
+ isDead: boolean;
83
+ }
84
+ export declare function poolHolders(url: string, q?: ViewQuery): Promise<PoolHolderRow[]>;
85
+ /** A wallet's holding (backstop and dead excluded). `valueQuote`: an F share of the live generation at the latest snapshot's share value, a retired one at its bundle's quote per share; NULL for C (a lens read: {@link legsOf}). */
86
+ export interface WalletPositionRow {
87
+ side: Side;
88
+ manager: Address;
89
+ wallet: Address;
90
+ poolId: Hex | null;
91
+ kind: string | null;
92
+ quote: Address | null;
93
+ bases: Address[];
94
+ id: bigint;
95
+ gen: number | null;
96
+ floor: bigint | null;
97
+ cap: bigint | null;
98
+ capped: boolean | null;
99
+ shares: bigint;
100
+ valueQuote: bigint | null;
101
+ /** `live` / `retired` / `unknown` (F), `class` (C). */
102
+ status: string;
103
+ valuedAtBlock: bigint | null;
104
+ }
105
+ export declare function walletPositions(url: string, q?: ViewQuery): Promise<WalletPositionRow[]>;
106
+ /** A wallet's flows in a pool, from its own events: what it put in and took out, fees and dividends realised. F mints and burns carry the quote leg only. C `Update` is not counted (it repeats its Burn and Mint). */
107
+ export interface WalletPoolFlowRow {
108
+ side: Side;
109
+ manager: Address;
110
+ wallet: Address;
111
+ poolId: Hex;
112
+ baseIn: bigint;
113
+ quoteIn: bigint;
114
+ baseOut: bigint;
115
+ quoteOut: bigint;
116
+ feesRealised: bigint;
117
+ dividendsClaimed: bigint;
118
+ redeemedQuote: bigint;
119
+ entries: number;
120
+ exits: number;
121
+ firstTime: number;
122
+ lastTime: number;
123
+ }
124
+ export declare function walletPoolFlows(url: string, q?: ViewQuery): Promise<WalletPoolFlowRow[]>;
125
+ /** A swap's volume and fee in quote, the app's definitions (C: the quote leg and the event's fee; F: see VIEWS.md). F rows carry the traded legs and their L_j = w_j·L. */
126
+ export interface SwapFlowRow {
127
+ side: Side;
128
+ manager: Address;
129
+ poolId: Hex;
130
+ txHash: Hex;
131
+ logIndex: number;
132
+ blockNumber: bigint;
133
+ blockTimestamp: number;
134
+ volumeQuote: bigint;
135
+ feeQuote: bigint;
136
+ tokenIn: Address | null;
137
+ tokenOut: Address | null;
138
+ reserveIn: bigint | null;
139
+ reserveOut: bigint | null;
140
+ lIn: bigint | null;
141
+ lOut: bigint | null;
142
+ }
143
+ export declare function swapFlows(url: string, q?: ViewQuery): Promise<SwapFlowRow[]>;
144
+ /** A price point per (pool, base) after a swap: C e^newX, F the traded leg's mark L_j / R_j. Quote wei per base wei. */
145
+ export interface PriceTickRow {
146
+ side: Side;
147
+ poolId: Hex;
148
+ base: Address;
149
+ blockNumber: bigint;
150
+ blockTimestamp: number;
151
+ logIndex: number;
152
+ priceRaw: number;
153
+ volumeQuote: bigint;
154
+ feeQuote: bigint;
155
+ }
156
+ export declare function priceTicks(url: string, q?: ViewQuery): Promise<PriceTickRow[]>;
157
+ /** OHLC per (pool, base, UTC bucket). A base → base F swap counts in both legs' candles; pool totals come from {@link poolSummaries}. */
158
+ export interface CandleRow {
159
+ side: Side;
160
+ poolId: Hex;
161
+ base: Address;
162
+ /** Bucket start, unix seconds. */
163
+ bucket: number;
164
+ open: number;
165
+ high: number;
166
+ low: number;
167
+ close: number;
168
+ volumeQuote: bigint;
169
+ feeQuote: bigint;
170
+ swaps: number;
171
+ }
172
+ export type CandleInterval = "minute" | "hour" | "day";
173
+ export declare function candles(url: string, interval: CandleInterval, q?: ViewQuery): Promise<CandleRow[]>;
174
+ /** The hour's last snapshot per pool (forward-fill hours with none). `liquidity` is C's active L or F's L. */
175
+ export interface PoolTvlHourRow {
176
+ side: Side;
177
+ poolId: Hex;
178
+ bucket: number;
179
+ blockNumber: bigint;
180
+ tvlQuote: bigint | null;
181
+ liquidity: bigint | null;
182
+ /** C only. */
183
+ priceRaw: number | null;
184
+ feeGrowth: bigint | null;
185
+ /** F only. */
186
+ shareValue: bigint | null;
187
+ gen: number | null;
188
+ }
189
+ export declare function poolTvlHours(url: string, q?: ViewQuery): Promise<PoolTvlHourRow[]>;
190
+ /**
191
+ * A pool's trailing 24 h / 7 d figures and its latest state. APY, as the app shows it: the window's
192
+ * swap fees over the pool's current L, annualised over the window measured (clipped to the pool's
193
+ * birth) — `fees / L × 31 536 000 / seconds`; the same formula as {@link swapFeeApy}.
194
+ */
195
+ export interface PoolSummaryRow {
196
+ side: Side;
197
+ poolId: Hex;
198
+ kind: string;
199
+ quote: Address;
200
+ bases: Address[];
201
+ swapFee: bigint;
202
+ birthTime: number;
203
+ volume24h: bigint;
204
+ fees24h: bigint;
205
+ swaps24h: number;
206
+ volume7d: bigint;
207
+ fees7d: bigint;
208
+ volumeAll: bigint;
209
+ feesAll: bigint;
210
+ lastSwap: number | null;
211
+ tvlQuote: bigint | null;
212
+ liquidity: bigint | null;
213
+ priceRaw: number | null;
214
+ shareValue: bigint | null;
215
+ gen: number | null;
216
+ stateBlock: bigint | null;
217
+ seconds24h: number;
218
+ seconds7d: number;
219
+ apy24h: number | null;
220
+ apy7d: number | null;
221
+ }
222
+ export declare function poolSummaries(url: string, q?: ViewQuery): Promise<PoolSummaryRow[]>;
223
+ /** A `regenerate` step: the pot and its split (payee, the protocol's cut, the burn, the rest deepening the bid); a pad's `rung` from `Graduated`. */
224
+ export interface GenerationStepRow {
225
+ kind: string | null;
226
+ poolId: Hex;
227
+ /** The pool's generation after this step. */
228
+ genAfter: number;
229
+ pot: bigint;
230
+ payee: Address;
231
+ toPayee: bigint;
232
+ cut: bigint;
233
+ burnt: bigint;
234
+ deepened: bigint;
235
+ rung: number | null;
236
+ txHash: Hex;
237
+ blockNumber: bigint;
238
+ blockTimestamp: number;
239
+ }
240
+ export declare function generationSteps(url: string, q?: ViewQuery): Promise<GenerationStepRow[]>;
241
+ /** Every pad and POL now: the latest snapshot's state, the next graduation's threshold (pads) and the pot's progress to it, and the steps so far. */
242
+ export interface PadStatusRow {
243
+ kind: string;
244
+ poolId: Hex;
245
+ quote: Address;
246
+ bases: Address[];
247
+ creator: Address | null;
248
+ birthTime: number;
249
+ gen: number | null;
250
+ pot: bigint | null;
251
+ unharvested: bigint | null;
252
+ l: bigint | null;
253
+ q: bigint | null;
254
+ tvlQuote: bigint | null;
255
+ shareValue: bigint | null;
256
+ threshold: bigint | null;
257
+ /** pot / threshold, a fraction; null without a threshold. */
258
+ progress: number | null;
259
+ stateBlock: bigint | null;
260
+ stateTime: number | null;
261
+ steps: number;
262
+ burntTotal: bigint;
263
+ cutTotal: bigint;
264
+ paidTotal: bigint;
265
+ deepenedTotal: bigint;
266
+ lastStep: number | null;
267
+ }
268
+ export declare function padStatuses(url: string, q?: ViewQuery): Promise<PadStatusRow[]>;
269
+ /**
270
+ * Protocol revenue per UTC day, side, source and token. Sources: F `mint_fee` (shares minted to the
271
+ * treasury, valued at the share value) and `pot_cut`; C `accrued` (the swap-fee tax and the mint fee
272
+ * together, from the snapshots) and `collected` — basis `collected`, cash moved, not revenue on top
273
+ * of `accrued`.
274
+ */
275
+ export interface ProtocolRevenueDayRow {
276
+ day: number;
277
+ side: Side;
278
+ source: string;
279
+ basis: "earned" | "collected";
280
+ token: Address;
281
+ amount: bigint;
282
+ amountQuote: bigint;
283
+ events: number;
284
+ }
285
+ export declare function protocolRevenueDays(url: string, q?: ViewQuery): Promise<ProtocolRevenueDayRow[]>;