@logswap/sdk 0.5.102 → 0.5.103

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.
Files changed (64) hide show
  1. package/README.md +14 -418
  2. package/dist/actions.d.ts +0 -39
  3. package/dist/actions.js +0 -39
  4. package/dist/admin.d.ts +0 -106
  5. package/dist/admin.js +1 -96
  6. package/dist/chains.d.ts +0 -49
  7. package/dist/chains.js +0 -30
  8. package/dist/claims.d.ts +0 -32
  9. package/dist/claims.js +0 -30
  10. package/dist/client.d.ts +0 -116
  11. package/dist/client.js +1 -231
  12. package/dist/fees.d.ts +1 -45
  13. package/dist/fees.js +0 -44
  14. package/dist/fpool.d.ts +4 -612
  15. package/dist/fpool.js +14 -490
  16. package/dist/generated.js +0 -30
  17. package/dist/history.d.ts +0 -61
  18. package/dist/history.js +5 -74
  19. package/dist/ids.d.ts +0 -30
  20. package/dist/ids.js +0 -31
  21. package/dist/index.d.ts +0 -7
  22. package/dist/index.js +0 -7
  23. package/dist/indexer.d.ts +0 -68
  24. package/dist/indexer.js +1 -77
  25. package/dist/keys.d.ts +0 -50
  26. package/dist/keys.js +0 -35
  27. package/dist/liquidity.d.ts +0 -128
  28. package/dist/liquidity.js +1 -107
  29. package/dist/onboard.d.ts +0 -52
  30. package/dist/onboard.js +1 -59
  31. package/dist/pools.d.ts +3 -157
  32. package/dist/pools.js +1 -164
  33. package/dist/positions.d.ts +0 -102
  34. package/dist/positions.js +1 -90
  35. package/dist/quote.d.ts +0 -14
  36. package/dist/quote.js +0 -14
  37. package/dist/swap.d.ts +0 -31
  38. package/dist/swap.js +5 -37
  39. package/dist/tokencache.d.ts +0 -48
  40. package/dist/tokencache.js +1 -73
  41. package/dist/write.d.ts +1 -87
  42. package/dist/write.js +1 -87
  43. package/package.json +3 -8
  44. package/src/actions.ts +0 -208
  45. package/src/admin.ts +0 -350
  46. package/src/chains.ts +0 -278
  47. package/src/claims.ts +0 -111
  48. package/src/client.ts +0 -436
  49. package/src/fees.ts +0 -138
  50. package/src/fpool.ts +0 -2049
  51. package/src/generated.ts +0 -4345
  52. package/src/history.ts +0 -383
  53. package/src/ids.ts +0 -78
  54. package/src/index.ts +0 -26
  55. package/src/indexer.ts +0 -264
  56. package/src/keys.ts +0 -138
  57. package/src/liquidity.ts +0 -456
  58. package/src/onboard.ts +0 -253
  59. package/src/pools.ts +0 -465
  60. package/src/positions.ts +0 -297
  61. package/src/quote.ts +0 -36
  62. package/src/swap.ts +0 -181
  63. package/src/tokencache.ts +0 -178
  64. package/src/write.ts +0 -236
package/dist/pools.js CHANGED
@@ -1,16 +1,3 @@
1
- /**
2
- * pools.ts — market state and discovery.
3
- *
4
- * Two things worth knowing before reading further.
5
- *
6
- * **Markets are discovered from logs, not configuration.** `MarketCreated` carries the ENTIRE
7
- * `PoolKey` in the clear, so a client can reconstruct any market's key — and therefore call any
8
- * keyed function — having never been told the market exists. There is no registry to maintain.
9
- *
10
- * **`x` is the state, price is derived.** The contract stores $x = \log p$ and materialises the
11
- * price only where unavoidable; `priceOf` below mirrors that, and is lossy in the way any float
12
- * conversion is. Prefer comparing in log space when precision matters.
13
- */
14
1
  import { formatUnits } from "viem";
15
2
  import { lensCAbi, managerCAbi } from "./generated.js";
16
3
  import { lensC, managerC, clientChainId } from "./client.js";
@@ -18,7 +5,6 @@ import { signerFor } from "./write.js";
18
5
  import { readCachedToken, registerCacheClear, writeCachedToken } from "./tokencache.js";
19
6
  import { poolId, swapFeeOfKey } from "./keys.js";
20
7
  import { getEventLogs } from "./history.js";
