@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/src/fpool.ts DELETED
@@ -1,2049 +0,0 @@
1
- /**
2
- * fpool.ts — the `ManagerF` surface: n bases, one quote, one shared floor.
3
- *
4
- * The other primitive. `ManagerC` gives every position its own floor on a tick ladder;
5
- * `ManagerF` gives every share the SAME floor and deletes the ladder, the accumulators and the
6
- * per-position accounting with it. Reading the two side by side is the fastest way to understand
7
- * either.
8
- *
9
- * **A pool is an ID, not an address.** Both primitives are singletons now, so neither has a
10
- * per-pool deployment — but they are addressed differently and for a reason. The C manager rides
11
- * its whole `PoolKey` in calldata because that key is small, fixed and wholly needed. An F-pool
12
- * key is variable-length and only ever partially needed (no swap path is O(n)), so it is stored
13
- * once at `initialize` and every later call names `(poolId, j)`. Callers hold a `bytes32`.
14
- *
15
- * **Two products, one contract.** The basket (n > 1) and the launch (n = 1, the creator alone on
16
- * the lever) are the same bytecode under two key fields — the KIND (what the manager promises
17
- * structurally) and the POLICY (the pool's policy: its roles, its gates, the terms of every harvest
18
- * and release) — and nothing in the maths. `describeFPool` below reports
19
- * which shape a given pool is, because a UI has to decide what to render.
20
- *
21
- * **The roles are the policy's** (policy.md; F version 41). The manager holds no authority, gate or list: it asks
22
- * the pool's policy `may(poolId, action, who)` and acts on the answer (the one thing it caches is the operator,
23
- * admitted with no call). One policy contract, `PolicyF`, serves every F pool; its kinds — public, desk, POL, pad —
24
- * are parameter sets, every one an immutable ({@link FPolicyTerms}). The policy's AUTHORITY (immutable; the LOG
25
- * Authority of the day on the LOG's own instances) appoints each pool's OPERATOR, who runs the pool: funds it
26
- * ({@link fPoolDeploy}), harvests, closes, sets its gate modes and its name. `getFPool` carries the policy and what
27
- * it declared (`flags`), {@link getFPoolRoles} reads the roles FROM the policy, and every setting is a write to the
28
- * policy ({@link fPoolAppointOperator}, {@link fPoolSetSwapMode}, {@link fPoolSetMintMode}, {@link fPolicySetRights}, …).
29
- * A policy has no setter of its own: a change is a new policy, approved by the registry; the key's policy is the
30
- * pool's for life.
31
- *
32
- * **Zaps live on the ROUTER, not here.** `RouterF` is F's own router and its own Permit2 spender (decision 096: one
33
- * router per manager; a second spender is a second signature, not a second on-chain approval). See
34
- * `fPoolZapIn`/`fPoolZapOut` below, which target `addresses.routerF`; a wallet's Permit2 allowance for it is
35
- * `onboardToken(c, "F", token, need)`.
36
- */
37
-
38
- import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256, toFunctionSelector, type Address, type Hash, type Hex } from "viem";
39
- import { managerFAbi, lensFAbi, routerFAbi, policyFAbi, policyRegistryAbi } from "./generated.js";
40
-
41
- /**
42
- * One contract, one ABI (F version 12): `harvest`, `claim`, `close`, `deployLiquidity`, the fee list are `ManagerF`'s own
43
- * code. The roles left it for the policy in F version 15; since F 41 there is one policy contract, {@link policyFAbi}
44
- * (`PolicyF`, policy.md): every F pool's operator, gate modes and lists.
45
- */
46
- export { managerFAbi, policyFAbi };
47
- import { clientChainId, type LogswapClient } from "./client.js";
48
- import { FEE_LIST, FEE_LIST_BP } from "./keys.js";
49
- import { findQuoteResult } from "./quote.js";
50
- import { fallBackUnlessRejected, signerFor } from "./write.js";
51
- import { getEventLogs } from "./history.js";
52
-
53
- const WAD = 10n ** 18n;
54
- const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" as const;
55
-
56
- /**
57
- * The bits a policy declares at birth, in `Pool.flags` (decision 098; `ASK_SWAP` / `ASK_MINT` before): with a gate bit off nothing is
58
- * asked; with it on the manager admits the cached operator with no policy call and asks the policy about everyone else.
59
- */
60
- export const GATE_SWAP = 1;
61
- export const GATE_MINT = 2;
62
- /** `GATE_SWAP | GATE_MINT`: the bits `setGates` carries (`SEED_TO_DEAD` is the birth's alone). */
63
- export const GATES = GATE_SWAP | GATE_MINT;
64
-
65
- /** Everything scalar about a basket pool, in one round trip's worth of reads. */
66
- export interface FPoolState {
67
- /** The pool's id — the hash of its key. There is no per-pool address. */
68
- poolId: Hex;
69
- quote: Address;
70
- bases: Address[];
71
- /** Each base asset's fraction of the pool's `L`, WAD, summing to WAD, derived at each deployment (`weights` before decision 090). `L_j = liquidityWeight_j · L`. */
72
- liquidityWeights: bigint[];
73
- /** Per-asset log prices, WAD. Price is derived; `x` is the state. */
74
- x: bigint[];
75
- /** Quote reserve. The one leg a base→quote swap can exhaust. */
76
- Q: bigint;
77
- /** Total exposure. Grows on mint, shrinks on burn; never moves on a swap. */
78
- L: bigint;
79
- /** The swap fee, WAD: `F_FEE_LIST[key.swapFeeIdx]`, resolved by the manager at the birth (policy.md §6). Never 0: the list has no zero. */
80
- swapFee: bigint;
81
- /** The mint fee, WAD of newly-minted L: the list's next entry after the swap fee (the same at the top), resolved at the birth — nothing was chosen ({@link fMintFeeOf}). */
82
- mintFee: bigint;
83
- /** The reference log floor (`refLogFloor`): where the floor stood at the seed (re-based by a capital harvest and at each step); income is counted from it. `theta0` before F version 25. */
84
- refLogFloor: bigint;
85
- /** logFloor = X − Q/L, the log of the pool's current floor price: where the bid runs out. Derived, never stored. `theta` before F version 25. */
86
- logFloor: bigint;
87
- /** X = Σ w_j x_j, the composite index. */
88
- compositeX: bigint;
89
- /** This generation's income still in the pool, quote: L·(refLogFloor − logFloor). */
90
- unharvested: bigint;
91
- /**
92
- * The pool's one cap as a log ratio (decisions 061, 075): ln(cap price / seed price) in 1e-6 log units, set by the
93
- * generation's `deployLiquidity`; each asset's maximum price is its own seed price times it. 0 is uncapped (cap ∞).
94
- * The liquidity per unit of base value is 1/(1 − e^{−value}): {@link fPoolLeverageOfCap}.
95
- */
96
- lnCapOverSeed: number;
97
- /** Σ = ∫ Σ_j w_j (dx_j)², accrued even though the fee is fixed — the kernel stays calculable. */
98
- realizedVariance: bigint;
99
- /**
100
- * The pool's policy for life: the contract the key names, holding the pool's roles and answering every question the
101
- * manager does not decide itself. Read its roles with {@link getFPoolRoles}, its terms with {@link fPolicyTermsOf}; one
102
- * of the deployment's four ({@link fPoolPolicyFor}) on every protocol pool.
103
- */
104
- policy: Address;
105
- /**
106
- * What the policy declared for the pool (`Pool.flags`, decision 098): the gate bits {@link GATE_SWAP} and {@link GATE_MINT} (set by the
107
- * policy's `setGates` as the operator changes the modes) and the birth bit {@link SEED_TO_DEAD} (a pad's, the pool's for life).
108
- */
109
- flags: number;
110
- /**
111
- * The operator the manager caches (`Pool.operator`): the one account that funds, harvests and closes the pool, admitted by a gated swap or
112
- * mint with no policy call. The policy's `operator(poolId)`, synced at every appointment ({@link getFPoolRoles}).
113
- */
114
- operator: Address;
115
- /** The time (unix seconds) of the last harvest / composition action: no swap runs at that timestamp (F version 29; a block number before). */
116
- restructureTime: number;
117
- /** What the pool is — a label read off its POLICY's immutables; see {@link FPoolKind}. */
118
- kind: FPoolKind;
119
- /** False before the first `deployLiquidity` — and between a `close` and the next one (the pool is INACTIVE: listed, or closed). */
120
- seeded: boolean;
121
- /**
122
- * The live GENERATION (policy.md §10). The first is 0. A `close` freezes it into a bundle its shares redeem
123
- * ({@link fPoolRedeem}) and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens — so an
124
- * inactive pool after a close already reads the number its next deploy will carry. The share id carries it
125
- * ({@link fPoolShareId}): generations `0 … gen-1` are claims ({@link fPoolClaimsOf}) and `gen` is the pool.
126
- */
127
- gen: number;
128
- totalSupply: bigint;
129
- /** What the pool holds of each base — the STATE; the mark `x` is derived from it. */
130
- reserves: bigint[];
131
- /** The reserve every price reads: `reserves[j] + L_j·κ_j` on a capped pool (061), `reserves[j]` otherwise. */
132
- virtualReserves: bigint[];
133
- /** κ_j = e^{−μ_j}, WAD: each leg's phantom reserve per unit of its liquidity. 0 uncapped. */
134
- kappa: bigint[];
135
- }
136
-
137
- /**
138
- * The lens's raw F pool struct — what the manager's `getPool` returned. Since F version 25 the
139
- * manager's typed views are behind `extsload` (decisions 062) and the lens reads them; one call.
140
- */
141
- async function rawFPool(c: LogswapClient, poolId: Hex) {
142
- const [p] = await c.public.readContract({
143
- address: c.addresses.lensF,
144
- abi: lensFAbi,
145
- functionName: "getPools",
146
- args: [[poolId]],
147
- });
148
- if (!p || /^0x0{40}$/i.test(p.quote)) throw new Error(`logswap: no F pool with id ${poolId}`);
149
- return p;
150
- }
151
-
152
- /** Read a basket pool whole: one lens call (`pool`, F version 25) plus the policy's terms (cached per policy). The name is a log query apart: {@link fPoolNameOf}. */
153
- export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolState> {
154
- const v = await c.public.readContract({
155
- address: c.addresses.lensF,
156
- abi: lensFAbi,
157
- functionName: "pool",
158
- args: [poolId],
159
- });
160
- const p = v.pool;
161
- // A pool that was never created reads as an all-zero struct rather than reverting, so the
162
- // absence has to be named here or every caller mistakes "no such pool" for "a pool holding
163
- // nothing". `quote` is the manager's own existence test (`_live`), and it is what the create
164
- // flow's resumability turns on: an initialized-but-unseeded pool MUST still read, so this
165
- // cannot be a check on `seeded`.
166
- if (/^0x0{40}$/i.test(p.quote)) throw new Error(`logswap: no F pool with id ${poolId}`);
167
- const kind = await fPoolKindOfPolicy(c, p.policy);
168
- return {
169
- poolId,
170
- quote: p.quote,
171
- bases: v.baseAssets.map((l) => l.base),
172
- liquidityWeights: v.baseAssets.map((l) => l.liquidityWeight),
173
- x: v.baseAssets.map((l) => l.x), // derived by the manager: x_j = ln(w_j·L / R̃_j)
174
- Q: p.Q,
175
- L: p.L,
176
- swapFee: p.swapFee,
177
- mintFee: p.mintFee,
178
- refLogFloor: p.refLogFloor,
179
- logFloor: v.logFloor,
180
- compositeX: v.compositeX,
181
- unharvested: v.unharvested,
182
- lnCapOverSeed: Number(p.lnCapOverSeed),
183
- realizedVariance: p.realizedVariance,
184
- policy: p.policy,
185
- flags: Number(p.flags),
186
- operator: p.operator,
187
- restructureTime: Number(p.restructureTime),
188
- kind,
189
- seeded: p.seeded,
190
- gen: Number(p.gen),
191
- totalSupply: p.shares,
192
- reserves: v.baseAssets.map((l) => l.reserve), // the state
193
- virtualReserves: v.baseAssets.map((l) => l.virtualReserve),
194
- kappa: v.baseAssets.map((l) => l.kappa),
195
- };
196
- }
197
-
198
- /**
199
- * The kind of pool — a LABEL read off its policy's immutables (policy.md §4.1; the manager knows no kind, and the policy's
200
- * `kind()` says `"f"` for every instance). `public`: an `open` policy — anyone creates at salt zero, no gate ever, the
201
- * LOG runs the pool. `pad`: `seedToDead` — the deploy's shares are the pool's, a harvest takes income only, the pool never
202
- * closes. `pol`: a closed policy keeping a bid under its pools (`quoteBuffer`), a treasury's. `desk`: any other closed
203
- * policy — a sponsor's, gates by pool. The LOG's four instances are one of each ({@link fPoolPolicyFor}); a third
204
- * party's policy is whatever its terms say ({@link fPolicyKindOf}).
205
- */
206
- export type FPoolKind = "public" | "desk" | "pol" | "pad";
207
- /** The policy's birth-time declaration that the deploy's shares are the pool's (`seedToDead`, a pad's), in `flags`. */
208
- export const SEED_TO_DEAD = 4;
209
-
210
- /** A policy's parameters — `PolicyF`'s immutables (policy.md §4.1), set at its deployment and never changed. */
211
- export interface FPolicyTerms {
212
- policy: Address;
213
- /** The authority as deployed; zero defers to the LOG Authority of the day — {@link getFPoolRoles} reads the live answer (`authority()`). */
214
- fixedAuthority: Address;
215
- /** Anyone initializes; the salt must be zero; no gate is ever set on its pools. */
216
- open: boolean;
217
- /** The deploy's shares go to 0xdead: a pad. The pool never closes and a harvest takes income only (the manager's rule as well). */
218
- seedToDead: boolean;
219
- /** A harvest takes income and never capital. */
220
- incomeHarvestOnly: boolean;
221
- /** WAD, at most the manager's `INCOME_TAX_MAX`: the tax on the payer's slice of each harvest's income (§8). */
222
- incomeTaxRate: bigint;
223
- /** The entries of {@link F_FEE_LIST} a pool may be born with, a bit per index; 0 lists all eight ({@link fFeesAllowed}). */
224
- feeMask: number;
225
- /** Legs per pool, 1..8. */
226
- lenMax: number;
227
- /** Millionths of ln(cap / seed price): the least distance a cap may sit above the seed price; 0 allows any cap, none included (§7). */
228
- lnCapMin: number;
229
- /** WAD, a multiple of L: the bid a deploy must bring and a harvest must leave. */
230
- quoteBuffer: bigint;
231
- /** The policy lists the quotes a pool may be born on (`quoteListed`); false: any quote. */
232
- quoteCurated: boolean;
233
- /** The policy lists the bases a pool may hold (`baseListed`); false: any base. */
234
- baseCurated: boolean;
235
- /** The label the terms spell: {@link fPolicyKindOf}. */
236
- kind: FPoolKind;
237
- }
238
-
239
- const termsCache = new Map<string, Promise<FPolicyTerms>>();
240
-
241
- /** The label a policy's terms spell (see {@link FPoolKind}). Pure. */
242
- export function fPolicyKindOf(t: Pick<FPolicyTerms, "open" | "seedToDead" | "quoteBuffer">): FPoolKind {
243
- if (t.open) return "public";
244
- if (t.seedToDead) return "pad";
245
- if (t.quoteBuffer > 0n) return "pol";
246
- return "desk";
247
- }
248
-
249
- /**
250
- * A policy's terms, read once per policy address and cached for the client's chain (the policies sit at one address on
251
- * every release chain): every field is an immutable, so the first read is the last. A failed read is not cached.
252
- */
253
- export async function fPolicyTermsOf(c: LogswapClient, policy: Address): Promise<FPolicyTerms> {
254
- const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
255
- let hit = termsCache.get(key);
256
- if (!hit) {
257
- const rd = <T>(functionName: string) => c.public.readContract({ address: policy, abi: policyFAbi, functionName } as never) as Promise<T>;
258
- hit = Promise.all([
259
- rd<Address>("fixedAuthority"),
260
- rd<boolean>("open"),
261
- rd<boolean>("seedToDead"),
262
- rd<boolean>("incomeHarvestOnly"),
263
- rd<bigint>("incomeTaxRate"),
264
- rd<number | bigint>("feeMask"),
265
- rd<number | bigint>("lenMax"),
266
- rd<number | bigint>("lnCapMin"),
267
- rd<bigint>("quoteBuffer"),
268
- rd<boolean>("quoteCurated"),
269
- rd<boolean>("baseCurated"),
270
- ]).then(([fixedAuthority, open, seedToDead, incomeHarvestOnly, incomeTaxRate, feeMask, lenMax, lnCapMin, quoteBuffer, quoteCurated, baseCurated]) => {
271
- const t = {
272
- policy,
273
- fixedAuthority,
274
- open,
275
- seedToDead,
276
- incomeHarvestOnly,
277
- incomeTaxRate,
278
- feeMask: Number(feeMask),
279
- lenMax: Number(lenMax),
280
- lnCapMin: Number(lnCapMin),
281
- quoteBuffer,
282
- quoteCurated,
283
- baseCurated,
284
- };
285
- return { ...t, kind: fPolicyKindOf(t) };
286
- });
287
- termsCache.set(key, hit);
288
- hit.catch(() => termsCache.delete(key)); // a failed read is not a fact
289
- }
290
- return hit;
291
- }
292
-
293
- /** What a policy IS, as a label: {@link fPolicyTermsOf}'s `kind`. One read per policy address, cached. */
294
- export async function fPoolKindOfPolicy(c: LogswapClient, policy: Address): Promise<FPoolKind> {
295
- return (await fPolicyTermsOf(c, policy)).kind;
296
- }
297
-
298
- /**
299
- * The pool's label — the last `NameSet` its policy emitted for it: the operator's word, mutable, never identity. Nothing is
300
- * stored on chain (policy.md §4.3), so this is a log query — pass `indexer`, or set the client's. "" when never named.
301
- */
302
- export async function fPoolNameOf(c: LogswapClient, poolId: Hex, opts: { policy?: Address; fromBlock?: bigint; indexer?: string } = {}): Promise<string> {
303
- const policy = opts.policy ?? (await fPoolPolicyOf(c, poolId));
304
- type Ev = Extract<(typeof policyFAbi)[number], { type: "event"; name: "NameSet" }>;
305
- const ev = policyFAbi.find((x): x is Ev => x.type === "event" && x.name === "NameSet");
306
- if (!ev) throw new Error("logswap: NameSet event missing from the generated ABI");
307
- const { logs } = await getEventLogs<{ poolId: Hex; name: Hex }>(c, { indexer: opts.indexer, address: policy, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
308
- const last = logs[logs.length - 1];
309
- return last ? bytes32ToText(last.args.name) : "";
310
- }
311
-
312
- /**
313
- * The deployment's named policies (its artifact keys): the LOG's four `PolicyF` instances — `public` (open: anyone creates at
314
- * salt zero, no gate ever), `private` (the LOG's desk: closed, gates by pool), `pol`, `pad`. The keys predate the one-contract
315
- * policy and are kept.
316
- */
317
- export type FPolicySlot = "public" | "private" | "pol" | "pad";
318
-
319
- /** The deployment's policy for a slot — the one a key names when no `policy` is given. */
320
- export function fPoolPolicyFor(c: LogswapClient, slot: FPolicySlot): Address {
321
- const a = c.addresses;
322
- const policy = slot === "public" ? a.publicPolicy : slot === "private" ? a.privatePolicy : slot === "pol" ? a.polPolicy : a.padPolicy;
323
- if (!policy) throw new Error(`logswap: this deployment carries no ${slot} policy`);
324
- return policy;
325
- }
326
-
327
- /** The policy a pool named in its key — one read; {@link getFPool} carries it too. */
328
- export async function fPoolPolicyOf(c: LogswapClient, poolId: Hex): Promise<Address> {
329
- return (await rawFPool(c, poolId)).policy;
330
- }
331
-
332
- /**
333
- * A pool's roles, as its POLICY holds them (policy.md §2). The AUTHORITY is the policy's — one address per policy, immutable,
334
- * the LOG Authority of the day on the LOG's own instances — and appoints the pool's OPERATOR (zero resets it to the authority),
335
- * who runs the pool: `deployLiquidity`, `harvest`, `close`, the two gate modes, the name; the operator pays the seed and holds
336
- * its shares. The modes are the pool's; the lists they consult are the policy's ({@link fPolicyRightsOf}).
337
- */
338
- export interface FPoolRoles {
339
- policy: Address;
340
- /** The policy's authority now (`authority()`): its immutable, or the registry's LOG Authority when that is zero. */
341
- authority: Address;
342
- /** The pool's operator (`operator(poolId)`): the authority at birth until re-appointed. Zero: the policy never held this pool. */
343
- operator: Address;
344
- /** Swap admission: everyone (`open`), the policy's swap list (`listed`; the operator always passes) or the operator alone. Always `open` under an open policy. */
345
- swapMode: FPoolMode;
346
- /** Mint admission, at least as restrictive as the swap mode (`ModeOrder`): the same three, the mint list in `listed`. */
347
- mintMode: FPoolMode;
348
- }
349
-
350
- /** `IPolicyF.Mode`: Open = 0, Listed = 1, Operator = 2 — the order `open < listed < operator` is what `mintMode ≥ swapMode` compares. */
351
- export type FPoolMode = "open" | "listed" | "operator";
352
- const MODES: readonly FPoolMode[] = ["open", "listed", "operator"];
353
- /** The gate modes in `IPolicyF.Mode` order — the index is the on-chain ordinal. */
354
- export const fPoolModes: readonly FPoolMode[] = MODES;
355
-
356
- /** Read a pool's roles from its policy. `state` saves the `getPool` round trip when the policy is already in hand. */
357
- export async function getFPoolRoles(c: LogswapClient, poolId: Hex, state?: Pick<FPoolState, "policy">): Promise<FPoolRoles> {
358
- const policy = state?.policy ?? (await fPoolPolicyOf(c, poolId));
359
- const rd = <T>(functionName: string, args: readonly unknown[] = []) =>
360
- c.public.readContract({ address: policy, abi: policyFAbi, functionName, args } as never) as Promise<T>;
361
- const [authority, operator, swap, mint] = await Promise.all([
362
- rd<Address>("authority"),
363
- rd<Address>("operator", [poolId]),
364
- rd<number | bigint>("swapMode", [poolId]),
365
- rd<number | bigint>("mintMode", [poolId]),
366
- ]);
367
- return { policy, authority, operator, swapMode: MODES[Number(swap)] ?? "open", mintMode: MODES[Number(mint)] ?? "open" };
368
- }
369
-
370
- /** Which of the two products a pool is configured as — a pad is a launch, anything else a basket/pool. A UI has to choose what to render. */
371
- export type FPoolShape = "launch" | "basket";
372
-
373
- export interface FPoolDescription {
374
- /** The pad is the launch shape, by the kind. */
375
- shape: FPoolShape;
376
- legs: number;
377
- /** True when the pool holds no quote: an all-base resting ask. base→quote is the one blocked path. */
378
- atFloor: boolean;
379
- /**
380
- * This generation's fee income still in the pool, quote: `L·(refLogFloor − logFloor)` (F version 14 —
381
- * `feePerL` before, per unit L). A harvest of capital moves the reference floor, so this counts
382
- * from the first wei after it.
383
- */
384
- unharvested: bigint;
385
- /** What a harvest takes with `extra` 0: the income, at most the bid. */
386
- income: bigint;
387
- /** The most capital a harvest may take beside the income (`extra`): `Q − income − quoteBuffer·L`; 0 under an income-only policy and on a pad ({@link fPoolHarvestRoom}). */
388
- capitalRoom: bigint;
389
- /** The most a harvest may take now, income and capital: `income + capitalRoom`. */
390
- harvestable: bigint;
391
- }
392
-
393
- /**
394
- * What a harvest may take now (policy.md §9): the income `I = min(unharvested, Q)` always; capital on top of it up to
395
- * `Q − I − quoteBuffer·L` (`QuoteTooThin` past it), none where the policy is income-only (`IncomeOnly`) or the pool a pad
396
- * (`SEED_TO_DEAD`: the manager's own rule, `HarvestLimit`). Nothing on an unfunded pool.
397
- */
398
- export function fPoolHarvestRoom(
399
- s: Pick<FPoolState, "Q" | "L" | "unharvested" | "flags">,
400
- t: Pick<FPolicyTerms, "incomeHarvestOnly" | "quoteBuffer">,
401
- ): { income: bigint; capital: bigint } {
402
- if (s.L === 0n) return { income: 0n, capital: 0n };
403
- const income = s.unharvested < s.Q ? s.unharvested : s.Q;
404
- if (t.incomeHarvestOnly || (s.flags & SEED_TO_DEAD) !== 0) return { income, capital: 0n };
405
- const keep = income + (s.L * t.quoteBuffer + WAD - 1n) / WAD; // `mulWadUp`, as the policy rounds
406
- return { income, capital: s.Q > keep ? s.Q - keep : 0n };
407
- }
408
-
409
- export async function describeFPool(c: LogswapClient, s: FPoolState): Promise<FPoolDescription> {
410
- // an unfunded pool has no L: nothing earned, nothing to harvest
411
- const terms = await fPolicyTermsOf(c, s.policy);
412
- const { income, capital } = fPoolHarvestRoom(s, terms);
413
- return {
414
- shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
415
- legs: s.bases.length,
416
- atFloor: s.Q === 0n,
417
- unharvested: s.L > 0n ? s.unharvested : 0n,
418
- income,
419
- capitalRoom: capital,
420
- harvestable: income + capital,
421
- };
422
- }
423
-
424
- /** `p_j = e^{x_j}`, lossy the way any float conversion is. Compare in log space when it matters. */
425
- export function fPoolPriceOf(x: bigint, scale = 1): number {
426
- return Math.exp(Number(x) / 1e18) * scale;
427
- }
428
-
429
- /**
430
- * Value per share at the pool's own marks, WAD. Uncapped, `V = L + Q`. Capped (decisions 061), leg
431
- * j's base is worth `L_j·R_j/R̃_j`, less than `L_j` by the phantom the cap removed — the lens's
432
- * `shareValue`, without the call.
433
- */
434
- export function fPoolShareValue(s: FPoolState): bigint {
435
- if (s.totalSupply === 0n) return 0n;
436
- let v = s.L + s.Q;
437
- if (s.lnCapOverSeed !== 0) {
438
- v = s.Q;
439
- for (let j = 0; j < s.reserves.length; j++) {
440
- const rv = s.virtualReserves[j]!;
441
- if (rv !== 0n) v += (((s.liquidityWeights[j]! * s.L) / WAD) * s.reserves[j]!) / rv;
442
- }
443
- }
444
- return (v * WAD) / s.totalSupply;
445
- }
446
-
447
- // ─── swaps ────────────────────────────────────────────────────────────────────
448
- // Exact-in only. Three paths; the third is the one that makes a basket a basket.
449
-
450
- export interface FPoolSwapArgs {
451
- poolId: Hex;
452
- /** Leg index into `bases`. */
453
- j: number;
454
- amountIn: bigint;
455
- /**
456
- * The least the swap must return. Required: an F swap is exact-in, and without a floor on the
457
- * output a front-run takes the difference. {@link fPoolQuoteSwap} is exact; bound it with
458
- * {@link withSlippage} (`"output"`).
459
- */
460
- minOut: bigint;
461
- /** Who receives the out leg. Defaults to the account. */
462
- to?: Address;
463
- /** Absolute unix seconds. Defaulted to a bounded window, as every router write is. */
464
- deadline?: bigint;
465
- account: Address;
466
- }
467
-
468
- /**
469
- * All three F swaps go through the ROUTER's `swapExactIn` overload — the same surface as a C
470
- * swap: Permit2 pull, `minOut`, recipient, deadline. The manager's direct `swapQuoteIn` etc.
471
- * remain callable (plain allowance to the manager, settle to caller) but are the primitive's
472
- * interface, not the SDK's: routing everywhere is what keeps the two pools identical to use.
473
- */
474
- async function fSwap(c: LogswapClient, a: FPoolSwapArgs, kind: FPoolQuoteKind, k = 0) {
475
- const st = await getFPool(c, a.poolId);
476
- const pull = kind === FPoolQuoteKind.QuoteIn ? st.quote : st.bases[a.j]!;
477
- return writeRouter(
478
- c,
479
- "swapExactIn",
480
- [a.poolId, kind, BigInt(a.j), BigInt(k), a.amountIn, a.minOut, a.to ?? a.account, a.deadline ?? defaultDeadline()],
481
- a.account,
482
- [pull],
483
- );
484
- }
485
-
486
- export async function fPoolSwapQuoteIn(c: LogswapClient, a: FPoolSwapArgs) {
487
- return fSwap(c, a, FPoolQuoteKind.QuoteIn);
488
- }
489
-
490
- export async function fPoolSwapBaseIn(c: LogswapClient, a: FPoolSwapArgs) {
491
- return fSwap(c, a, FPoolQuoteKind.BaseIn);
492
- }
493
-
494
- /**
495
- * Base j → base k. Needs no quote, works at Q = 0, and cannot cross the floor: X is held
496
- * exactly up to the in-kind fee. Note it moves BOTH quote prices — p_j down, p_k up — because the
497
- * pool has one coordinate per asset and every trade moves at least one.
498
- */
499
- export async function fPoolSwapBaseForBase(c: LogswapClient, a: FPoolSwapArgs & { k: number }) {
500
- return fSwap(c, a, FPoolQuoteKind.BaseForBase, a.k);
501
- }
502
-
503
- // ─── liquidity ────────────────────────────────────────────────────────────────
504
-
505
- /** Deposit dL/L of every reserve, receive shares ∝ dL. logFloor is untouched by construction. */
506
- export async function fPoolMint(
507
- c: LogswapClient,
508
- /** `maxQuoteIn` is required: the quote leg is Q·dL/L at landing, and Q moves with every swap. */
509
- a: { poolId: Hex; dL: bigint; maxQuoteIn: bigint; account: Address; to?: Address },
510
- ) {
511
- // shares go to `to` (the account by default); on a gated pool `to` must be allowed. `payer` (F 42, decision 107) is the
512
- // account the caller declares as funding the mint, read by `SharesMinted` alone: on this direct call, the sender itself.
513
- return writeFPool(c, a.poolId, "mint", [a.account, a.to ?? a.account, a.dL, a.maxQuoteIn], a.account);
514
- }
515
-
516
- /**
517
- * Burn shares for the pro-rata slice of every reserve. Available at any Q, and after dissolution.
518
- * By owner: the account burns its own shares; an
519
- * operator may pass another owner's address, as on the C manager's `burnById`.
520
- */
521
- export async function fPoolBurn(
522
- c: LogswapClient,
523
- /** `minQuoteOut` is required: the quote slice is Q·shares/S at landing. See {@link fPoolPreviewBurn}. */
524
- a: { poolId: Hex; shares: bigint; minQuoteOut: bigint; account: Address; owner?: Address },
525
- ) {
526
- return writeFPool(c, a.poolId, "burn", [a.owner ?? a.account, a.shares, a.minQuoteOut], a.account);
527
- }
528
-
529
- /**
530
- * What burning `shares` returns at today's state — the manager's own arithmetic: every reserve and
531
- * the quote pro rata, rounded down (FPoolManager.burn). Exact until the next swap or mint.
532
- */
533
- export function fPoolPreviewBurn(st: Pick<FPoolState, "Q" | "reserves" | "totalSupply">, shares: bigint): { quoteOut: bigint; basesOut: bigint[] } {
534
- if (st.totalSupply === 0n) return { quoteOut: 0n, basesOut: st.reserves.map(() => 0n) };
535
- return { quoteOut: (st.Q * shares) / st.totalSupply, basesOut: st.reserves.map((r) => (r * shares) / st.totalSupply) };
536
- }
537
-
538
- /**
539
- * The quote {@link fPoolMint} pulls for `dL` at today's state: Q·dL/L, rounded up (the pool never
540
- * under-collects), before any mint fee — so bound it with {@link withSlippage} (`"input"`).
541
- */
542
- export function fPoolPreviewMintQuote(st: Pick<FPoolState, "Q" | "L">, dL: bigint): bigint {
543
- return st.L === 0n ? 0n : (st.Q * dL + st.L - 1n) / st.L;
544
- }
545
-
546
- // ─── zaps (on the router — one router, one Permit2 spender) ───────────────────
547
-
548
- /**
549
- * Quote needed to zap into exposure `dL`. An UPPER bound: buying each leg raises its mark, so the
550
- * mint consumes less base than was bought for it and every zap ends with a refund. Size from this
551
- * and expect change back — do not treat it as exact.
552
- */
553
- export async function fPoolPreviewZapIn(c: LogswapClient, poolId: Hex, dL: bigint): Promise<bigint> {
554
- // read-only lives on the LENS (LensF: the previews)
555
- const { lensFAbi } = await import("./generated.js");
556
- return c.public.readContract({
557
- address: c.addresses.lensF,
558
- abi: lensFAbi,
559
- functionName: "previewZapIn",
560
- args: [poolId, dL],
561
- } as never) as Promise<bigint>;
562
- }
563
-
564
- /**
565
- * Buy `dL` of the basket with quote alone.
566
- *
567
- * The imbalanced part goes through the pool's own curve before anything is minted. That is not a
568
- * penalty: minting against a quote-only deposit would be a zero-slippage, zero-fee swap at stale
569
- * spot, paid for by the existing LPs. Routing it through
570
- * the curve deletes the subsidy and hands the fee and impact to the incumbents instead.
571
- */
572
- export async function fPoolZapIn(
573
- c: LogswapClient,
574
- a: { poolId: Hex; dL: bigint; maxQuoteIn: bigint; minShares?: bigint; to?: Address; account: Address; deadline?: bigint },
575
- ) {
576
- const to = a.to ?? a.account;
577
- const st = await getFPool(c, a.poolId);
578
- return writeRouter(
579
- c,
580
- "zapIn",
581
- [a.poolId, a.dL, a.maxQuoteIn, a.minShares ?? 0n, to, a.deadline ?? defaultDeadline()],
582
- a.account,
583
- [st.quote],
584
- );
585
- }
586
-
587
- /**
588
- * Sell shares into ONE token — the quote, or any base.
589
- *
590
- * Into a base the other legs route through `swapBaseForBase`, which needs no quote and cannot
591
- * cross the floor; only the burn's own quote slice touches the quote leg. Into the quote every
592
- * base leg is sold, which is the one path a drained quote leg can block.
593
- */
594
- export async function fPoolZapOut(
595
- c: LogswapClient,
596
- /** `minOut` is required: the sale routes every leg through the curve. See {@link fPoolPreviewZapOut}. */
597
- a: { poolId: Hex; shares: bigint; tokenOut: Address; minOut: bigint; to?: Address; account: Address; deadline?: bigint },
598
- ) {
599
- const to = a.to ?? a.account;
600
- return writeRouter(
601
- c,
602
- "zapOut",
603
- [a.poolId, a.shares, a.tokenOut, a.minOut, to, a.deadline ?? defaultDeadline()],
604
- a.account,
605
- );
606
- }
607
-
608
- /**
609
- * What {@link fPoolZapOut} returns at today's state: the router's own `zapOut`, simulated as the
610
- * holder with no bound. Exact, but it needs what the real call needs — the shares, and the router
611
- * as the holder's ERC-6909 operator — so it throws where the zap-out itself would revert.
612
- */
613
- export async function fPoolPreviewZapOut(
614
- c: LogswapClient,
615
- a: { poolId: Hex; shares: bigint; tokenOut: Address; account: Address },
616
- ): Promise<bigint> {
617
- const { result } = await c.public.simulateContract({
618
- address: c.addresses.routerF,
619
- abi: routerFAbi,
620
- functionName: "zapOut",
621
- args: [a.poolId, a.shares, a.tokenOut, 0n, a.account, defaultDeadline()],
622
- account: a.account,
623
- } as never);
624
- return result as bigint;
625
- }
626
-
627
- /**
628
- * Roll a retired generation's bundle into the pool's live one, on the
629
- * router under one lock: redeem `shares` of generation `gen` in place — the legs, the quote and
630
- * any unpulled dividend come back — buy through the pool's own curve only what the live
631
- * generation's ratio lacks, mint `dL` of it to `to`, and refund the rest in kind. Quote the
632
- * bundle does not cover is pulled from the payer, at most `maxQuoteIn`; surplus base is
633
- * refunded, never sold. Size `dL` with {@link fPoolPreviewRollIn}. The router must be the
634
- * caller's ERC-6909 operator ({@link approveRouterForFPool}).
635
- */
636
- export async function fPoolRollIn(
637
- c: LogswapClient,
638
- a: {
639
- poolId: Hex;
640
- /** the retired generation whose shares roll */
641
- gen: bigint | number;
642
- shares: bigint;
643
- dL: bigint;
644
- maxQuoteIn?: bigint;
645
- minShares?: bigint;
646
- to?: Address;
647
- account: Address;
648
- deadline?: bigint;
649
- },
650
- ) {
651
- const to = a.to ?? a.account;
652
- return writeRouter(
653
- c,
654
- "rollIn",
655
- [a.poolId, BigInt(a.gen), a.shares, a.dL, a.maxQuoteIn ?? 0n, a.minShares ?? 0n, to, a.deadline ?? defaultDeadline()],
656
- a.account,
657
- );
658
- }
659
-
660
- /**
661
- * The roll `holder`'s `shares` of retired generation `gen` fund into the live one WITHOUT a
662
- * trade: the largest `dL` the bundle's base covers on every leg, and the quote the bundle is
663
- * short of (pass it as `maxQuoteIn`) or over (refunded — the up direction's distribution) at
664
- * that `dL`. A leg the live generation admitted since makes `dL` zero: such a roll must buy, so
665
- * size it below with `previewZapIn` in mind. Zero for the live generation, or before the next
666
- * seed.
667
- */
668
- export async function fPoolPreviewRollIn(
669
- c: LogswapClient,
670
- poolId: Hex,
671
- gen: bigint | number,
672
- holder: Address,
673
- shares: bigint,
674
- ): Promise<{ dL: bigint; quoteShort: bigint; quoteExcess: bigint }> {
675
- const { lensFAbi } = await import("./generated.js");
676
- const [dL, quoteShort, quoteExcess] = (await c.public.readContract({
677
- address: c.addresses.lensF,
678
- abi: lensFAbi,
679
- functionName: "previewRollIn",
680
- args: [poolId, BigInt(gen), holder, shares],
681
- } as never)) as readonly [bigint, bigint, bigint];
682
- return { dL, quoteShort, quoteExcess };
683
- }
684
-
685
- // ─── the floor lever (the operator's) ─────────────────────────────────────────
686
-
687
- /**
688
- * Harvest (policy.md §9): take this generation's income — `L·(refLogFloor − logFloor)`, the fees since the floor was last
689
- * referenced — and `extra` of capital on top of it, out of the bid; price-neutral, no base moves. Both accrue as a DIVIDEND to
690
- * every share, settled lazily on each holder's next transfer, mint or burn or pulled with {@link fPoolClaim}; the income is taxed
691
- * on the payer's slice (the operator's; 0xdead's on a pad, whose net slice goes to the operator) at the policy's `incomeTaxRate`.
692
- * The operator's own settled dividend — this harvest's and anything pending — is paid to `to` in the same call: one transaction,
693
- * and the operator (usually a contract) routes the payout through `to`. The operator's alone (`NotOperator`). `extra` must fit the
694
- * room ({@link fPoolHarvestRoom}): 0 on a pad (`HarvestLimit`) and under an income-only policy (`IncomeOnly`), within the buffer
695
- * otherwise (`QuoteTooThin`).
696
- */
697
- export async function fPoolHarvest(c: LogswapClient, a: { poolId: Hex; extra?: bigint; to?: Address; account: Address }) {
698
- return writeFPool(c, a.poolId, "harvest", [a.extra ?? 0n, a.to ?? a.account], a.account);
699
- }
700
-
701
- /**
702
- * Pull an owner's settled dividend on a generation's shares without moving them;
703
- * anyone with shares. `gen` defaults to the live generation; a retired generation's harvests
704
- * stay claimable under its own id. By owner (F 42), as {@link fPoolBurn} and {@link fPoolRedeem}: the account claims its
705
- * own, and an ERC-6909 operator may pass another `owner`. Paid to `to` (the account by default).
706
- */
707
- export async function fPoolClaim(c: LogswapClient, a: { poolId: Hex; gen?: bigint | number; owner?: Address; to?: Address; account: Address }) {
708
- const gen = a.gen ?? (await fPoolGen(c, a.poolId));
709
- return writeFPool(c, a.poolId, "claim", [BigInt(gen), a.owner ?? a.account, a.to ?? a.account], a.account);
710
- }
711
-
712
- /**
713
- * A holder's claimable dividend as of now on generation `gen` (the live one by default) — banked
714
- * plus pending on the current balance; under a lien, the free fraction's only: the locked
715
- * fraction's is the lien's ({@link fPoolLienOf}, decisions 063).
716
- */
717
- export async function fPoolDividendOf(c: LogswapClient, poolId: Hex, holder: Address, gen?: bigint | number): Promise<bigint> {
718
- const g = gen ?? (await fPoolGen(c, poolId));
719
- return c.public.readContract({
720
- address: c.addresses.lensF,
721
- abi: lensFAbi,
722
- functionName: "dividendOf",
723
- args: [poolId, BigInt(g), holder],
724
- });
725
- }
726
-
727
- // ─── the lien (decisions 063) ─────────────────────────────────────────────────
728
- // A lending contract — the LOCKER — locks part of an owner's shares in place: no transfer, burn or
729
- // redeem past the free balance. The dividend the locked amount earns is HELD BY THE LIEN, claimable
730
- // by nobody while it stands; lifted, it goes with the lifted part — to the owner on a release (a
731
- // repaid loan gets it back), to the seizer on a seizure. A borrower frozen into a bundle by `close` keeps
732
- // its lien on the old generation's id.
733
-
734
- /** A lien on one share id: the locker, the amount locked, and the dividend the lien holds (banked). */
735
- export interface FPoolLien {
736
- locker: Address;
737
- amount: bigint;
738
- owed: bigint;
739
- }
740
-
741
- /**
742
- * The lien on `owner`'s shares of `poolId`'s generation `gen` (the live one by default). `owed` counts
743
- * what has been banked into it; the locked fraction of the owner's pending since its last bank is
744
- * not yet in it — {@link fPoolBankLien} banks it.
745
- */
746
- export async function fPoolLienOf(c: LogswapClient, poolId: Hex, owner: Address, gen?: bigint | number): Promise<FPoolLien> {
747
- const g = gen ?? (await fPoolGen(c, poolId));
748
- const [locker, amount, owed] = await c.public.readContract({
749
- address: c.addresses.lensF,
750
- abi: lensFAbi,
751
- functionName: "lienOf",
752
- args: [fPoolShareId(poolId, g), owner],
753
- });
754
- return { locker, amount, owed };
755
- }
756
-
757
- /**
758
- * Lock `amount` of `owner`'s shares for the caller, the locker (`account`). Paid with the owner's
759
- * per-id allowance to the locker — the owner first sends `approve(locker, shareId, amount)` on the
760
- * F manager ({@link fPoolApproveShares}) — or an operator grant. One locker per (id, owner) while a
761
- * lien stands. In practice the lending contract calls `lock` itself; this is the EOA path.
762
- */
763
- export async function fPoolLock(c: LogswapClient, a: { poolId: Hex; owner: Address; amount: bigint; gen?: bigint | number; account: Address }) {
764
- const g = a.gen ?? (await fPoolGen(c, a.poolId));
765
- return writeFPool0(c, "lienLock", [fPoolShareId(a.poolId, g), a.owner, a.amount], a.account);
766
- }
767
-
768
- /**
769
- * The locker's `unlock`: `amount` of the lien lifted with its share of the lien's dividend, credited
770
- * to `to` — the owner (a release) or anyone else (a seizure, the shares moving to `to`). It banks
771
- * first. The locker's alone.
772
- */
773
- export async function fPoolUnlock(
774
- c: LogswapClient,
775
- a: { poolId: Hex; owner: Address; amount: bigint; to: Address; gen?: bigint | number; account: Address },
776
- ) {
777
- const g = a.gen ?? (await fPoolGen(c, a.poolId));
778
- return writeFPool0(c, "lienUnlock", [fPoolShareId(a.poolId, g), a.owner, a.amount, a.to], a.account);
779
- }
780
-
781
- /** Bank the owner's pending into the lien now — `unlock(id, owner, 0, owner)`: dividends bank lazily. The locker's. */
782
- export async function fPoolBankLien(c: LogswapClient, a: { poolId: Hex; owner: Address; gen?: bigint | number; account: Address }) {
783
- return fPoolUnlock(c, { ...a, amount: 0n, to: a.owner });
784
- }
785
-
786
- /** The owner's per-id allowance to a locker on the F manager's ERC-6909 shares — what `lock` spends. */
787
- export async function fPoolApproveShares(c: LogswapClient, a: { poolId: Hex; spender: Address; amount: bigint; gen?: bigint | number; account: Address }) {
788
- const g = a.gen ?? (await fPoolGen(c, a.poolId));
789
- return writeFPool0(c, "approve", [a.spender, fPoolShareId(a.poolId, g), a.amount], a.account);
790
- }
791
-
792
- // ─── internals ────────────────────────────────────────────────────────────────
793
-
794
- function defaultDeadline(): bigint {
795
- return BigInt(Math.floor(Date.now() / 1000) + 1800);
796
- }
797
-
798
- function requireWallet(c: LogswapClient) {
799
- if (!c.wallet) throw new Error("logswap: this call needs a wallet client");
800
- return c.wallet;
801
- }
802
-
803
- async function writeFPool(c: LogswapClient, poolId: Hex, functionName: string, args: unknown[], account: Address) {
804
- const wallet = requireWallet(c);
805
- const { request } = await c.public.simulateContract({
806
- address: c.addresses.managerF,
807
- abi: managerFAbi,
808
- functionName,
809
- // Every manager write is keyed by poolId as its FIRST parameter; prepending it here, in the
810
- // one place all seven helpers share, is what keeps a caller from ever omitting it. The `as
811
- // never` casts blind tsc to arg counts, so this file's encode test is the real guard.
812
- args: [poolId, ...args],
813
- account: signerFor(c, account),
814
- } as never);
815
- return wallet.writeContract(request as never);
816
- }
817
-
818
- /** A manager write that is NOT keyed by a poolId — `multicall`. */
819
- async function writeFPool0(c: LogswapClient, functionName: string, args: unknown[], account: Address) {
820
- const wallet = requireWallet(c);
821
- const { request } = await c.public.simulateContract({
822
- address: c.addresses.managerF,
823
- abi: managerFAbi,
824
- functionName,
825
- args,
826
- account: signerFor(c, account),
827
- } as never);
828
- return wallet.writeContract(request as never);
829
- }
830
-
831
- async function writeRouter(
832
- c: LogswapClient,
833
- functionName: string,
834
- args: unknown[],
835
- account: Address,
836
- /** Tokens the call pulls: missing Permit2 allowances are SIGNED and ride in the same tx. */
837
- pullTokens: Address[] = [],
838
- ) {
839
- const wallet = requireWallet(c);
840
- let fn = functionName;
841
- let sendArgs: unknown[] = args;
842
- if (pullTokens.length) {
843
- const { permit2SigCalls } = await import("./onboard.js");
844
- const sigCalls = await permit2SigCalls(c, "F", pullTokens).catch(fallBackUnlessRejected);
845
- if (sigCalls.length) {
846
- const { encodeFunctionData } = await import("viem");
847
- const inner = encodeFunctionData({ abi: routerFAbi, functionName, args } as never);
848
- fn = "multicall";
849
- sendArgs = [[...sigCalls, inner]];
850
- }
851
- }
852
- const { request } = await c.public.simulateContract({
853
- address: c.addresses.routerF,
854
- abi: routerFAbi,
855
- functionName: fn,
856
- args: sendArgs,
857
- account: signerFor(c, account),
858
- } as never);
859
- return wallet.writeContract(request as never);
860
- }
861
-
862
- // ─── token readiness (two pull paths, not one) ────────────────────────────────
863
- //
864
- // The F screens have TWO spenders to satisfy, and confusing them was a shipped bug. Direct
865
- // manager calls (swaps, mint, burn) pull with plain `transferFrom`, so the MANAGER needs an
866
- // ERC-20 allowance. The router's zaps pull through Permit2 when the deployment carries one, so a
867
- // plain approval to the router does nothing there and the zap reverts `NotAllowed()` — that leg
868
- // is `onboardToken`'s job. This helper covers the manager leg; a UI needs both.
869
-
870
- /** Plain ERC-20 approval to the F manager — the allowance every DIRECT call pulls against. */
871
- export async function approveTokenForFPoolManager(c: LogswapClient, token: Address): Promise<Hash> {
872
- const wallet = requireWallet(c);
873
- return c.wallet!.writeContract({
874
- address: token,
875
- abi: [{ type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "s", type: "address" }, { name: "a", type: "uint256" }], outputs: [{ type: "bool" }] }],
876
- functionName: "approve",
877
- args: [c.addresses.managerF, (1n << 256n) - 1n],
878
- account: wallet.account,
879
- chain: c.wallet!.chain,
880
- } as never);
881
- }
882
-
883
- /** Does `owner` have enough allowance on `token` for the MANAGER to pull `need`? */
884
- export async function fPoolManagerAllowanceOk(c: LogswapClient, token: Address, owner: Address, need: bigint): Promise<boolean> {
885
- const allowance = (await c.public.readContract({
886
- address: token,
887
- abi: [{ type: "function", name: "allowance", stateMutability: "view", inputs: [{ name: "o", type: "address" }, { name: "s", type: "address" }], outputs: [{ type: "uint256" }] }],
888
- functionName: "allowance",
889
- args: [owner, c.addresses.managerF],
890
- } as never)) as bigint;
891
- return allowance >= need;
892
- }
893
-
894
- // ─── ERC-6909 operator (zapOut needs it) ──────────────────────────────────────
895
- //
896
- // The singleton's shares are ERC-6909, so the router cannot `transferFrom` them the way it could
897
- // an ERC-20 LP token. The holder approves it once as an operator. This is the one place the move
898
- // off a per-pool ERC-20 costs a user-visible step, so the SDK names it rather than letting the
899
- // first `fPoolZapOut` revert with something unreadable.
900
-
901
- export async function isRouterOperatorForFPool(c: LogswapClient, owner: Address): Promise<boolean> {
902
- return c.public.readContract({
903
- address: c.addresses.managerF,
904
- abi: managerFAbi,
905
- functionName: "isOperator",
906
- args: [owner, c.addresses.routerF],
907
- } as never) as Promise<boolean>;
908
- }
909
-
910
- /** Approve the router to move this account's F-pool shares. Needed once, before any `fPoolZapOut`. */
911
- export async function approveRouterForFPool(c: LogswapClient, account: Address) {
912
- const wallet = requireWallet(c);
913
- const { request } = await c.public.simulateContract({
914
- address: c.addresses.managerF,
915
- abi: managerFAbi,
916
- functionName: "setOperator",
917
- args: [c.addresses.routerF, true],
918
- account: signerFor(c, account),
919
- } as never);
920
- return wallet.writeContract(request as never);
921
- }
922
-
923
- // ─── ids ──────────────────────────────────────────────────────────────────────
924
- //
925
- // One ERC-6909 space, split structurally on bit 255 — the C manager's scheme. Derived here rather
926
- // than read from the chain: it is pure, and a client that has to call to learn an id cannot build
927
- // a multicall that uses it.
928
-
929
- /**
930
- * The ERC-6909 id carrying generation `gen` of a pool's shares: bit 255 set (the
931
- * share flag), the pool id's top 239 bits, the generation in the low 16. Each generation's shares
932
- * are their own asset — a retired one is a claim on its bundle, the live one on the pool.
933
- */
934
- export function fPoolShareId(poolId: Hex, gen: bigint | number = 0n): bigint {
935
- return (1n << 255n) | ((BigInt(poolId) >> 17n) << 16n) | BigInt(gen);
936
- }
937
-
938
- /** The generation a share id carries — its low 16 bits. */
939
- export function fPoolGenOfShareId(id: bigint): number {
940
- return Number(id & 0xffffn);
941
- }
942
-
943
- /** The pool's live generation, one read. */
944
- export async function fPoolGen(c: LogswapClient, poolId: Hex): Promise<number> {
945
- return Number((await rawFPool(c, poolId)).gen);
946
- }
947
-
948
- /** The ERC-6909 id carrying claims on a token. Bit 255 clear, so it can never meet a share id. */
949
- export function fPoolClaimId(token: Address): bigint {
950
- return BigInt(token);
951
- }
952
-
953
- /** A holder's shares of generation `gen` — the live one by default. */
954
- export async function fPoolShareBalance(c: LogswapClient, poolId: Hex, owner: Address, gen?: bigint | number): Promise<bigint> {
955
- const g = gen ?? (await fPoolGen(c, poolId));
956
- return c.public.readContract({
957
- address: c.addresses.managerF,
958
- abi: managerFAbi,
959
- functionName: "balanceOf",
960
- args: [owner, fPoolShareId(poolId, g)],
961
- } as never) as Promise<bigint>;
962
- }
963
-
964
- /** A retired generation's bundle: what is left to redeem — supply, quote, base per leg index. */
965
- export async function fPoolBundleOf(
966
- c: LogswapClient,
967
- poolId: Hex,
968
- gen: bigint | number,
969
- ): Promise<{ supply: bigint; quote: bigint; base: bigint[] }> {
970
- const [supply, quote, base] = await c.public.readContract({
971
- address: c.addresses.lensF,
972
- abi: lensFAbi,
973
- functionName: "bundleOf",
974
- args: [poolId, BigInt(gen)],
975
- });
976
- return { supply, quote, base: [...base] };
977
- }
978
-
979
- /** A holder's claim on one retired generation, as the lens reports it: what `redeem` pays now. */
980
- export interface FPoolClaimRow {
981
- gen: number;
982
- shares: bigint;
983
- base: bigint[];
984
- quote: bigint;
985
- dividend: bigint;
986
- }
987
-
988
- /** A holder's claims on a pool's retired generations — one row per generation still held. */
989
- export async function fPoolClaimsOf(c: LogswapClient, poolId: Hex, owner: Address): Promise<FPoolClaimRow[]> {
990
- const { lensFAbi } = await import("./generated.js");
991
- const rows = (await c.public.readContract({
992
- address: c.addresses.lensF,
993
- abi: lensFAbi,
994
- functionName: "claimsOf",
995
- args: [poolId, owner],
996
- } as never)) as readonly { gen: bigint; shares: bigint; base: readonly bigint[]; quote: bigint; dividend: bigint }[];
997
- return rows.map((r) => ({ gen: Number(r.gen), shares: r.shares, base: [...r.base], quote: r.quote, dividend: r.dividend }));
998
- }
999
-
1000
- /**
1001
- * Redeem `shares` of a RETIRED generation: its bundle, pro rata — the base per
1002
- * leg and the quote — plus the owner's settled dividend. Not `burn`: nothing can move a bundle's
1003
- * ratio, so there is no slippage to bound. The owner, or an operator of theirs.
1004
- */
1005
- export async function fPoolRedeem(
1006
- c: LogswapClient,
1007
- a: { poolId: Hex; gen: bigint | number; shares: bigint; owner?: Address; account: Address },
1008
- ) {
1009
- return writeFPool(c, a.poolId, "redeem", [BigInt(a.gen), a.owner ?? a.account, a.shares], a.account);
1010
- }
1011
-
1012
- export async function fPoolClaimBalance(c: LogswapClient, token: Address, owner: Address): Promise<bigint> {
1013
- return c.public.readContract({
1014
- address: c.addresses.managerF,
1015
- abi: managerFAbi,
1016
- functionName: "balanceOf",
1017
- args: [owner, fPoolClaimId(token)],
1018
- } as never) as Promise<bigint>;
1019
- }
1020
-
1021
- // ─── the quoter ───────────────────────────────────────────────────────────────
1022
-
1023
- export enum FPoolQuoteKind {
1024
- QuoteIn = 0,
1025
- BaseIn = 1,
1026
- BaseForBase = 2,
1027
- }
1028
-
1029
- /**
1030
- * An EXACT quote — what execution returns, not an estimate.
1031
- *
1032
- * `quoteSwap` runs the real swap and reverts with the answer, so the value has to be decoded out
1033
- * of the revert rather than returned. That is the point of the pattern: there is no second pricing
1034
- * path to drift from the first. It needs no tokens, no approvals and no balance, so it works from
1035
- * a disconnected wallet — unlike `fPoolPreviewZapIn`, which is a genuine upper bound.
1036
- */
1037
- export async function fPoolQuoteSwap(
1038
- c: LogswapClient,
1039
- a: { poolId: Hex; kind: FPoolQuoteKind; j: number; k?: number; amountIn: bigint; taker?: Address },
1040
- ): Promise<bigint> {
1041
- try {
1042
- await c.public.simulateContract({
1043
- address: c.addresses.routerF,
1044
- abi: routerFAbi,
1045
- functionName: "quoteSwap",
1046
- // the taker matters only on a gated pool: the connected account, or the zero address
1047
- args: [a.poolId, a.kind, BigInt(a.j), BigInt(a.k ?? 0), a.amountIn, a.taker ?? c.wallet?.account?.address ?? ZERO_ADDRESS],
1048
- } as never);
1049
- } catch (err) {
1050
- const hit = findQuoteResult(err);
1051
- if (hit !== null) return hit;
1052
- throw err; // a real revert — the floor stop, a bad leg — belongs to the caller
1053
- }
1054
- throw new Error("logswap: quoteSwap returned without reverting, which it must never do");
1055
- }
1056
-
1057
-
1058
- // ─── the pool lifecycle (creation to dissolution) ─────────────────────────────
1059
- //
1060
- // Everything here is MANAGER-DIRECT by design: creation and governance are one-time,
1061
- // authority-gated acts with no pull to route and no slippage to bound, so the router adds
1062
- // nothing and its 128 bytes of EIP-170 margin are not spent on them.
1063
-
1064
- export interface FPoolCreateArgs {
1065
- quote: Address;
1066
- /** The pool's assets, in any order; sorted into the key's canonical order before the call. The set is fixed for the pool's life. */
1067
- bases: Address[];
1068
- /** The swap fee as its index into {@link F_FEE_LIST} (policy.md §6); the mint fee is the list's next entry, nothing to choose. One of this or `swapFee`. */
1069
- swapFeeIdx?: number;
1070
- /** The swap fee, WAD — one of the list's eight values ({@link fFeeIndexOf} throws otherwise); the index is what the key carries. */
1071
- swapFee?: bigint;
1072
- /**
1073
- * Which of the deployment's policies the key names when `policy` is not given ({@link fPoolPolicyFor}). NOT a key
1074
- * field (decisions 049: the manager knows no kind): the policy is, and its terms say what it is ({@link FPoolKind}).
1075
- */
1076
- kind: FPolicySlot;
1077
- /**
1078
- * The pool's policy for life: the contract the key names, approved by the registry (`PolicyNotApproved`). Defaults to the
1079
- * deployment's policy for `kind`. An open policy admits anyone; a closed one its authority alone (`Refused`). The policy's
1080
- * authority is the pool's operator at birth: the one account that then funds it ({@link fPoolDeploy}).
1081
- */
1082
- policy?: Address;
1083
- /**
1084
- * The differentiator, and nothing else. Identity is the key's hash, so a sponsor cannot run two pools of the same shape
1085
- * without varying it — the second `initialize` would land on the first pool's id. Zero under an open policy (`NotCanonical`):
1086
- * one public pool per shape and swap fee. Defaults to zero. A pool's NAME is not this: names are events on the policy
1087
- * ({@link fPoolSetName}), so a rename forks nothing.
1088
- */
1089
- salt?: Hex;
1090
- account: Address;
1091
- }
1092
-
1093
- const ZERO_SALT = `0x${"0".repeat(64)}` as const;
1094
-
1095
- // ─── the fee list (policy.md §6) ──────────────────────────────────────────────
1096
-
1097
- /** `FeeParams.FEE_LIST` in bp: the eight swap fees an F pool may be born with. The key carries the index. */
1098
- export const F_FEE_LIST_BP = FEE_LIST_BP;
1099
- /** The list in WAD (1 bp = 1e14). No zero: the fee-free pool cannot be born. */
1100
- export const F_FEE_LIST: readonly bigint[] = FEE_LIST;
1101
-
1102
- /** The fee at `idx` of the list, WAD. Throws off the list. */
1103
- export function fFeeOf(idx: number): bigint {
1104
- const fee = Number.isInteger(idx) ? F_FEE_LIST[idx] : undefined;
1105
- if (fee === undefined) throw new Error(`logswap: swap fee index ${idx} is off the F fee list (0..${F_FEE_LIST.length - 1})`);
1106
- return fee;
1107
- }
1108
-
1109
- /** The mint fee's index for a swap fee's: the next entry, the same at the top (`FeeParams.mintIdx`). Every pair has `mintFee ≥ 2·swapFee` but the top's (200 → 200 bp). */
1110
- export function fMintFeeIdxOf(swapFeeIdx: number): number {
1111
- fFeeOf(swapFeeIdx);
1112
- return Math.min(swapFeeIdx + 1, F_FEE_LIST.length - 1);
1113
- }
1114
-
1115
- /** The mint fee, WAD of newly-minted L, a pool born at `swapFeeIdx` charges on outside mints. */
1116
- export function fMintFeeOf(swapFeeIdx: number): bigint {
1117
- return fFeeOf(fMintFeeIdxOf(swapFeeIdx));
1118
- }
1119
-
1120
- /** The list index of a WAD fee. Throws when the fee is not one of the eight: no F pool can be born at it. */
1121
- export function fFeeIndexOf(fee: bigint): number {
1122
- const idx = F_FEE_LIST.indexOf(fee);
1123
- if (idx < 0) throw new Error(`logswap: swap fee ${fee} is not on the F fee list (${F_FEE_LIST_BP.join(", ")} bp)`);
1124
- return idx;
1125
- }
1126
-
1127
- /** Whether a policy's `feeMask` admits `idx`: a bit per index, an empty mask admitting all eight. */
1128
- export function fFeeListed(feeMask: number, idx: number): boolean {
1129
- return Number.isInteger(idx) && idx >= 0 && idx < F_FEE_LIST.length && (feeMask === 0 || ((feeMask >> idx) & 1) === 1);
1130
- }
1131
-
1132
- /** The indices a policy's `feeMask` admits, ascending. */
1133
- export function fFeesAllowed(feeMask: number): number[] {
1134
- return F_FEE_LIST.map((_, i) => i).filter((i) => fFeeListed(feeMask, i));
1135
- }
1136
-
1137
- /** The swap fee index of create arguments given either way; both given must agree. */
1138
- export function fPoolSwapFeeIdxOf(a: { swapFeeIdx?: number; swapFee?: bigint }): number {
1139
- if (a.swapFeeIdx !== undefined) {
1140
- const fee = fFeeOf(a.swapFeeIdx);
1141
- if (a.swapFee !== undefined && a.swapFee !== fee) throw new Error(`logswap: swap fee ${a.swapFee} is not the F fee list's entry ${a.swapFeeIdx} (${fee})`);
1142
- return a.swapFeeIdx;
1143
- }
1144
- if (a.swapFee !== undefined) return fFeeIndexOf(a.swapFee);
1145
- throw new Error("logswap: an F pool needs its swap fee — `swapFeeIdx` (into the list) or `swapFee` (WAD, on the list)");
1146
- }
1147
-
1148
- /** `bytes32` ⇄ short UTF-8 text, for the pool and sponsor labels. */
1149
- export function textToBytes32(text: string): Hex {
1150
- const b = new TextEncoder().encode(text);
1151
- if (b.length > 31) throw new Error(`logswap: "${text}" is ${b.length} bytes; a label holds 31`);
1152
- const out = new Uint8Array(32);
1153
- out.set(b);
1154
- return `0x${Array.from(out, (x) => x.toString(16).padStart(2, "0")).join("")}` as Hex;
1155
- }
1156
- export function bytes32ToText(word: Hex): string {
1157
- if (!word) return ""; // a manager older than the field answers with nothing at all
1158
- const bytes = (word.slice(2).match(/../g) ?? []).map((h) => parseInt(h, 16));
1159
- const end = bytes.findIndex((x) => x === 0);
1160
- return new TextDecoder().decode(new Uint8Array(end === -1 ? bytes : bytes.slice(0, end)));
1161
- }
1162
-
1163
- /** Sort legs by base address (the key's canonical order), carrying companion arrays along. */
1164
- export function sortFPoolLegs<T>(bases: Address[], ...companions: T[][]): { bases: Address[]; companions: T[][] } {
1165
- const idx = bases.map((_, i) => i).sort((a, b) => (bases[a]!.toLowerCase() < bases[b]!.toLowerCase() ? -1 : 1));
1166
- return { bases: idx.map((i) => bases[i]!), companions: companions.map((arr) => idx.map((i) => arr[i]!)) };
1167
- }
1168
-
1169
- /**
1170
- * The tuple an F pool's id hashes — `src/types/PoolKeyF.sol`, field order load-bearing (it is the ABI encoding order).
1171
- * Stored by the manager at `initialize` and never in calldata again. No creator, no mint fee, no weights and no cap
1172
- * (policy.md §5): both fees follow from `swapFeeIdx`, the book belongs to a generation's `deployLiquidity`.
1173
- */
1174
- export interface FPoolKey {
1175
- quote: Address;
1176
- /** Sorted ascending, unique, 1..8; fixed for the pool's life. */
1177
- bases: Address[];
1178
- /** Into {@link F_FEE_LIST}; the mint fee is the next entry ({@link fMintFeeIdxOf}). */
1179
- swapFeeIdx: number;
1180
- /** The pool's policy for life. */
1181
- policy: Address;
1182
- /** Zero under an open policy. */
1183
- salt: Hex;
1184
- }
1185
-
1186
- /** The key's ABI as `abi.encode(key)` lays it out: what {@link fPoolIdOfKey} hashes. */
1187
- export const F_POOL_KEY_ABI = [
1188
- {
1189
- type: "tuple",
1190
- components: [
1191
- { name: "quote", type: "address" },
1192
- { name: "bases", type: "address[]" },
1193
- { name: "swapFeeIdx", type: "uint8" },
1194
- { name: "policy", type: "address" },
1195
- { name: "salt", type: "bytes32" },
1196
- ],
1197
- },
1198
- ] as const;
1199
-
1200
- /**
1201
- * An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
1202
- * manager's `idOf` getter was cut in F version 21; this is the same hash (checked against Foundry's encoder in the
1203
- * tests). The key must be the one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them).
1204
- */
1205
- export function fPoolIdOfKey(key: FPoolKey): Hex {
1206
- return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
1207
- }
1208
-
1209
- /** The key as the manager hashes it: bases sorted, the fee as its index, the slot's policy filled in when none is named. No kind in it (049). */
1210
- export function fPoolKeyOf(c: LogswapClient, a: Omit<FPoolCreateArgs, "account">): FPoolKey {
1211
- const { bases } = sortFPoolLegs(a.bases);
1212
- return { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy ?? fPoolPolicyFor(c, a.kind), salt: a.salt ?? ZERO_SALT };
1213
- }
1214
-
1215
- /**
1216
- * List the pool — `initialize(key)` (policy.md §9): no funds move; the pool is inactive until its operator funds it
1217
- * ({@link fPoolDeploy}). Anyone under an open policy (salt zero), the policy's authority alone under a closed one
1218
- * (`Refused`); refused past the policy's sunset (`PolicyNotApproved`), off the policy's fee mask (`FeeNotListed`), quote or
1219
- * base list (`QuoteNotListed`, `BaseNotListed`), or with more legs than it allows (`TooManyLegs`). Returns the tx hash;
1220
- * read the id with {@link fPoolIdOf}.
1221
- */
1222
- export async function fPoolInitialize(c: LogswapClient, a: FPoolCreateArgs) {
1223
- const key = fPoolKeyOf(c, a);
1224
- const wallet = requireWallet(c);
1225
- const { request } = await c.public.simulateContract({
1226
- address: c.addresses.managerF,
1227
- abi: managerFAbi,
1228
- functionName: "initialize",
1229
- args: [key],
1230
- account: wallet.account,
1231
- } as never);
1232
- return c.wallet!.writeContract(request as never);
1233
- }
1234
-
1235
- /**
1236
- * The pool id is the key's hash — pure, so it can be read before or after creation. Computed
1237
- * locally since F version 21 ({@link fPoolIdOfKey}; the manager's `idOf` is gone): no RPC. Still
1238
- * async, so callers written against the read keep working.
1239
- */
1240
- export async function fPoolIdOf(c: LogswapClient, a: Omit<FPoolCreateArgs, "account">): Promise<Hex> {
1241
- return fPoolIdOfKey(fPoolKeyOf(c, a));
1242
- }
1243
-
1244
- /**
1245
- * Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field, the salt included (F 41). The result
1246
- * is checked against the id.
1247
- */
1248
- export async function fPoolKeyOfPool(c: LogswapClient, poolId: Hex, opts: { fromBlock?: bigint; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. */ indexer?: string } = {}): Promise<FPoolKey> {
1249
- type Ev = Extract<(typeof managerFAbi)[number], { type: "event"; name: "PoolCreated" }>;
1250
- const ev = managerFAbi.find((x): x is Ev => x.type === "event" && x.name === "PoolCreated")!;
1251
- const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev as never, args: { poolId }, fromBlock: opts.fromBlock });
1252
- const l = logs[0];
1253
- if (!l) throw new Error(`logswap: no PoolCreated for F pool ${poolId}`);
1254
- const a = l.args as unknown as { quote: Address; policy: Address; bases: readonly Address[]; swapFeeIdx: number | bigint; salt: Hex };
1255
- const key: FPoolKey = { quote: a.quote, bases: [...a.bases], swapFeeIdx: Number(a.swapFeeIdx), policy: a.policy, salt: a.salt };
1256
- if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase()) {
1257
- throw new Error(`logswap: the PoolCreated log of F pool ${poolId} does not hash to it — a wrong manager, or a log from before F 41`);
1258
- }
1259
- return key;
1260
- }
1261
-
1262
- /**
1263
- * The reserve a leg holds at a mark: `R = Lj·e^{−x}`, WAD math. A deployment names the TOTAL base
1264
- * reserve and the price that values it, and the price follows from the pair, `p = Lj / R` — so this is
1265
- * the one conversion from a wanted mark to what the pool will hold, done here, on the way in. Float
1266
- * precision (~1e-16 relative) is what a deployment needs: any reserve is legal, and the mark
1267
- * the pool derives from it is the one the sponsor meant to within that.
1268
- */
1269
- export function fPoolReserveAt(Lj: bigint, x: bigint, k = 0): bigint {
1270
- // on a capped pool (decisions 061) the mark reads the virtual reserve R̃ = R + c, and the
1271
- // deployment puts c = R·k/(1 − k): so the REAL reserve for a mark is L_j·e^{−x}·(1 − k)
1272
- const e = Math.exp(-Number(x) / 1e18) * (1 - k);
1273
- return (Lj * BigInt(Math.round(e * 1e18))) / 10n ** 18n;
1274
- }
1275
-
1276
- /**
1277
- * The cap constant k = e^{−lnCapOverSeed} (decisions 061, 075): every leg's phantom is c_j = r_j·k/(1 − k), and the
1278
- * generation's liquidity is its base value over 1 − k. 0 on an uncapped pool. It no longer depends on the bid:
1279
- * the cap is a ratio of the cap price to each asset's own seed price.
1280
- */
1281
- export function fPoolCapK(lnCapOverSeed: number): number {
1282
- return lnCapOverSeed === 0 ? 0 : Math.exp(-lnCapOverSeed / 1e6);
1283
- }
1284
-
1285
- /**
1286
- * The pool's `lnCapOverSeed` = ln(cap price / seed price) (1e-6 log units) for a leverage λ: ln(λ/(λ − 1))
1287
- * (decisions 061), so λ = 1/(1 − seed/cap) = L / (base value) and the cap sits λ/(λ − 1) × the seed price — λ = 2
1288
- * puts it at twice. **λ = 1 is uncapped**: cap ∞, `lnCapOverSeed` 0. A λ under 1, or one so close to
1289
- * 1 (or so large) that d leaves a uint24 of 1e-6 units, is refused.
1290
- */
1291
- export function fPoolCapOfLeverage(lambda: number): number {
1292
- if (lambda === 1) return 0;
1293
- if (!(lambda > 1) || !Number.isFinite(lambda)) throw new Error(`logswap: leverage must be 1 (uncapped) or a finite number above 1, got ${lambda}`);
1294
- const d = Math.round(Math.log(lambda / (lambda - 1)) * 1e6);
1295
- if (d < 1 || d > 0xffffff) throw new Error(`logswap: leverage ${lambda} needs a cap outside a uint24 of 1e-6 units`);
1296
- return d;
1297
- }
1298
-
1299
- /** The leverage λ = 1/(1 − e^{−x}) for x = `lnCapOverSeed` (1e-6 log units); 1 for an uncapped pool (cap ∞). */
1300
- export function fPoolLeverageOfCap(lnCapOverSeed: number): number {
1301
- return lnCapOverSeed === 0 ? 1 : 1 / (1 - Math.exp(-lnCapOverSeed / 1e6));
1302
- }
1303
-
1304
- /** A pool's leverage, ready to tag: `capped` false and `capOverSeed` Infinity for an uncapped pool. */
1305
- export interface FPoolLeverage {
1306
- /** λ at the seed; exactly 1 when uncapped. */
1307
- lambda: number;
1308
- capped: boolean;
1309
- /** The cap's price over the seed's, e^d = λ/(λ − 1): 2 at λ = 2; Infinity when uncapped. */
1310
- capOverSeed: number;
1311
- /** "1×" uncapped; otherwise λ to two decimals, trailing zeros dropped ("2×", "1.5×"), never "1×" for a capped pool ("1.01×" at least shown as "≈1×"). */
1312
- label: string;
1313
- }
1314
-
1315
- /**
1316
- * The leverage tag of a pool from its `lnCapOverSeed` (decisions 061): `1×` means no cap — the only way a tag
1317
- * reads 1× — and a capped pool always reads above it, so the two can never be confused on screen.
1318
- */
1319
- export function fPoolLeverage(lnCapOverSeed: number): FPoolLeverage {
1320
- if (lnCapOverSeed === 0) return { lambda: 1, capped: false, capOverSeed: Infinity, label: "1×" };
1321
- const lambda = fPoolLeverageOfCap(lnCapOverSeed);
1322
- const rounded = Math.round(lambda * 100) / 100;
1323
- const label = rounded <= 1 ? "≈1×" : `${String(rounded)}×`;
1324
- return { lambda, capped: true, capOverSeed: Math.exp(lnCapOverSeed / 1e6), label };
1325
- }
1326
-
1327
- /** The `lnCapOverSeed` from deployment args: as given, else from `leverage`, else 0 (uncapped, cap ∞). Both given and disagreeing is refused. */
1328
- export function fPoolCapOfArgs(a: { lnCapOverSeed?: number; leverage?: number }): number {
1329
- const fromLeverage = a.leverage === undefined ? undefined : fPoolCapOfLeverage(a.leverage);
1330
- if (a.lnCapOverSeed !== undefined && fromLeverage !== undefined && a.lnCapOverSeed !== fromLeverage)
1331
- throw new Error(`logswap: lnCapOverSeed ${a.lnCapOverSeed} and leverage ${a.leverage} (${fromLeverage}) disagree — pass one`);
1332
- return a.lnCapOverSeed ?? fromLeverage ?? 0;
1333
- }
1334
-
1335
- /**
1336
- * One entry of `deployLiquidity`'s input (F 38, decision 084): the TOTAL base reserve the asset has after the call
1337
- * (0 leaves it out) and the price that values it, quote atomic units per base atomic unit, 1e36-scaled.
1338
- */
1339
- export interface BaseAsset {
1340
- base: Address;
1341
- amount: bigint;
1342
- priceX36: bigint;
1343
- }
1344
-
1345
- /** The book a deployment names, from the sponsor's terms: weights, total liquidity `L0`, and either the wanted marks `x0` or the reserves `r0`. */
1346
- export type FPoolBookSpec = {
1347
- /** The pool's assets, in any order; the result is sorted into the key's order. */
1348
- bases: Address[];
1349
- /** WAD, one per asset, summing to 1e18; 0 leaves the asset out (not in generation 0). `L_j = w_j · L0`. */
1350
- weights: bigint[];
1351
- /** The book's total liquidity, quote units. */
1352
- L0: bigint;
1353
- /** The pool's one cap, or the leverage it stands for; absent is uncapped. */
1354
- lnCapOverSeed?: number;
1355
- leverage?: number;
1356
- } & ({ x0: bigint[] } | { r0: bigint[] });
1357
-
1358
- /**
1359
- * The `baseAssets` (and cap) a deployment sends for a wanted book — what the old seed did with reserves and
1360
- * marks, as the amounts and prices the manager takes now. Per asset: the reserve `r_j` (given as `r0`, or
1361
- * {@link fPoolReserveAt} the wanted mark `x0`) and the price that makes its value `L_j · (1 − k)`:
1362
- * `priceX36 = ceil(L_j(1 − k) · 1e36 / r_j)`. A zero weight is an asset left out. Sorted by base address, the
1363
- * key's order, with the companions carried along.
1364
- */
1365
- export function fPoolBook(a: FPoolBookSpec): { baseAssets: BaseAsset[]; lnCapOverSeed: number } {
1366
- const sum = a.weights.reduce((x, y) => x + y, 0n);
1367
- if (sum !== WAD) throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
1368
- if (a.weights.length !== a.bases.length) throw new Error(`logswap: ${a.weights.length} weights for ${a.bases.length} assets`);
1369
- const lnCapOverSeed = fPoolCapOfArgs(a);
1370
- const k = fPoolCapK(lnCapOverSeed);
1371
- const oneMinusK = BigInt(Math.round((1 - k) * 1e18));
1372
- const rows = a.bases.map((base, j): BaseAsset => {
1373
- const w = a.weights[j]!;
1374
- if (w === 0n) return { base, amount: 0n, priceX36: 0n };
1375
- const Lj = (w * a.L0) / WAD;
1376
- const amount = "r0" in a ? a.r0[j]! : fPoolReserveAt(Lj, a.x0[j]!, k);
1377
- if (amount === 0n) throw new Error(`logswap: asset ${base} has weight ${w} but a zero reserve`);
1378
- const value = (Lj * oneMinusK) / WAD;
1379
- return { base, amount, priceX36: (value * 10n ** 36n + amount - 1n) / amount };
1380
- });
1381
- const { companions } = sortFPoolLegs(a.bases, rows);
1382
- return { baseAssets: companions[0]!, lnCapOverSeed };
1383
- }
1384
-
1385
- /**
1386
- * The allocation a `deployLiquidity` book implies: asset `j`'s value `amount_j · priceX36_j / 1e36` over the sum,
1387
- * normalized as the manager does it (cumulative shares, floored), so the weights sum to exactly 1e18. A zero-value
1388
- * book has no allocation (`[]`). What an indexer derives from `LiquidityDeployed` instead of reading the weights.
1389
- */
1390
- export function fPoolBookWeights(baseAssets: readonly BaseAsset[]): bigint[] {
1391
- const values = baseAssets.map((x) => (x.amount * x.priceX36) / 10n ** 36n);
1392
- const total = values.reduce((x, y) => x + y, 0n);
1393
- if (total === 0n) return [];
1394
- let cumulative = 0n;
1395
- let previous = 0n;
1396
- return values.map((v) => {
1397
- cumulative += v;
1398
- const next = (cumulative * WAD) / total;
1399
- const w = next - previous;
1400
- previous = next;
1401
- return w;
1402
- });
1403
- }
1404
-
1405
- /**
1406
- * The book's total liquidity `L` from a `LiquidityDeployed` input: the values' sum over `1 − k`, `k = e^{−cap}`.
1407
- * Exact when uncapped; with a cap it carries the float error of `k` (~1e-16 relative) — read the pool for the wei.
1408
- */
1409
- export function fPoolBookL(baseAssets: readonly BaseAsset[], lnCapOverSeed: number): bigint {
1410
- const total = baseAssets.reduce((x, a) => x + (a.amount * a.priceX36) / 10n ** 36n, 0n);
1411
- if (lnCapOverSeed === 0) return total;
1412
- const oneMinusK = BigInt(Math.round((1 - fPoolCapK(lnCapOverSeed)) * 1e18));
1413
- return (total * WAD) / oneMinusK;
1414
- }
1415
-
1416
- /**
1417
- * Put liquidity into the pool, the authority's: `deployLiquidity` (F 38, decisions 083, 084). It SETS THE BOOK:
1418
- * `baseAssets[j].amount` is the total base reserve of asset `j` after the call (0 removes it), `quoteAmount` the
1419
- * total bid, and the manager settles each figure against what the pool holds — a larger total is pulled from the
1420
- * caller, a smaller one pushed to `to` — so one call can replace an asset by another. Pass the book outright
1421
- * (`baseAssets`, `lnCapOverSeed`) or the sponsor's terms ({@link fPoolBook}: `weights`, `L0` and marks `x0` or
1422
- * reserves `r0`, in any order). On an UNFUNDED pool (new, or after {@link fPoolClose}) it funds the first or the next
1423
- * generation. On a LIVE pool it is a regeneration that sets the book: income settles to `to`, the policy picks the
1424
- * carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
1425
- * carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
1426
- */
1427
- /**
1428
- * Fund the pool — `deployLiquidity(poolId, baseAssets, quoteAmount, lnCapOverSeed)` (policy.md §9): the book of this generation,
1429
- * on an INACTIVE pool — listed and never funded, or closed (`PoolActive` otherwise). The operator's alone (`NotOperator`): it pays
1430
- * every leg's amount and `quoteAmount` by plain allowance to the manager ({@link approveTokenForFPoolManager}) and holds the shares —
1431
- * all but `MIN_SHARES`, which go to 0xdead; every share does on a pad. Refused past the policy's sunset (`PolicyNotApproved`),
1432
- * under its buffer (`QuoteTooThin`), with a cap under its `lnCapMin` (`CapTooClose`). An amount of 0 leaves a leg dormant. Pass the
1433
- * book raw (`baseAssets` + `lnCapOverSeed`) or as a {@link FPoolBookSpec}.
1434
- */
1435
- export async function fPoolDeploy(
1436
- c: LogswapClient,
1437
- a: { poolId: Hex; quoteAmount: bigint; account: Address } & ({ baseAssets: BaseAsset[]; lnCapOverSeed: number } | FPoolBookSpec),
1438
- ) {
1439
- const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
1440
- return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed], a.account);
1441
- }
1442
-
1443
- /**
1444
- * Close the pool (policy.md §9) — at any bid. The manager harvests the income first (a dividend to every share, the operator's
1445
- * paid to `to`), freezes every reserve and the bid into generation `gen`'s bundle — every share of it redeems pro rata
1446
- * ({@link fPoolRedeem}), forever — and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens under
1447
- * the same id, policy, roles and gates. The operator's alone. Throws before sending on a pad: a pad never closes
1448
- * (`PadNeverCloses`). Pass `flags` when in hand to save the read.
1449
- */
1450
- export async function fPoolClose(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address; flags?: number }) {
1451
- const flags = a.flags ?? (await getFPool(c, a.poolId)).flags;
1452
- if ((flags & SEED_TO_DEAD) !== 0) throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
1453
- return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
1454
- }
1455
-
1456
- /**
1457
- * The relaunch's calls — what `regenerate` was (policy.md §9): `close(poolId, to)`, `redeem(poolId, gen, operator, shares)` for the
1458
- * operator's own shares of the generation closed (left out at 0), then `deployLiquidity` with the next book. Pure, so a form can show
1459
- * what it is about to send; {@link fPoolRelaunch} sends them as one `multicall`.
1460
- */
1461
- export function fPoolRelaunchCalls(
1462
- a: { poolId: Hex; gen: number | bigint; shares: bigint; quoteAmount: bigint; to?: Address; account: Address } & (
1463
- | { baseAssets: BaseAsset[]; lnCapOverSeed: number }
1464
- | FPoolBookSpec
1465
- ),
1466
- ): Hex[] {
1467
- const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
1468
- const enc = (functionName: string, args: unknown[]) => encodeFunctionData({ abi: managerFAbi, functionName, args } as never) as Hex;
1469
- const calls = [enc("close", [a.poolId, a.to ?? a.account])];
1470
- if (a.shares > 0n) calls.push(enc("redeem", [a.poolId, BigInt(a.gen), a.account, a.shares]));
1471
- calls.push(enc("deployLiquidity", [a.poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
1472
- return calls;
1473
- }
1474
-
1475
- /**
1476
- * Relaunch the pool as ONE transaction: close generation `gen`, redeem the operator's own shares of it (its funds come back),
1477
- * fund `gen + 1` with the book given — the manager's `multicall`, the operator as sender. Every other holder is frozen into the
1478
- * bundle and redeems it ({@link fPoolRedeem}); the new book may re-weight any of the key's bases and pick its own cap. The
1479
- * deploy pulls its amounts and `quoteAmount` from the operator in the same transaction the redeem pays it, so the allowances
1480
- * must cover the pull. Not on a pad (a pad never closes); not on an inactive pool (fund it with {@link fPoolDeploy}).
1481
- */
1482
- export async function fPoolRelaunch(
1483
- c: LogswapClient,
1484
- a: { poolId: Hex; quoteAmount: bigint; to?: Address; account: Address } & ({ baseAssets: BaseAsset[]; lnCapOverSeed: number } | FPoolBookSpec),
1485
- ) {
1486
- const s = await getFPool(c, a.poolId);
1487
- if ((s.flags & SEED_TO_DEAD) !== 0) throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
1488
- if (!s.seeded) throw new Error("logswap: the pool is inactive — nothing to close; fund it with fPoolDeploy");
1489
- const shares = await fPoolShareBalance(c, a.poolId, a.account, s.gen);
1490
- return writeFPool0(c, "multicall", [fPoolRelaunchCalls({ ...a, gen: s.gen, shares })], a.account);
1491
- }
1492
-
1493
- /** Where a pad's seed lives: `deployLiquidity` mints every share of a pad here itself. */
1494
- export const DEAD_ADDRESS: Address = "0x000000000000000000000000000000000000dEaD";
1495
- /** The manager's `MIN_SHARES`: the deploy mints this much to 0xdead on every pool, the rest to the operator — or, on a pad, to 0xdead too. */
1496
- export const F_MIN_SHARES = 1000n;
1497
-
1498
- /**
1499
- * One genesis transaction: a swap the creator sends right after the seed, inside the launch's
1500
- * `multicall`. A `buy` spends `amountIn` of quote for leg `j` (an index into `bases` AS GIVEN); a
1501
- * `sell` spends `amountIn` of that leg for quote. The creator pays and is paid — the manager settles
1502
- * to its sender — so a `recipient` is paid by an ERC-20 transfer of the row's output
1503
- * ({@link fPoolGenesisTransfers}); without one the output stays with the creator.
1504
- */
1505
- export interface FPoolGenesisRow {
1506
- side: "buy" | "sell";
1507
- j: number;
1508
- amountIn: bigint;
1509
- /** Defaults to 0. With a `recipient`, {@link fPoolLaunch} pins it to the simulated output, which is what the transfer pays. */
1510
- minOut?: bigint;
1511
- recipient?: Address;
1512
- }
1513
-
1514
- /** An ERC-20 transfer owed to a genesis recipient: one per (token, recipient), rows summed. */
1515
- export interface FPoolGenesisTransfer {
1516
- token: Address;
1517
- to: Address;
1518
- amount: bigint;
1519
- }
1520
-
1521
- export interface FPoolLaunchArgs extends Omit<FPoolCreateArgs, "account"> {
1522
- /** WAD, one per asset (in `bases` order), summing to 1e18; `L_j = w_j · L0`. The generation's allocation (F 38: not in the key). */
1523
- weights: bigint[];
1524
- /** The generation's total liquidity, quote units. */
1525
- L0: bigint;
1526
- /** The pool's one cap as ln(cap price / seed price), 1e-6 log units, or the leverage it stands for; absent is uncapped. A pad is always uncapped (`PadUncapped`). */
1527
- lnCapOverSeed?: number;
1528
- leverage?: number;
1529
- /** The bid the deployment pulls (`quoteAmount`). A pad deploys at 0 — pure float, a resting ask, nothing raised. */
1530
- quoteAmount: bigint;
1531
- /**
1532
- * An opening buy of leg `j` (an index into `bases` AS GIVEN) for `amountIn` of quote, ON THE
1533
- * MANAGER — the same sender, a plain allowance to the manager, the router nowhere near it. A
1534
- * pad seeds at Q = 0, so until someone trades it the mark sits at p₀; buying inside the launch
1535
- * gives it a price that has moved and a buffer under it. Nothing can trade between the seed and
1536
- * this buy — they are one transaction — so `minOut` is safe at its default of 0.
1537
- */
1538
- openBuy?: { j: number; amountIn: bigint; minOut?: bigint };
1539
- /**
1540
- * The genesis transactions: an ordered list of swaps right after the seed, each with an optional
1541
- * recipient ({@link FPoolGenesisRow}). The same batch as `openBuy`, which stays as the one-buy
1542
- * case and runs first when both are given. See `specs/f-pools/opening.md`.
1543
- */
1544
- openBatch?: FPoolGenesisRow[];
1545
- /**
1546
- * How a row's recipient is paid. `auto` (default): in the launch's own transaction when the
1547
- * wallet batches atomically (EIP-5792), else left to {@link fPoolSendGenesisTransfers};
1548
- * `followup`: always left to it. Ignored when no row names a recipient.
1549
- */
1550
- deliver?: "auto" | "followup";
1551
- /** The pool's label (≤ 31 bytes of UTF-8) — a `NameSet` event on the policy, the operator's (049), written right after the batch by {@link fPoolLaunch}; not in the batch. */
1552
- name?: string;
1553
- /**
1554
- * The pool already exists (a previous launch got as far as `initialize` and no further — a seed
1555
- * that reverted, a closed tab, before the launch was one transaction), so `initialize` is left
1556
- * out: the key is a pure function of the arguments and a second `initialize` can only revert.
1557
- */
1558
- initialized?: boolean;
1559
- /** Anything else, pre-encoded against {@link managerFAbi}, appended after the above. */
1560
- extra?: Hex[];
1561
- account: Address;
1562
- }
1563
-
1564
- /**
1565
- * The launch's calls, in order — the batch {@link fPoolLaunch} sends. Pure, so a form can show
1566
- * what it is about to send, and a test can decode it. Legs are sorted here with their weights and
1567
- * reserves (the key's canonical order; `openBuy.j` is re-indexed to match), and the weights are
1568
- * checked here, where the message is readable.
1569
- */
1570
- export function fPoolLaunchCalls(
1571
- poolId: Hex,
1572
- a: FPoolLaunchArgs & ({ r0: bigint[] } | { x0: bigint[] }),
1573
- ): Hex[] {
1574
- if (!a.policy) throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
1575
- const { baseAssets, lnCapOverSeed } = fPoolBook(a);
1576
- const bases = baseAssets.map((x) => x.base);
1577
- const key: FPoolKey = { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy, salt: a.salt ?? ZERO_SALT };
1578
- const enc = (functionName: string, args: unknown[]) =>
1579
- encodeFunctionData({ abi: managerFAbi, functionName, args } as never) as Hex;
1580
- const calls: Hex[] = [];
1581
- if (!a.initialized) calls.push(enc("initialize", [key]));
1582
- calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
1583
- // gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the closed pool.
1584
- // No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
1585
- for (const row of fPoolGenesisRows(a)) {
1586
- const j = bases.indexOf(a.bases[row.j]!);
1587
- if (j < 0) throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
1588
- calls.push(enc(row.side === "buy" ? "swapQuoteIn" : "swapBaseIn", [poolId, BigInt(j), row.amountIn, row.minOut ?? 0n, a.account]));
1589
- }
1590
- // the name and the gate modes are the POLICY's, not the manager's: they cannot ride in this batch — `fPoolLaunch`
1591
- // sends the name right after, as the same operator; the modes are `fPoolSetSwapMode` / `fPoolSetMintMode`
1592
- calls.push(...(a.extra ?? []));
1593
- return calls;
1594
- }
1595
-
1596
- /** The genesis rows in the order they run: `openBuy` first when given, then `openBatch`. Legs as given. */
1597
- export function fPoolGenesisRows(a: Pick<FPoolLaunchArgs, "openBuy" | "openBatch">): FPoolGenesisRow[] {
1598
- return [...(a.openBuy ? [{ side: "buy" as const, ...a.openBuy }] : []), ...(a.openBatch ?? [])];
1599
- }
1600
-
1601
- /**
1602
- * What each genesis row returned, read by simulating the launch's `multicall` on the chain — the
1603
- * contract's own rounding, no re-implementation. Exact at send time: the pool is new, and nothing
1604
- * can trade between the seed and the rows. Needs the creator's funds and allowances, as the launch
1605
- * does. One output per row, in {@link fPoolGenesisRows} order: base for a buy, quote for a sell.
1606
- */
1607
- export async function fPoolGenesisOutputs(
1608
- c: LogswapClient,
1609
- poolId: Hex,
1610
- a: FPoolLaunchArgs & ({ r0: bigint[] } | { x0: bigint[] }),
1611
- ): Promise<bigint[]> {
1612
- const rows = fPoolGenesisRows(a);
1613
- if (rows.length === 0) return [];
1614
- const calls = fPoolLaunchCalls(poolId, a);
1615
- const { result } = await c.public.simulateContract({
1616
- address: c.addresses.managerF,
1617
- abi: managerFAbi,
1618
- functionName: "multicall",
1619
- args: [calls],
1620
- account: signerFor(c, a.account),
1621
- } as never);
1622
- const results = result as readonly Hex[];
1623
- const first = (a.initialized ? 0 : 1) + 1; // [initialize] · deployLiquidity · rows
1624
- return rows.map((_, i) => decodeAbiParameters([{ type: "uint256" }], results[first + i]!)[0] as bigint);
1625
- }
1626
-
1627
- /**
1628
- * The transfers that pay the recipients: each row's output (`outs`, aligned with
1629
- * {@link fPoolGenesisRows}) to its `recipient`, summed per (token, recipient), zero amounts dropped.
1630
- * The token is the leg's base for a buy and the quote for a sell. Pure.
1631
- */
1632
- export function fPoolGenesisTransfers(
1633
- a: Pick<FPoolLaunchArgs, "quote" | "bases" | "openBuy" | "openBatch">,
1634
- outs: bigint[],
1635
- ): FPoolGenesisTransfer[] {
1636
- const out = new Map<string, FPoolGenesisTransfer>();
1637
- fPoolGenesisRows(a).forEach((row, i) => {
1638
- if (!row.recipient || !outs[i]) return;
1639
- const token = row.side === "buy" ? a.bases[row.j]! : a.quote;
1640
- const k = `${token.toLowerCase()}:${row.recipient.toLowerCase()}`;
1641
- const t = out.get(k);
1642
- if (t) t.amount += outs[i]!;
1643
- else out.set(k, { token, to: row.recipient, amount: outs[i]! });
1644
- });
1645
- return [...out.values()];
1646
- }
1647
-
1648
- /** Pay genesis recipients with plain ERC-20 transfers, one transaction each, in order. For a launch that did not deliver itself. */
1649
- export async function fPoolSendGenesisTransfers(c: LogswapClient, a: { transfers: FPoolGenesisTransfer[]; account: Address }): Promise<Hash[]> {
1650
- const wallet = requireWallet(c);
1651
- const hashes: Hash[] = [];
1652
- for (const t of a.transfers) {
1653
- const { request } = await c.public.simulateContract({
1654
- address: t.token,
1655
- abi: erc20Abi,
1656
- functionName: "transfer",
1657
- args: [t.to, t.amount],
1658
- account: signerFor(c, a.account),
1659
- } as never);
1660
- hashes.push(await wallet.writeContract(request as never));
1661
- }
1662
- return hashes;
1663
- }
1664
-
1665
- /** Whether the wallet runs a batch of calls atomically (EIP-5792 `atomic` capability), on the client's chain. A wallet without it, or one that errors, says no. */
1666
- export async function fPoolWalletBatchesAtomically(c: LogswapClient, account: Address): Promise<boolean> {
1667
- try {
1668
- const wallet = requireWallet(c);
1669
- const chainId = wallet.chain?.id;
1670
- const caps = (await wallet.getCapabilities({ account, chainId })) as { atomic?: { status?: string } };
1671
- return caps?.atomic?.status === "supported" || caps?.atomic?.status === "ready";
1672
- } catch {
1673
- return false;
1674
- }
1675
- }
1676
-
1677
- /**
1678
- * Create a pool as ONE transaction: `initialize`, `deployLiquidity`, the opening buys — the manager's `multicall`, one sender
1679
- * throughout. Either every call lands or none does; there is no half-built pool to resume. The sender must be the policy's
1680
- * AUTHORITY: it is the pool's operator at birth, and `deployLiquidity` is the operator's (`NotOperator`). Under an open
1681
- * policy anyone may list a pool ({@link fPoolInitialize}) but only the LOG — its authority — funds it, so a launch under the
1682
- * public policy is the LOG's; a sponsor launches under its own policy.
1683
- *
1684
- * Why the manager and not the router: every one of these entries authenticates by `msg.sender`. Routed, the router would be
1685
- * the sender — the operator, the holder of the seed shares. `multicall` is delegatecall-to-self, so the sender survives.
1686
- *
1687
- * What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base, `quoteAmount` of quote, plus
1688
- * each opening buy's `amountIn` of quote. Grant those first — one `approve` per token, once ever
1689
- * ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
1690
- *
1691
- * Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}). The name, when given, is a second transaction on
1692
- * the policy ({@link fPoolSetName}); the gate modes are {@link fPoolSetSwapMode} / {@link fPoolSetMintMode} after it.
1693
- */
1694
- export async function fPoolLaunch(
1695
- c: LogswapClient,
1696
- a: FPoolLaunchArgs & ({ r0: bigint[] } | { x0: bigint[] }),
1697
- ): Promise<{ hash: Hash; poolId: Hex; transfers: FPoolGenesisTransfer[]; delivered: boolean }> {
1698
- const poolId = await fPoolIdOf(c, a);
1699
- const policy = a.policy ?? fPoolPolicyFor(c, a.kind);
1700
- let args = { ...a, policy };
1701
- // With recipients, each row's minOut is pinned to its simulated output and the transfers pay
1702
- // exactly that: a row that returns less reverts the launch, a wei of surplus stays with the creator.
1703
- let transfers: FPoolGenesisTransfer[] = [];
1704
- const rows = fPoolGenesisRows(a);
1705
- if (rows.some((r) => r.recipient)) {
1706
- const outs = await fPoolGenesisOutputs(c, poolId, args);
1707
- args = { ...args, openBuy: undefined, openBatch: rows.map((r, i) => ({ ...r, minOut: outs[i]! })) };
1708
- transfers = fPoolGenesisTransfers(args, outs);
1709
- }
1710
- const calls = fPoolLaunchCalls(poolId, args);
1711
- let hash: Hash;
1712
- let delivered = transfers.length === 0;
1713
- if (transfers.length > 0 && a.deliver !== "followup" && (await fPoolWalletBatchesAtomically(c, a.account))) {
1714
- const wallet = requireWallet(c);
1715
- const { id } = await wallet.sendCalls({
1716
- account: signerFor(c, a.account),
1717
- forceAtomic: true,
1718
- calls: [
1719
- { to: c.addresses.managerF, data: encodeFunctionData({ abi: managerFAbi, functionName: "multicall", args: [calls] } as never) },
1720
- ...transfers.map((t) => ({ to: t.token, data: encodeFunctionData({ abi: erc20Abi, functionName: "transfer", args: [t.to, t.amount] }) })),
1721
- ],
1722
- } as never);
1723
- const status = await wallet.waitForCallsStatus({ id });
1724
- const receipt = status.receipts?.[0];
1725
- if (status.status !== "success" || !receipt) throw new Error("logswap: the launch batch did not succeed — nothing was created");
1726
- hash = receipt.transactionHash;
1727
- delivered = true;
1728
- } else {
1729
- hash = await writeFPool0(c, "multicall", [calls], a.account);
1730
- }
1731
- if (a.name) await fPoolSetName(c, { poolId, name: a.name, account: a.account, policy });
1732
- return { hash, poolId, transfers, delivered };
1733
- }
1734
-
1735
- // ─── the roles, on the policy ─────────────────────────────────────────────
1736
- //
1737
- // Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy` may be passed when in
1738
- // hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once. The policy syncs the manager itself
1739
- // (`setGates`), which stamps the block: no swap lands in the block of a change (047). Every mode and list write reverts
1740
- // `GatesUnavailable` on an open policy: a public pool can never be gated.
1741
-
1742
- /** A write on a policy. */
1743
- async function writePolicy(c: LogswapClient, policy: Address, functionName: string, args: unknown[], account: Address) {
1744
- const wallet = requireWallet(c);
1745
- const { request } = await c.public.simulateContract({ address: policy, abi: policyFAbi, functionName, args, account: signerFor(c, account) } as never);
1746
- return wallet.writeContract(request as never);
1747
- }
1748
-
1749
- /** A write keyed by poolId, on the pool's policy. */
1750
- async function writePoolPolicy(c: LogswapClient, a: { poolId: Hex; policy?: Address; account: Address }, functionName: string, args: unknown[]) {
1751
- const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
1752
- return writePolicy(c, policy, functionName, [a.poolId, ...args], a.account);
1753
- }
1754
-
1755
- /**
1756
- * Appoint the pool's operator (the AUTHORITY's; zero resets it to the authority): the account that funds, harvests, closes and sets the
1757
- * pool's modes and name, admitted by the gates with no policy call. Immediate, with no acceptance step, so check the address; it may be
1758
- * a contract (an executor). `InactivePool` on a pool the policy never held.
1759
- */
1760
- export async function fPoolAppointOperator(c: LogswapClient, a: { poolId: Hex; operator: Address; account: Address; policy?: Address }) {
1761
- return writePoolPolicy(c, a, "appointOperator", [a.operator]);
1762
- }
1763
-
1764
- /**
1765
- * Set the pool's swap gate (the OPERATOR's): `open`, `listed` (the policy's swap list, {@link fPolicySetRights}; the operator always
1766
- * passes) or `operator`. The mint mode must stay at least as restrictive (`ModeOrder`). `burn`, `redeem` and `claim` are never gated.
1767
- */
1768
- export async function fPoolSetSwapMode(c: LogswapClient, a: { poolId: Hex; mode: FPoolMode; account: Address; policy?: Address }) {
1769
- return writePoolPolicy(c, a, "setSwapMode", [MODES.indexOf(a.mode)]);
1770
- }
1771
-
1772
- /** Set the pool's mint gate (the OPERATOR's): at least as restrictive as the swap mode (`ModeOrder`); `listed` consults the policy's mint list. */
1773
- export async function fPoolSetMintMode(c: LogswapClient, a: { poolId: Hex; mode: FPoolMode; account: Address; policy?: Address }) {
1774
- return writePoolPolicy(c, a, "setMintMode", [MODES.indexOf(a.mode)]);
1775
- }
1776
-
1777
- /** The bits of `PolicyF.rights`: listed for swaps; listed for mints, which implies swaps. */
1778
- export const RIGHT_SWAP = 1;
1779
- export const RIGHT_MINT = 2;
1780
- /** What a policy lists an address for: nothing, swaps, or mints (and so swaps). */
1781
- export type FPolicyRight = "none" | "swap" | "mint";
1782
-
1783
- /** The on-chain bits of a right (`MINT` is written as `MINT | SWAP`, as the policy does). */
1784
- export function fPolicyRightBits(right: FPolicyRight): number {
1785
- return right === "none" ? 0 : right === "swap" ? RIGHT_SWAP : RIGHT_SWAP | RIGHT_MINT;
1786
- }
1787
-
1788
- /** The right the bits spell. */
1789
- export function fPolicyRightOf(bits: number | bigint): FPolicyRight {
1790
- const b = Number(bits);
1791
- return (b & RIGHT_MINT) !== 0 ? "mint" : (b & RIGHT_SWAP) !== 0 ? "swap" : "none";
1792
- }
1793
-
1794
- /**
1795
- * List addresses on the POLICY (the AUTHORITY's): `swap` admits them where a pool's swap mode is `listed`, `mint` where its mint mode is
1796
- * — and to swap as well (`MINT ⇒ SWAP`); `none` unlists. One pair of lists per policy, shared by every pool under it (policy.md §4.2);
1797
- * the modes are each pool's. Stamps nothing: an address removed in a block can still swap in that block.
1798
- */
1799
- export async function fPolicySetRights(c: LogswapClient, a: { policy: Address; who: readonly Address[]; right: FPolicyRight; account: Address }) {
1800
- return writePolicy(c, a.policy, "setRights", [a.who, fPolicyRightBits(a.right)], a.account);
1801
- }
1802
-
1803
- /** What `policy` lists `who` for now (`rights`). */
1804
- export async function fPolicyRightsOf(c: LogswapClient, policy: Address, who: Address): Promise<FPolicyRight> {
1805
- return fPolicyRightOf((await c.public.readContract({ address: policy, abi: policyFAbi, functionName: "rights", args: [who] } as never)) as number | bigint);
1806
- }
1807
-
1808
- /** Label the pool (the OPERATOR's): a `NameSet` event on the policy, nothing stored — mutable, never identity. At most 31 bytes of UTF-8. */
1809
- export async function fPoolSetName(c: LogswapClient, a: { poolId: Hex; name: string; account: Address; policy?: Address }) {
1810
- return writePoolPolicy(c, a, "setName", [textToBytes32(a.name)]);
1811
- }
1812
-
1813
- /**
1814
- * What the PROTOCOL says an address is — "Keyrock" — on the REGISTRY. Only its
1815
- * owner, the LOG authority, may write it, which is what makes it an attestation rather than a
1816
- * claim anyone could make about themselves.
1817
- */
1818
- export async function fPoolSetSponsorName(c: LogswapClient, a: { who: Address; name: string; account: Address }) {
1819
- const wallet = requireWallet(c);
1820
- const registry = await registryAddress(c);
1821
- const { request } = await c.public.simulateContract({
1822
- address: registry,
1823
- abi: policyRegistryAbi,
1824
- functionName: "setSponsorName",
1825
- args: [a.who, textToBytes32(a.name)],
1826
- account: signerFor(c, a.account),
1827
- } as never);
1828
- return wallet.writeContract(request as never);
1829
- }
1830
-
1831
- /** The protocol's attestation for an address, or "" when unattested — which most addresses are, and every address on a deployment with no registry. */
1832
- export async function fPoolSponsorName(c: LogswapClient, who: Address): Promise<string> {
1833
- const registry = c.addresses.policyRegistry ?? (await fPoolRegistryOf(c));
1834
- if (registry === ZERO_ADDRESS) return "";
1835
- const word = (await c.public.readContract({ address: registry, abi: policyRegistryAbi, functionName: "sponsorName", args: [who] } as never)) as Hex;
1836
- return bytes32ToText(word);
1837
- }
1838
-
1839
- /** The registry the manager asks at every birth — `addresses.policyRegistry`, else the manager's word; zero on a bare deployment. */
1840
- export async function fPoolRegistryOf(c: LogswapClient): Promise<Address> {
1841
- if (c.addresses.policyRegistry) return c.addresses.policyRegistry;
1842
- return (await c.public.readContract({ address: c.addresses.managerF, abi: managerFAbi, functionName: "registry" } as never)) as Address;
1843
- }
1844
-
1845
- async function registryAddress(c: LogswapClient): Promise<Address> {
1846
- const registry = await fPoolRegistryOf(c);
1847
- if (registry === ZERO_ADDRESS) throw new Error("logswap: this deployment carries no policy registry");
1848
- return registry;
1849
- }
1850
-
1851
- /** Who runs the pool (policy.md §2): its operator — the one account the manager admits to fund, harvest and close. Empty on a pool the policy never held. */
1852
- export function fPoolRunners(s: Pick<FPoolRoles, "operator">): Address[] {
1853
- return s.operator === ZERO_ADDRESS ? [] : [s.operator];
1854
- }
1855
-
1856
- /**
1857
- * Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
1858
- * Burning to the dead address is a sponsor's way to make its liquidity permanent: the shares can
1859
- * never be redeemed.
1860
- */
1861
- export async function fPoolTransferShares(
1862
- c: LogswapClient,
1863
- a: { poolId: Hex; to: Address; shares: bigint; account: Address; gen?: bigint | number },
1864
- ) {
1865
- const wallet = requireWallet(c);
1866
- const gen = a.gen ?? (await fPoolGen(c, a.poolId));
1867
- const { request } = await c.public.simulateContract({
1868
- address: c.addresses.managerF,
1869
- abi: managerFAbi,
1870
- functionName: "transfer",
1871
- args: [a.to, fPoolShareId(a.poolId, gen), a.shares],
1872
- account: signerFor(c, a.account),
1873
- } as never);
1874
- return wallet.writeContract(request as never);
1875
- }
1876
-
1877
- // ─── discovery from the log stream ────────────────────────────────────────────
1878
-
1879
- export interface DiscoveredFPool {
1880
- poolId: Hex;
1881
- quote: Address;
1882
- bases: Address[];
1883
- /** The generation-0 allocation, from the pool's first `LiquidityDeployed` ({@link fPoolBookWeights}); `[]` until it is deployed — F 38 keeps no weights in the key. */
1884
- weights: bigint[];
1885
- /** The key's swap fee index (policy.md §6). */
1886
- swapFeeIdx: number;
1887
- /** The swap fee, WAD: `F_FEE_LIST[swapFeeIdx]`. */
1888
- swapFee: bigint;
1889
- /** The mint fee, WAD: the list's next entry ({@link fMintFeeOf}). */
1890
- mintFee: bigint;
1891
- /** The generation-0 cap as ln(cap price / seed price), in 1e-6 log units; 0 uncapped, cap ∞ (decisions 061); 0 until deployed. */
1892
- lnCapOverSeed: number;
1893
- kind: FPoolKind;
1894
- /** The pool's policy for life — the contract the key names. */
1895
- policy: Address;
1896
- /** The key's salt: zero under an open policy. */
1897
- salt: Hex;
1898
- /** The account that created the pool (`PoolCreated.creator`, F 42): the one the policy judged. Not a key field. */
1899
- creator: Address;
1900
- /** The block the pool was initialized in — its age, for annualising realized income. */
1901
- block: bigint;
1902
- /** Whether `deployLiquidity` has run; an unfunded pool has no floor and no float, so nothing to show. */
1903
- seeded: boolean;
1904
- /** The quote the pool was born with. Zero is the launchpad's signature. */
1905
- q0: bigint;
1906
- /**
1907
- * The PRODUCT the pool is, by the spec's definition rather than a guess: a LAUNCH is one asset
1908
- * born at Q = 0 — a resting ask under a token, nothing raised, the creator alone on the lever;
1909
- * everything else is a liquidity BASKET (public, quote-funded). Read from the Seeded log, so a
1910
- * one-asset pool seeded WITH quote files correctly as liquidity, not as a pad.
1911
- */
1912
- shape: FPoolShape;
1913
- }
1914
-
1915
- /**
1916
- * Every F pool ever created, from `PoolCreated` logs alone — plus the terms of each distinct policy, read once and cached.
1917
- * Possible only because the event carries the full key (quote, policy, bases, swapFeeIdx, salt) and the creator — the poolId is a hash and
1918
- * could never be inverted; contracts PR #17 exists for exactly this call. With `indexer`, the logs come from it (the node
1919
- * when it fails): a scan from block 0 per call is what made the first load wait on the node.
1920
- */
1921
- export async function discoverFPools(
1922
- c: LogswapClient,
1923
- opts: { fromBlock?: bigint; toBlock?: bigint; indexer?: string } = {},
1924
- ): Promise<DiscoveredFPool[]> {
1925
- type Ev = Extract<(typeof managerFAbi)[number], { type: "event"; name: "PoolCreated" }>;
1926
- const ev = managerFAbi.find((x): x is Ev => x.type === "event" && x.name === "PoolCreated");
1927
- if (!ev) throw new Error("logswap: F PoolCreated event missing from the generated ABI");
1928
- type DeployEv = Extract<(typeof managerFAbi)[number], { type: "event"; name: "LiquidityDeployed" }>;
1929
- const deployEv = managerFAbi.find((x): x is DeployEv => x.type === "event" && x.name === "LiquidityDeployed");
1930
- const range = { indexer: opts.indexer, address: c.addresses.managerF, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
1931
- const [{ logs }, { logs: deploys }] = await Promise.all([
1932
- getEventLogs(c, { ...range, event: ev }),
1933
- deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
1934
- ]);
1935
- // the pool's first deployment (generation 0) names its allocation, cap and opening bid
1936
- const first = new Map<string, { weights: bigint[]; lnCapOverSeed: number; q0: bigint }>();
1937
- for (const l of deploys) {
1938
- const a = l.args as { poolId: Hex; gen: bigint | number; quoteAmount: bigint; baseAssets: readonly BaseAsset[]; lnCapOverSeed: number | bigint };
1939
- if (BigInt(a.gen) !== 0n) continue;
1940
- first.set(a.poolId.toLowerCase(), { weights: fPoolBookWeights(a.baseAssets), lnCapOverSeed: Number(a.lnCapOverSeed), q0: a.quoteAmount });
1941
- }
1942
- return Promise.all(
1943
- logs.map(async (l) => {
1944
- const a = l.args as { poolId: Hex; quote: Address; creator: Address; policy: Address; bases: readonly Address[]; swapFeeIdx: number | bigint; salt: Hex };
1945
- const g0 = first.get(a.poolId.toLowerCase());
1946
- const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
1947
- const swapFeeIdx = Number(a.swapFeeIdx);
1948
- return {
1949
- poolId: a.poolId,
1950
- quote: a.quote,
1951
- bases: [...a.bases],
1952
- weights: g0?.weights ?? [],
1953
- swapFeeIdx,
1954
- swapFee: fFeeOf(swapFeeIdx),
1955
- mintFee: fMintFeeOf(swapFeeIdx),
1956
- lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
1957
- kind,
1958
- policy: a.policy,
1959
- salt: a.salt,
1960
- creator: a.creator,
1961
- block: l.blockNumber,
1962
- seeded: g0 !== undefined,
1963
- q0: g0?.q0 ?? 0n,
1964
- shape: kind === "pad" ? "launch": "basket", // the policy's word, not n = 1: a mono POL is a pool
1965
- };
1966
- }),
1967
- );
1968
- }
1969
-
1970
- // ─── the policy page: what an account runs ────────────────────────
1971
- //
1972
- // One policy serves every pool under it, so "the pools I run" is not a policy's list: it is every pool whose policy answers
1973
- // `operator(poolId) == me` — and, for a sponsor, every pool under a policy whose `authority()` is me. Discovery from the log
1974
- // stream (or the indexer), then the roles per pool on its policy — viem multicalls them.
1975
-
1976
- /** A pool an account runs or sponsors, with what the policy page shows of it. */
1977
- export interface FPoolControlled {
1978
- pool: DiscoveredFPool;
1979
- roles: FPoolRoles;
1980
- state: FPoolState;
1981
- /** The policy's immutables: the terms a holder reads before entering. */
1982
- terms: FPolicyTerms;
1983
- }
1984
-
1985
- /**
1986
- * Every F pool `who` runs (its operator) or sponsors (the authority of its policy) — the policy page's list. `roles` tells
1987
- * which. `pools` may be passed (from the indexer, say) to skip the log scan.
1988
- */
1989
- export async function fPoolsControlledBy(
1990
- c: LogswapClient,
1991
- who: Address,
1992
- opts: { pools?: DiscoveredFPool[]; fromBlock?: bigint } = {},
1993
- ): Promise<FPoolControlled[]> {
1994
- const pools = opts.pools ?? (await discoverFPools(c, { fromBlock: opts.fromBlock }));
1995
- const states = await Promise.all(pools.map((p) => getFPool(c, p.poolId)));
1996
- const roles = await Promise.all(states.map((s) => getFPoolRoles(c, s.poolId, s)));
1997
- const me = who.toLowerCase();
1998
- const out: FPoolControlled[] = [];
1999
- for (let i = 0; i < pools.length; ++i) {
2000
- const r = roles[i]!;
2001
- if (r.operator.toLowerCase() !== me && r.authority.toLowerCase() !== me) continue;
2002
- const state = states[i]!;
2003
- out.push({ pool: pools[i]!, roles: r, state, terms: await fPolicyTermsOf(c, state.policy) });
2004
- }
2005
- return out;
2006
- }
2007
-
2008
-
2009
- /**
2010
- * Every holder of a pool's shares, from the ERC-6909 Transfer stream — the id is an indexed
2011
- * topic, so one filtered log query aggregates the whole ledger. The 0xdead entry is the
2012
- * MIN_SHARES lock from seeding; callers usually label rather than hide it. Pass `indexer`: the Transfer rows come from
2013
- * its tables — a node prunes its logs (anvil keeps about a day), and a ledger rebuilt from a pruned stream loses every
2014
- * holder minted before the cut. (The indexer's derived views are read by the app's `@logswap/base`, not here.)
2015
- */
2016
- export async function fPoolShareHolders(
2017
- c: LogswapClient,
2018
- poolIdHex: Hex,
2019
- opts: { fromBlock?: bigint; gen?: bigint | number; indexer?: string } = {},
2020
- ): Promise<Array<{ holder: Address; shares: bigint }>> {
2021
- type Ev = Extract<(typeof managerFAbi)[number], { type: "event"; name: "Transfer" }>;
2022
- const ev = managerFAbi.find((x): x is Ev => x.type === "event" && x.name === "Transfer");
2023
- if (!ev) throw new Error("logswap: 6909 Transfer event missing from the generated ABI");
2024
- const gen = opts.gen ?? (await fPoolGen(c, poolIdHex));
2025
- const id = fPoolShareId(poolIdHex, gen);
2026
- const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev, args: { id }, fromBlock: opts.fromBlock });
2027
- const bal = new Map<string, bigint>();
2028
- for (const l of logs) {
2029
- const a = l.args as { from: Address; to: Address; amount: bigint };
2030
- if (a.from !== "0x0000000000000000000000000000000000000000") bal.set(a.from, (bal.get(a.from) ?? 0n) - a.amount);
2031
- if (a.to !== "0x0000000000000000000000000000000000000000") bal.set(a.to, (bal.get(a.to) ?? 0n) + a.amount);
2032
- }
2033
- return [...bal.entries()]
2034
- .filter(([, v]) => v > 0n)
2035
- .map(([holder, shares]) => ({ holder: holder as Address, shares }))
2036
- .sort((a, b) => (b.shares > a.shares ? 1 : -1));
2037
- }
2038
-
2039
- /** Every F pool's raw state in one lens call (the manager's `Pool` struct: quote, swapFee, restructureTime, flags, policy, seeded, gen, n, lnCapOverSeed, Q, realizedVariance, L, shares, refLogFloor, operator, mintFee). */
2040
- export async function getFPoolsRaw(c: LogswapClient, poolIds: Hex[]): Promise<readonly unknown[]> {
2041
- const { lensFAbi } = await import("./generated.js");
2042
- return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "getPools", args: [poolIds] } as never)) as readonly unknown[];
2043
- }
2044
-
2045
- /** Share value from the lens — (L + Q)/shares, WAD per share — the same figure as `fPoolShareValue`, from one source. */
2046
- export async function shareValueOnChain(c: LogswapClient, poolId: Hex): Promise<bigint> {
2047
- const { lensFAbi } = await import("./generated.js");
2048
- return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "shareValue", args: [poolId] } as never)) as bigint;
2049
- }