21
- /** Read a market's full state by key, through the lens (`getPools`; C version 7). All zero, `initialized` false, for a market nobody opened. */
22
8
  export async function getPool(c, key) {
23
9
  const v = (await c.public.readContract({
24
10
  address: lensC(c),
@@ -28,52 +14,20 @@ export async function getPool(c, key) {
28
14
  }));
29
15
  return v[0];
30
16
  }
31
- /**
32
- * The market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]` (C 18, decision 099), constant for the market's
33
- * life. Still a read: it refuses a key nobody initialized, which `discoverMarkets` relies on to
34
- * drop a stale indexer's rows. Offline: {@link swapFeeOfKey}. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
35
- */
36
17
  export async function marketSwapFee(c, key) {
37
18
  const s = await getPool(c, key);
38
19
  if (!s.initialized)
39
20
  throw new Error(`logswap: market ${poolId(key)} is not initialized`);
40
21
  return swapFeeOfKey(key);
41
22
  }
42
- /**
43
- * Price from the stored log-price. **Lossy** — `x` is exact and this is a float, so use it for
44
- * display and never for arithmetic you intend to send back on-chain.
45
- */
46
23
  export function priceOf(state, scale = 1) {
47
24
  return Math.exp(Number(state.logPrice) / 1e18) * scale;
48
25
  }
49
- /**
50
- * The factor between the chain's price and the human one. The chain's log-price is of the WEI
51
- * ratio, so with a 6-dec USDC quote and an 18-dec base the human price is `e^x · 10^12`. Pass
52
- * this as `scale` to {@link priceOf}, {@link floorPrice} and `fPoolPriceOf` — with 18/18 tokens
53
- * it is 1 and nothing changes.
54
- */
55
26
  export function priceScale(baseDecimals, quoteDecimals) {
56
27
  return 10 ** (baseDecimals - quoteDecimals);
57
28
  }
58
- /** The C manager's log-price wall: |x| ≤ 46 on the WEI ratio (`MAX_ABS_FLOOR`). */
59
29
  export const C_MAX_ABS_X = 46;
60
- /** The least derived base reserve a C book keeps, in base wei (`MIN_RESERVE`, decisions 023). */
61
30
  export const C_MIN_RESERVE = 10n ** 6n;
62
- /**
63
- * The prices a C market can hold, in human units — quote per whole base token (decisions 054).
64
- *
65
- * - `listMin`, `listMax`: the wall, `10^(base − quote) · e^{∓46}`. A market cannot be initialized,
66
- * and no floor or cap placed, outside it. An 18-dec token against 6-dec USDC cannot list under
67
- * 1.05e-8; against an 18-dec quote the same token lists down to 1.05e-20.
68
- * - `ceiling`: the highest price the book can trade to with `lActive` of active exposure (quote
69
- * wei): the derived reserve `lActive / p` must stay at or above `C_MIN_RESERVE` base wei, so
70
- * `ceiling = lActive · 10^(base − quote) / 1e6`, capped by `listMax`. In whole units that is
71
- * `L · 10^(base − 6)`: the quote's decimals cancel and the base's set it — harmless on an
72
- * 18-dec base, but a WBTC book of 1,000 USDC of depth stops at 100,000. Omit `lActive` for the
73
- * wall alone.
74
- *
75
- * Floats, for display and warnings; the chain is the authority.
76
- */
77
31
  export function cPriceRange(baseDecimals, quoteDecimals, lActive) {
78
32
  const scale = priceScale(baseDecimals, quoteDecimals);
79
33
  const listMin = Math.exp(-C_MAX_ABS_X) * scale;
@@ -81,40 +35,18 @@ export function cPriceRange(baseDecimals, quoteDecimals, lActive) {
81
35
  const ceiling = lActive === undefined || lActive === 0n ? listMax : Math.min(listMax, (Number(lActive) / Number(C_MIN_RESERVE)) * scale);
82
36
  return { listMin, listMax, ceiling };
83
37
  }
84
- /** Whether a C market can be initialized at `price` (human units) for this pair's decimals. */
85
38
  export function cListable(price, baseDecimals, quoteDecimals) {
86
39
  const { listMin, listMax } = cPriceRange(baseDecimals, quoteDecimals);
87
40
  return price >= listMin && price <= listMax;
88
41
  }
89
- /**
90
- * The model-free LP edge, $F - \tfrac12\Sigma$ — the protocol's headline metric, in quote per unit
91
- * of exposure.
92
- *
93
- * $F$ is fee income per unit active $L$; $\Sigma$ is the realised quadratic variation, whose half
94
- * is the LVR a log pool pays. The difference is what an LP actually earns, with no model of the
95
- * price process assumed. Both ride on every `Swap` event, so this is reconstructible from logs
96
- * alone (docs/app.md) — no state read needed if you are already indexing.
97
- *
98
- * Signed: negative means variation has outrun fee income over the pool's life.
99
- */
100
42
  export function lpEdge(state) {
101
43
  return state.feeGrowth - state.realizedVariance / 2n;
102
44
  }
103
- /**
104
- * Enumerate markets from the C manager's `PoolCreated` logs.
105
- *
106
- * This is the whole market registry: the event carries every key field rather than just the id,
107
- * deliberately, so nothing downstream needs a configured list. The scan starts at the client's
108
- * `deployBlock` unless `fromBlock` says otherwise.
109
- */
110
45
  export async function discoverMarkets(c, opts = {}) {
111
46
  const ev = managerCAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
112
47
  if (!ev)
113
48
  throw new Error("logswap: PoolCreated event missing from the generated ABI");
114
49
  const args = {};
115
- // C 20: the topics are `poolId`, `quote`, `policy`; `base` and `creator` are data and filter below.
116
- // C 18 (decision 099): the event carries the six key fields, so the whole key is rebuilt from the log; `creator` is the account
117
- // that opened the market and no key field.
118
50
  if (opts.quote)
119
51
  args.quote = opts.quote;
120
52
  if (opts.policy)
@@ -124,7 +56,7 @@ export async function discoverMarkets(c, opts = {}) {
124
56
  address: managerC(c),
125
57
  event: ev,
126
58
  args,
127
- fromBlock: opts.fromBlock, // the client's deployBlock when absent
59
+ fromBlock: opts.fromBlock,
128
60
  toBlock: opts.toBlock,
129
61
  });
130
62
  const wantBase = opts.base?.toLowerCase();
@@ -144,14 +76,6 @@ export async function discoverMarkets(c, opts = {}) {
144
76
  };
145
77
  });
146
78
  }
147
- /**
148
- * Ladder shape: the live FLOORS, in log-price WAD — **not** tick indices.
149
- *
150
- * Named `liveFloors` deliberately. The lens function it wraps is called `liveTicks`, which reads as
151
- * if it returns `k`; it returns `k * tickSpacing`. Multiplying by the spacing again yields an
152
- * off-grid value and an `OffGrid` revert at the next call, which is a confusing place to discover
153
- * the mistake.
154
- */
155
79
  export async function liveFloors(c, key) {
156
80
  return c.public.readContract({
157
81
  address: lensC(c),
@@ -160,7 +84,6 @@ export async function liveFloors(c, key) {
160
84
  args: [poolId(key)],
161
85
  });
162
86
  }
163
- /** Is this floor on the market's grid, and inside `MAX_ABS_FLOOR`? Pure — no RPC on the manager. */
164
87
  export async function isValidFloor(c, key, floor) {
165
88
  return c.public.readContract({
166
89
  address: lensC(c),
@@ -169,38 +92,10 @@ export async function isValidFloor(c, key, floor) {
169
92
  args: [poolId(key), floor],
170
93
  });
171
94
  }
172
- /**
173
- * A market's token decimals, read from the tokens themselves.
174
- *
175
- * **Never assume these.** A market's two tokens routinely differ (USDC 6 against WETH 18), the
176
- * manager itself probes `decimals()` to scale `minBackstopL`, and a token that does not implement
177
- * it falls back to 18. Hardcoding a guess makes every parse and every display wrong by orders of
178
- * magnitude while the contract behaves perfectly — which reads as "the app is broken".
179
- */
180
95
  export async function marketDecimals(c, key) {
181
- // It used to fall back to 18 on ANY failure, a dropped request included — a 6-decimal quote read
182
- // as 18 is every amount 10^12 off. `marketTokens` retries and then refuses; so does this.
183
96
  const { base, quote } = await marketTokens(c, key);
184
97
  return { base: base.decimals, quote: quote.decimals };
185
98
  }
186
- /**
187
- * Both sides of a market, for labelling and scaling.
188
- *
189
- * **Decimals are read from the token and never guessed.** They used to fall back to 18 on any
190
- * failure, which quietly reintroduced the worst bug this stack has had: an 18 assumed for a
191
- * 6-decimal token is a 10^12 error in a number that goes on to `parseUnits` and becomes a transfer
192
- * amount. A wrong scale is indistinguishable from a working app until somebody moves funds, so a
193
- * read that will not resolve must fail loudly instead.
194
- *
195
- * `symbol` keeps a fallback because it is a label: a market shown as `0x5FbD…` is ugly, not wrong.
196
- *
197
- * Retries first, because a blip on the transport is not the same as a token that has no `decimals`,
198
- * and killing a market over one dropped packet is its own kind of wrong.
199
- *
200
- * **Cached** per (chain, address) — see `tokencache.ts` for why only successes are stored and why
201
- * the chain id is part of the key. Concurrent calls for the same token share one read, which
202
- * matters because the quote asset is usually the same across every market in a deployment.
203
- */
204
99
  export async function marketTokens(c, key) {
205
100
  const abi = [
206
101
  { type: "function", name: "decimals", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
@@ -234,18 +129,9 @@ export async function marketTokens(c, key) {
234
129
  if (inflight)
235
130
  return inflight;
236
131
  const k = `${chainId}:${address.toLowerCase()}`;
237
- // Deregistration happens INSIDE the job, so it completes before the promise settles. Cleaning
238
- // up in a `.finally()` on the outside runs a microtask later — late enough that a caller
239
- // arriving right after an `await` could still attach to a job that has already failed and
240
- // inherit a failure a fresh read would not have hit. Sharing an in-flight read is an
241
- // optimisation for concurrent callers; it must never make a later, separate call fail.
242
- // `| undefined` because the assignment below is what tsc cannot see happening first; the
243
- // finally only runs after an await, so by then it is set.
244
132
  let self;
245
133
  const job = (async () => {
246
134
  try {
247
- // `symbol` is allowed to fail; `decimals` is not. Caught separately so a missing symbol
248
- // does not discard a decimals read that succeeded.
249
135
  const [decimals, symbolResult] = await Promise.all([
250
136
  readDecimals(address),
251
137
  c.public
@@ -253,8 +139,6 @@ export async function marketTokens(c, key) {
253
139
  .then((v) => ({ ok: true, value: String(v) }))
254
140
  .catch(() => ({ ok: false, value: address.slice(0, 6) })),
255
141
  ]);
256
- // Only a real symbol is cached. Persisting the 0x… fallback would let one blip name the
257
- // token that for as long as the store lives.
258
142
  if (symbolResult.ok)
259
143
  writeCachedToken(chainId, address, { symbol: symbolResult.value, decimals });
260
144
  return { address, symbol: symbolResult.value, decimals };
@@ -271,82 +155,40 @@ export async function marketTokens(c, key) {
271
155
  const [base, quote] = await Promise.all([read(key.base), read(key.quote)]);
272
156
  return { base, quote };
273
157
  }
274
- /** In-flight reads, so simultaneous callers for one token share a single round trip. */
275
158
  const pending = new Map();
276
159
  registerCacheClear(() => pending.clear());
277
- /** Format a quote-denominated amount for display, given the quote's decimals. */
278
160
  export function formatQuote(amount, quoteDecimals) {
279
161
  return formatUnits(amount, quoteDecimals);
280
162
  }
281
- // ---------------------------------------------------------------------------------------------
282
- // Denominated readouts
283
- //
284
- // `F` and `lpEdge` are per unit of active L — dimensionless WAD fractions, not amounts. A
285
- // dashboard wants amounts, and multiplying by L is the whole conversion. Keeping these here rather
286
- // than in the app means one definition of "fees in quote" instead of one per screen.
287
- // ---------------------------------------------------------------------------------------------
288
163
  const WAD = 10n ** 18n;
289
164
  const YEAR_SECONDS = 31536000n;
290
- /** Fees the pool has accrued over its life, in QUOTE units: $F \cdot L$. */
291
165
  export function feesQuote(state) {
292
166
  return (state.feeGrowth * state.lActive) / WAD;
293
167
  }
294
- /** The LP edge in QUOTE units: $(F - \tfrac12\Sigma) \cdot L$. Signed. */
295
168
  export function edgeQuote(state) {
296
169
  return (lpEdge(state) * state.lActive) / WAD;
297
170
  }
298
- /** The pool floor as a price. **Lossy** — display only, like {@link priceOf}. */
299
171
  export function floorPrice(state, scale = 1) {
300
172
  return Math.exp(Number(state.backstopFloor) / 1e18) * scale;
301
173
  }
302
- /** $\log(p / p_{\text{floor}}) = x - \xi$ — how far spot sits above the floor, in log units (WAD). */
303
174
  export function floorDistance(state) {
304
175
  return state.logPrice - state.backstopFloor;
305
176
  }
306
- /**
307
- * $-\log(p/p_{\text{floor}})$ as a fraction: the log-drawdown from spot down to the floor.
308
- *
309
- * **Negative** while price is above the floor — it is how far price has to fall, so a UI can print
310
- * it with its sign and mean it. Zero at the floor.
311
- *
312
- * This is the LOG measure, not the arithmetic one: the actual price drawdown is
313
- * $e^{-\Delta} - 1$, which differs materially once the distance is large (a log distance of 0.7
314
- * is a 50% price fall, not 70%).
315
- */
316
177
  export function floorDrawdown(state) {
317
178
  return -Number(floorDistance(state)) / 1e18;
318
179
  }
319
- /** The arithmetic price drawdown to the floor, $p_{\text{floor}}/p - 1$. Negative above the floor. */
320
180
  export function floorDrawdownPrice(state) {
321
181
  return Math.exp(-Number(floorDistance(state)) / 1e18) - 1;
322
182
  }
323
- /**
324
- * Annualise a per-unit-L WAD rate over the window it accrued in.
325
- *
326
- * `F` is cumulative fee income per unit of exposure since the pool opened, so dividing by the
327
- * elapsed time and scaling to a year gives a rate directly — no price process assumed. Returns a
328
- * fraction: 0.12 is 12%.
329
- *
330
- * Treat it as what it is: a *realised* rate over one short devnet window, not a forecast.
331
- */
332
183
  export function annualise(perUnitL, elapsedSeconds) {
333
184
  if (elapsedSeconds <= 0n)
334
185
  return 0;
335
186
  return (Number(perUnitL) / 1e18) * (Number(YEAR_SECONDS) / Number(elapsedSeconds));
336
187
  }
337
- /** When a market was created, as a unix timestamp — the denominator for {@link annualise}. */
338
188
  export async function marketOpenedAt(c, m) {
339
189
  const b = await c.public.getBlock({ blockNumber: m.blockNumber });
340
190
  return b.timestamp;
341
191
  }
342
- /**
343
- * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and the one creation path
344
- * (C 18, decisions 099, 100: `RouterC.createMarket` is gone). The call mints the permanent backstop (`minBackstopL` of uncapped
345
- * liquidity to 0xdead on the rung under the opening price), so the market is born live and `account` pays dust of BOTH tokens,
346
- * and the mint fee on it, by plain ERC-20 allowance to the MANAGER: {@link approveTokenForCManager} for each first. Whoever opens
347
- * a market holds nothing of it. The policy answers who may create (`PolicyC.mayInit`): anyone at salt zero on an open policy,
348
- * the policy's authority on a closed one; {@link cGateRules} reads the same checks before a wallet is asked.
349
- */
350
192
  export async function initializeMarket(c, a) {
351
193
  const { request } = await c.public.simulateContract({
352
194
  address: managerC(c),
@@ -359,15 +201,10 @@ export async function initializeMarket(c, a) {
359
201
  }
360
202
  const ERC20_APPROVE = [{ type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "s", type: "address" }, { name: "a", type: "uint256" }], outputs: [{ type: "bool" }] }];
361
203
  const ERC20_ALLOWANCE = [{ type: "function", name: "allowance", stateMutability: "view", inputs: [{ name: "o", type: "address" }, { name: "s", type: "address" }], outputs: [{ type: "uint256" }] }];
362
- /**
363
- * Plain ERC-20 approval to the C manager — the allowance {@link initializeMarket} pulls the backstop against (C 18). Every
364
- * other C write goes through the router and Permit2 (`onboardToken`). `amount` defaults to the maximum; the backstop is dust.
365
- */
366
204
  export async function approveTokenForCManager(c, token, account, amount = (1n << 256n) - 1n) {
367
205
  const { request } = await c.public.simulateContract({ address: token, abi: ERC20_APPROVE, functionName: "approve", args: [managerC(c), amount], account: signerFor(c, account) });
368
206
  return c.wallet.writeContract(request);
369
207
  }
370
- /** Does `owner` have enough allowance on `token` for the C MANAGER to pull `need`? */
371
208
  export async function cManagerAllowanceOk(c, token, owner, need) {
372
209
  const allowance = (await c.public.readContract({ address: token, abi: ERC20_ALLOWANCE, functionName: "allowance", args: [owner, managerC(c)] }));
373
210
  return allowance >= need;
@@ -1,41 +1,15 @@
1
- /**
2
- * positions.ts — position and fee reads.
3
- *
4
- * A position CLASS is fungible at its full key: uncapped by (pool, floor), capped by
5
- * (pool, floor, cap). Holders own ERC-6909 shares of a class; fees are tracked per holder, so two
6
- * accounts holding the same class can have different claimable amounts.
7
- */
8
1
  import type { Address } from "viem";
9
2
  import { type LogswapClient } from "./client.js";
10
3
  import { type PoolKey } from "./keys.js";
11
- /** A class's aggregate state — the whole class, not one holder's slice. */
12
4
  export interface PositionClass {
13
- /** Total exposure across every holder. */
14
5
  L: bigint;
15
- /** Total shares outstanding. */
16
6
  shares: bigint;
17
- /** Fee-per-share accumulator (masterchef-style). */
18
7
  aps: bigint;
19
- /** Snapshot of `F_above[floor] − F_above[cap]` at the class's last touch. */
20
8
  insideLast: bigint;
21
9
  }
22
- /**
23
- * A class's aggregate state, read through `extsload` (C version 7: the manager's public
24
- * `positions` mapping is gone behind it, decisions 065). The slot is `CPoolState`'s:
25
- * `keccak256(abi.encode(id, POSITIONS_SLOT = 4))`, two words — (L | shares << 128) and
26
- * (aps | insideLast << 128). Pinned on chain by the integration suite.
27
- */
28
10
  export declare function getPositionClass(c: LogswapClient, id: bigint): Promise<PositionClass>;
29
- /** A holder's share balance in a class. */
30
11
  export declare function balanceOf(c: LogswapClient, owner: Address, id: bigint): Promise<bigint>;
31
- /**
32
- * A holder's claimable fees, in quote.
33
- *
34
- * For a capped class this is credit-minus-debit — two accumulator reads, `F_above[floor]` less
35
- * `F_above[cap]` — which is monotone non-decreasing, so a capped position can never owe fees.
36
- */
37
12
  export declare function feesOf(c: LogswapClient, id: bigint, owner: Address): Promise<bigint>;
38
- /** A holder's full view of one class: what they own and what they can claim. */
39
13
  export interface HolderPosition {
40
14
  id: bigint;
41
15
  key: PoolKey;
@@ -43,27 +17,10 @@ export interface HolderPosition {
43
17
  cap: bigint;
44
18
  capped: boolean;
45
19
  shares: bigint;
46
- /** The holder's pro-rata slice of the class's exposure. */
47
20
  L: bigint;
48
21
  claimableFees: bigint;
49
22
  }
50
- /**
51
- * Everything a UI needs for one holder in one class. Computes the id offline, so this costs three
52
- * reads and no id lookup.
53
- */
54
23
  export declare function getHolderPosition(c: LogswapClient, key: PoolKey, owner: Address, floor: bigint, cap?: bigint): Promise<HolderPosition>;
55
- /**
56
- * Resolve an id the manager already knows back to its (pool, floor, cap).
57
- *
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. `ClassRegistered` carries the same
60
- * information in the clear, so an indexer never needs this call.
61
- *
62
- * **Units.** The lens is inconsistent here and this wrapper hides it: `unpack` returns tick
63
- * INDICES (`kFloor`, `kCap`), while `liveFloors` returns log-price floors. Pass `tickSpacing` and
64
- * you get `floor`/`cap` in log-price WAD, the same units `mint` takes; omit it and you get the raw
65
- * indices, honestly named.
66
- */
67
24
  export declare function describeId(c: LogswapClient, id: bigint, tickSpacing?: bigint): Promise<{
68
25
  poolId: `0x${string}`;
69
26
  kFloor: bigint;
@@ -72,99 +29,40 @@ export declare function describeId(c: LogswapClient, id: bigint, tickSpacing?: b
72
29
  floor?: bigint;
73
30
  cap?: bigint;
74
31
  }>;
75
- /**
76
- * Split ERC-6909 ids into positions and token claims.
77
- *
78
- * **Do this before treating any `Transfer` as an LP event.** Bit 255 clear means a token claim — a
79
- * bearer IOU a market maker uses to park inventory inside the manager — not a position. An indexer
80
- * that skips this reports phantom LP positions for every parked balance.
81
- */
82
32
  export declare function partitionIds(ids: readonly bigint[]): {
83
33
  positions: bigint[];
84
34
  claims: bigint[];
85
35
  };
86
- /** Decode a class's floor and cap from its packed field (as carried by `ClassRegistered`). */
87
36
  export declare function describePacked(tickSpacing: bigint, packed: bigint): {
88
37
  floor: bigint;
89
38
  cap: bigint;
90
39
  capped: boolean;
91
40
  };
92
- /**
93
- * The QUOTE leg of a position at log-price `x`, in quote units.
94
- *
95
- * Mirrors the manager's `_assets` exactly, in its three cases:
96
- *
97
- * - **floor above spot** — the position is all base and holds no quote at all.
98
- * - **in range** — `L·(x − ξ)`: the buffer built up as price rose from the floor.
99
- * - **capped out** (spot at or above the cap) — `L·(cap − ξ)`, frozen. Past its cap a position
100
- * stops converting, which is what makes a capped position a resting limit order.
101
- *
102
- * Exact: this is bigint arithmetic throughout, unlike the base leg, which needs `L/p` and is
103
- * therefore transcendental. If you need base, read it from the chain rather than approximating it
104
- * here — a display-only float has no business being subtracted from a balance.
105
- */
106
41
  export declare function positionQuote(p: {
107
42
  L: bigint;
108
43
  floor: bigint;
109
44
  cap: bigint;
110
45
  capped: boolean;
111
46
  }, x: bigint): bigint;
112
- /**
113
- * The one-time mint fee at log-price `x`, in quote units — the amount `_mintCore` pulls ON TOP of
114
- * the position's own legs, so a mint's total quote pull is `positionQuote(p, x) + mintFee(p, x, rate)`.
115
- * `rate` is the MARKET's mint fee, WAD of L (`mintFeeOfKey(key)`): the fee list's next entry after the key's swap fee
116
- * (C 18, decision 099), fixed for life; there is no global `MINT_FEE`.
117
- *
118
- * Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
119
- * capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
120
- * the protocol's (decisions 058); with no treasury it goes through `F` to the LPs already
121
- * earning, and with none earning it is not charged. This is NOT the swap fee: that one is charged
122
- * per unit of |Δ log p| on swaps; this is a flat charge on L, once, at mint.
123
- *
124
- * One rung of imprecision: for a floor or cap exactly AT spot the contract consults its `currentK`
125
- * pointer (an up-move counts the tick, a down-move does not), which this offline mirror cannot see.
126
- * Preview with it; let the chain be authoritative on that boundary.
127
- */
128
47
  export declare function mintFee(p: {
129
48
  L: bigint;
130
49
  floor: bigint;
131
50
  cap: bigint;
132
51
  capped: boolean;
133
52
  }, x: bigint, rate: bigint): bigint;
134
- /**
135
- * Every UNCAPPED position `owner` holds in a market, enumerated fully on-chain by the lens — a
136
- * bitmap walk plus a balance check per live floor. No indexer, no log scan. Capped classes are
137
- * not listed here by contract (their candidate set is quadratic in live ticks); they come from
138
- * `ClassRegistered` replay when an indexer exists.
139
- */
140
53
  export interface HeldPositionRow {
141
54
  id: bigint;
142
55
  floor: bigint;
143
- /** NO_CAP for an uncapped class. */
144
56
  cap: bigint;
145
57
  capped: boolean;
146
58
  shares: bigint;
147
- /** The holder's slice of the class's exposure. */
148
59
  L: bigint;
149
- /** Claimable now, quote units. */
150
60
  fees: bigint;
151
61
  }
152
62
  export declare function positionsOf(c: LogswapClient, key: PoolKey, owner: Address): Promise<HeldPositionRow[]>;
153
- /**
154
- * EVERY class this owner holds in a pool, capped ones included — the complete book.
155
- *
156
- * `positionsOf` (the lens) enumerates the uncapped book from the ladder bitmap in one call and
157
- * cannot list capped classes: a capped id is a (floor, cap) pair, quadratic in live ticks. This
158
- * replays `ClassRegistered` — every class is registered once, on first mint, with its floor and
159
- * cap — then checks the owner's ERC-6909 balance on each and reads the class for its L, so the
160
- * holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
161
- * a read per registered class; fine for a pool's lifetime of classes.
162
- */
163
63
  export declare function holdingsOf(c: LogswapClient, key: PoolKey, owner: Address, fromBlock?: bigint, opts?: {
164
64
  indexer?: string;
165
65
  }): Promise<HeldPositionRow[]>;
166
- /** A holding's legs, exact from the lens: base (base units), the quote leg, claimable fees, and
167
- * value = base·p + quote + fees in quote units — L + quote + fees for an uncapped active class. */
168
66
  export declare function legsOf(c: LogswapClient, key: PoolKey, id: bigint, holder: Address): Promise<{
169
67
  base: bigint;
170
68
  quote: bigint;
package/dist/positions.js CHANGED
@@ -1,25 +1,11 @@
1
- /**
2
- * positions.ts — position and fee reads.
3
- *
4
- * A position CLASS is fungible at its full key: uncapped by (pool, floor), capped by
5
- * (pool, floor, cap). Holders own ERC-6909 shares of a class; fees are tracked per holder, so two
6
- * accounts holding the same class can have different claimable amounts.
7
- */
8
1
  import { encodeAbiParameters, keccak256, parseAbiItem } from "viem";
9
2
  import { lensCAbi, managerCAbi } from "./generated.js";
10
3
  import { managerC, lensC } from "./client.js";
11
4
  import { poolId, tickSpacingOf } from "./keys.js";
12
- /** `CPoolState.POSITIONS_SLOT`: the manager's `positions` mapping (`forge inspect CPoolManager storageLayout`). */
13
5
  const C_POSITIONS_SLOT = 4n;
14
6
  const U128 = (1n << 128n) - 1n;
15
7
  import { isPosition, NO_CAP, positionId, unpackFloorCap } from "./ids.js";
16
8
  import { getEventLogs } from "./history.js";
17
- /**
18
- * A class's aggregate state, read through `extsload` (C version 7: the manager's public
19
- * `positions` mapping is gone behind it, decisions 065). The slot is `CPoolState`'s:
20
- * `keccak256(abi.encode(id, POSITIONS_SLOT = 4))`, two words — (L | shares << 128) and
21
- * (aps | insideLast << 128). Pinned on chain by the integration suite.
22
- */
23
9
  export async function getPositionClass(c, id) {
24
10
  const slot = keccak256(encodeAbiParameters([{ type: "uint256" }, { type: "uint256" }], [id, C_POSITIONS_SLOT]));
25
11
  const w = (await c.public.readContract({
@@ -32,7 +18,6 @@ export async function getPositionClass(c, id) {
32
18
  const hi = w1 >> 128n;
33
19
  return { L: w0 & U128, shares: w0 >> 128n, aps: w1 & U128, insideLast: hi >= 1n << 127n ? hi - (1n << 128n) : hi };
34
20
  }
35
- /** A holder's share balance in a class. */
36
21
  export async function balanceOf(c, owner, id) {
37
22
  return c.public.readContract({
38
23
  address: managerC(c),
@@ -41,12 +26,6 @@ export async function balanceOf(c, owner, id) {
41
26
  args: [owner, id],
42
27
  });
43
28
  }
44
- /**
45
- * A holder's claimable fees, in quote.
46
- *
47
- * For a capped class this is credit-minus-debit — two accumulator reads, `F_above[floor]` less
48
- * `F_above[cap]` — which is monotone non-decreasing, so a capped position can never owe fees.
49
- */
50
29
  export async function feesOf(c, id, owner) {
51
30
  return c.public.readContract({
52
31
  address: lensC(c),
@@ -55,10 +34,6 @@ export async function feesOf(c, id, owner) {
55
34
  args: [id, owner],
56
35
  });
57
36
  }
58
- /**
59
- * Everything a UI needs for one holder in one class. Computes the id offline, so this costs three
60
- * reads and no id lookup.
61
- */
62
37
  export async function getHolderPosition(c, key, owner, floor, cap = NO_CAP) {
63
38
  const id = positionId(poolId(key), tickSpacingOf(key), floor, cap);
64
39
  const [cls, shares, claimableFees] = await Promise.all([
@@ -77,18 +52,6 @@ export async function getHolderPosition(c, key, owner, floor, cap = NO_CAP) {
77
52
  claimableFees,
78
53
  };
79
54
  }
80
- /**
81
- * Resolve an id the manager already knows back to its (pool, floor, cap).
82
- *
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. `ClassRegistered` carries the same
85
- * information in the clear, so an indexer never needs this call.
86
- *
87
- * **Units.** The lens is inconsistent here and this wrapper hides it: `unpack` returns tick
88
- * INDICES (`kFloor`, `kCap`), while `liveFloors` returns log-price floors. Pass `tickSpacing` and
89
- * you get `floor`/`cap` in log-price WAD, the same units `mint` takes; omit it and you get the raw
90
- * indices, honestly named.
91
- */
92
55
  export async function describeId(c, id, tickSpacing) {
93
56
  const r = (await c.public.readContract({
94
57
  address: lensC(c),
@@ -105,13 +68,6 @@ export async function describeId(c, id, tickSpacing) {
105
68
  cap: r[3] ? r[2] * tickSpacing : NO_CAP,
106
69
  };
107
70
  }
108
- /**
109
- * Split ERC-6909 ids into positions and token claims.
110
- *
111
- * **Do this before treating any `Transfer` as an LP event.** Bit 255 clear means a token claim — a
112
- * bearer IOU a market maker uses to park inventory inside the manager — not a position. An indexer
113
- * that skips this reports phantom LP positions for every parked balance.
114
- */
115
71
  export function partitionIds(ids) {
116
72
  const positions = [];
117
73
  const claims = [];
@@ -119,46 +75,15 @@ export function partitionIds(ids) {
119
75
  (isPosition(id) ? positions : claims).push(id);
120
76
  return { positions, claims };
121
77
  }
122
- /** Decode a class's floor and cap from its packed field (as carried by `ClassRegistered`). */
123
78
  export function describePacked(tickSpacing, packed) {
124
79
  return unpackFloorCap(tickSpacing, packed);
125
80
  }
126
- /**
127
- * The QUOTE leg of a position at log-price `x`, in quote units.
128
- *
129
- * Mirrors the manager's `_assets` exactly, in its three cases:
130
- *
131
- * - **floor above spot** — the position is all base and holds no quote at all.
132
- * - **in range** — `L·(x − ξ)`: the buffer built up as price rose from the floor.
133
- * - **capped out** (spot at or above the cap) — `L·(cap − ξ)`, frozen. Past its cap a position
134
- * stops converting, which is what makes a capped position a resting limit order.
135
- *
136
- * Exact: this is bigint arithmetic throughout, unlike the base leg, which needs `L/p` and is
137
- * therefore transcendental. If you need base, read it from the chain rather than approximating it
138
- * here — a display-only float has no business being subtracted from a balance.
139
- */
140
81
  export function positionQuote(p, x) {
141
82
  if (p.floor > x)
142
83
  return 0n;
143
84
  const upper = p.capped && p.cap <= x ? p.cap : x;
144
85
  return (p.L * (upper - p.floor)) / 10n ** 18n;
145
86
  }
146
- /**
147
- * The one-time mint fee at log-price `x`, in quote units — the amount `_mintCore` pulls ON TOP of
148
- * the position's own legs, so a mint's total quote pull is `positionQuote(p, x) + mintFee(p, x, rate)`.
149
- * `rate` is the MARKET's mint fee, WAD of L (`mintFeeOfKey(key)`): the fee list's next entry after the key's swap fee
150
- * (C 18, decision 099), fixed for life; there is no global `MINT_FEE`.
151
- *
152
- * Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
153
- * capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
154
- * the protocol's (decisions 058); with no treasury it goes through `F` to the LPs already
155
- * earning, and with none earning it is not charged. This is NOT the swap fee: that one is charged
156
- * per unit of |Δ log p| on swaps; this is a flat charge on L, once, at mint.
157
- *
158
- * One rung of imprecision: for a floor or cap exactly AT spot the contract consults its `currentK`
159
- * pointer (an up-move counts the tick, a down-move does not), which this offline mirror cannot see.
160
- * Preview with it; let the chain be authoritative on that boundary.
161
- */
162
87
  export function mintFee(p, x, rate) {
163
88
  if (p.floor > x || (p.capped && p.cap <= x))
164
89
  return 0n;
@@ -173,29 +98,17 @@ export async function positionsOf(c, key, owner) {
173
98
  }));
174
99
  return rows.map((r) => ({ id: r.id, floor: r.floor, cap: NO_CAP, capped: false, shares: r.shares, L: r.L, fees: r.fees }));
175
100
  }
176
- const ID_REGISTERED = parseAbiItem("event ClassRegistered(bytes32 indexed poolId, uint256 indexed id, int256 floor, int256 cap, bool capped)"); // C 17: poolId first;
177
- /** Every class id ever registered in `pool` (`ClassRegistered`), from the indexer's table or the node. */
101
+ const ID_REGISTERED = parseAbiItem("event ClassRegistered(bytes32 indexed poolId, uint256 indexed id, int256 floor, int256 cap, bool capped)");
178
102
  async function registeredIds(c, pool, fromBlock, indexer) {
179
103
  const { logs } = await getEventLogs(c, { indexer, address: managerC(c), event: ID_REGISTERED, args: { poolId: pool }, fromBlock });
180
104
  return logs.map((l) => l.args.id ?? 0n).filter((id) => id !== 0n);
181
105
  }
182
- /**
183
- * EVERY class this owner holds in a pool, capped ones included — the complete book.
184
- *
185
- * `positionsOf` (the lens) enumerates the uncapped book from the ladder bitmap in one call and
186
- * cannot list capped classes: a capped id is a (floor, cap) pair, quadratic in live ticks. This
187
- * replays `ClassRegistered` — every class is registered once, on first mint, with its floor and
188
- * cap — then checks the owner's ERC-6909 balance on each and reads the class for its L, so the
189
- * holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
190
- * a read per registered class; fine for a pool's lifetime of classes.
191
- */
192
106
  export async function holdingsOf(c, key, owner, fromBlock, opts = {}) {
193
107
  const pool = poolId(key);
194
108
  const indexer = opts.indexer ?? c.indexerUrl;
195
109
  const ids = await registeredIds(c, pool, fromBlock, indexer);
196
110
  if (ids.length === 0)
197
111
  return [];
198
- // one lens call: balance, class L, fees, floor and cap for every id the owner holds
199
112
  const rows = (await c.public.readContract({
200
113
  address: lensC(c),
201
114
  abi: lensCAbi,
@@ -204,8 +117,6 @@ export async function holdingsOf(c, key, owner, fromBlock, opts = {}) {
204
117
  }));
205
118
  return rows.map((r) => ({ id: r.id, floor: r.floor, cap: r.capped ? r.cap : NO_CAP, capped: r.capped, shares: r.shares, L: r.L, fees: r.fees }));
206
119
  }
207
- /** A holding's legs, exact from the lens: base (base units), the quote leg, claimable fees, and
208
- * value = base·p + quote + fees in quote units — L + quote + fees for an uncapped active class. */
209
120
  export async function legsOf(c, key, id, holder) {
210
121
  const [base, quote, fees, value] = (await c.public.readContract({
211
122
  address: lensC(c),
package/dist/quote.d.ts CHANGED
@@ -1,15 +1 @@
1
- /**
2
- * quote.ts — reading a revert-quoter's answer.
3
- *
4
- * Both managers' quoters are the router's (`Router.quoteSwap`, F: decision 049, C: decision 092): the real swap runs
5
- * in the manager's lock and the contract reverts with `QuoteResult(uint256)`. The value is therefore decoded out of the
6
- * revert, not returned. There is no second pricing path to drift from the first.
7
- */
8
- /**
9
- * `QuoteResult(uint256)` — selector then one word. viem nests the revert data several layers deep
10
- * depending on the transport, so walk for it rather than guessing the shape.
11
- *
12
- * The selector is DERIVED, not written down. A hardcoded one is wrong silently: the decode simply
13
- * never matches and every quote rethrows as if the swap had failed.
14
- */
15
1
  export declare function findQuoteResult(err: unknown): bigint | null;