@logswap/sdk 0.5.91 → 0.5.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/fpool.ts CHANGED
@@ -18,14 +18,16 @@
18
18
  * and release) — and nothing in the maths. `describeFPool` below reports
19
19
  * which shape a given pool is, because a UI has to decide what to render.
20
20
  *
21
- * **The roles are the policy's, not the manager's** (F version 15). The manager holds no
22
- * authority, gate or list: it asks the pool's policy `may(who, action)` and acts on the answer (the
23
- * one thing it caches is the operator the gates admit with no call, F 40). So `getFPool` carries the
24
- * policy and what it declared (`flags`), {@link getFPoolRoles} reads the roles FROM the policy, and
25
- * every setting — the operator, the gate modes, the whitelist — is a write to the policy
26
- * ({@link fPoolAppointOperator}, {@link fPoolSetSwapMode}, {@link fPoolSetListed}, …). Since decision 098
27
- * the authority is `key.creator` for life (no handover) and a policy has no setter of its own: its numbers
28
- * are constructor immutables, and a change is a new policy the LOG moves a pool to ({@link fPoolMigrate}).
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.
29
31
  *
30
32
  * **Zaps live on the ROUTER, not here.** `RouterF` is F's own router and its own Permit2 spender (decision 096: one
31
33
  * router per manager; a second spender is a second signature, not a second on-chain approval). See
@@ -34,29 +36,19 @@
34
36
  */
35
37
 
36
38
  import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256, toFunctionSelector, type Address, type Hash, type Hex } from "viem";
37
- import { managerFAbi, lensFAbi, routerFAbi, orphanPolicyFAbi, padPolicyAbi, polPolicyAbi, policyRegistryAbi, sponsorPolicyFAbi } from "./generated.js";
39
+ import { managerFAbi, lensFAbi, routerFAbi, policyFAbi, policyRegistryAbi } from "./generated.js";
38
40
 
39
41
  /**
40
- * One contract, one ABI (F version 12): `harvest`, `claim`, `regenerate`, `close`, `deployLiquidity`,
41
- * the fee parameters are `ManagerF`'s own code. The roles left it for the policies in F version 15:
42
- * {@link fPolicyBaseAbi} is what the policies share, {@link sponsorPolicyFAbi} the sponsored one (kind
43
- * `"sponsor"`, decision 098), {@link padPolicyAbi} / {@link polPolicyAbi} the other kinds', and
44
- * {@link orphanPolicyFAbi} the neutral policy of a pool the LOG orphaned.
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
45
  */
46
- export { managerFAbi, orphanPolicyFAbi, padPolicyAbi, polPolicyAbi, sponsorPolicyFAbi };
47
- /**
48
- * What the protocol's policies share: `authority`, `nameOf` / `setName`, `kind`, `maxHarvest`
49
- * (a harvest has no cut, decisions 056). `polPolicyAbi` is a superset of it, so it stands in for the base: a call
50
- * through it to any F policy decodes the base's functions (`maxHarvest` is absent on the orphan policy, which refuses every harvest).
51
- */
52
- export const fPolicyBaseAbi = polPolicyAbi;
46
+ export { managerFAbi, policyFAbi };
53
47
  import { clientChainId, type LogswapClient } from "./client.js";
54
48
  import { findQuoteResult } from "./quote.js";
55
49
  import { fallBackUnlessRejected, signerFor } from "./write.js";
56
50
  import { getEventLogs } from "./history.js";
57
51
  import { poolHolders } from "./views.js";
58
- import { presetMintFee } from "./positions.js";
59
- import { isValidMintFee, MINT_FEE_MAX } from "./keys.js";
60
52
 
61
53
  const WAD = 10n ** 18n;
62
54
  const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" as const;
@@ -84,9 +76,9 @@ export interface FPoolState {
84
76
  Q: bigint;
85
77
  /** Total exposure. Grows on mint, shrinks on burn; never moves on a swap. */
86
78
  L: bigint;
87
- /** The swap fee, WAD (`phi` before F version 25, decisions 059). 0 is no fee (F version 26, decisions 065), admitted only if the policy lists it. */
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. */
88
80
  swapFee: bigint;
89
- /** The pool's mint fee, WAD of newly-minted L: the creator-selected key field, fixed for life (F 38, decision 078): `2 * swapFee <= mintFee <= MINT_FEE_MAX`. */
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}). */
90
82
  mintFee: bigint;
91
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. */
92
84
  refLogFloor: bigint;
@@ -105,34 +97,32 @@ export interface FPoolState {
105
97
  /** Σ = ∫ Σ_j w_j (dx_j)², accrued even though the fee is fixed — the kernel stays calculable. */
106
98
  realizedVariance: bigint;
107
99
  /**
108
- * The pool's policy: the contract the key names, holding the pool's roles
109
- * and answering every question the manager does not decide itself. Read its roles with
110
- * {@link getFPoolRoles}; one of the deployment's four ({@link fPoolPolicyFor}) on every protocol pool.
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.
111
103
  */
112
104
  policy: Address;
113
105
  /**
114
- * What the policy declared for the pool (`Pool.flags`, decision 098): the gate bits {@link GATE_SWAP} and {@link GATE_MINT} (changed
115
- * later by the policy's `setGates`) and the birth bit {@link SEED_TO_DEAD} (a pad's, the pool's for life).
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).
116
108
  */
117
109
  flags: number;
118
- /** The operator the manager caches for the gates (`Pool.operator`): admitted by a gated swap or mint with no policy call. Zero with no gate on. */
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
+ */
119
114
  operator: Address;
120
- /** The sponsor's own label for this pool — the policy's word, mutable and never identity. "" when unnamed. */
121
- name: string;
122
115
  /** The time (unix seconds) of the last harvest / composition action: no swap runs at that timestamp (F version 29; a block number before). */
123
116
  restructureTime: number;
124
- /** What the pool is — its POLICY's self-description; see {@link FPoolKind}. */
117
+ /** What the pool is — a label read off its POLICY's immutables; see {@link FPoolKind}. */
125
118
  kind: FPoolKind;
126
- /** False before the first `deployLiquidity` — and between a `close` and the next one. */
119
+ /** False before the first `deployLiquidity` — and between a `close` and the next one (the pool is INACTIVE: listed, or closed). */
127
120
  seeded: boolean;
128
121
  /**
129
- * The live GENERATION. Every `close` freezes one into a bundle its shares redeem
130
- * ({@link fPoolRedeem}) and opens the next; so does every `regenerate`
131
- * (the generation step, {@link fPoolRegenerate}) and every live-pool `deployLiquidity`
132
- * ({@link fPoolDeploy}): the carried holder and the dead shares go on
133
- * as `gen + 1`, every other holder of `gen` is frozen out into its bundle. The share id carries
134
- * it ({@link fPoolShareId}), so generations `0 … gen-1` are claims ({@link fPoolClaimsOf}) and
135
- * `gen` is the pool. On a pad, `gen` is the graduation count — the rung.
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.
136
126
  */
137
127
  gen: number;
138
128
  totalSupply: bigint;
@@ -159,7 +149,7 @@ async function rawFPool(c: LogswapClient, poolId: Hex) {
159
149
  return p;
160
150
  }
161
151
 
162
- /** Read a basket pool whole: one lens call (`pool`, F version 25) plus the policy's kind and name. */
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}. */
163
153
  export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolState> {
164
154
  const v = await c.public.readContract({
165
155
  address: c.addresses.lensF,
@@ -174,7 +164,7 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
174
164
  // flow's resumability turns on: an initialized-but-unseeded pool MUST still read, so this
175
165
  // cannot be a check on `seeded`.
176
166
  if (/^0x0{40}$/i.test(p.quote)) throw new Error(`logswap: no F pool with id ${poolId}`);
177
- const [kind, name] = await Promise.all([fPoolKindOfPolicy(c, p.policy), fPoolNameOf(c, poolId, p.policy)]);
167
+ const kind = await fPoolKindOfPolicy(c, p.policy);
178
168
  return {
179
169
  poolId,
180
170
  quote: p.quote,
@@ -194,7 +184,6 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
194
184
  policy: p.policy,
195
185
  flags: Number(p.flags),
196
186
  operator: p.operator,
197
- name,
198
187
  restructureTime: Number(p.restructureTime),
199
188
  kind,
200
189
  seeded: p.seeded,
@@ -207,53 +196,123 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
207
196
  }
208
197
 
209
198
  /**
210
- * The kind of pool — the POLICY's self-description (the manager knows no kind; the
211
- * policy the key names is the kind, and what it promises is its code). `sponsor`: the sponsored policy (decision 098),
212
- * one kind for the LOG's own instances (sponsor = the LOG: the open canonical one, or one with gates) and a third party's
213
- * (the sponsor creates under it): its authority is `key.creator`, an optional operator, and the gate modes where the
214
- * policy offers them. `pol`, a treasury's pool, one base: composition and access fixed at birth. `pad`, a launch,
215
- * one base: its policy answers income only at every harvest and declared its seed the pool's at birth
216
- * (`SEED_TO_DEAD`) — open to all. `orphan`: the pool the LOG moved off a rogue or lost sponsor, no owner and no
217
- * setting (`PolicyRegistry.orphan`): swap and mint stay open, holders burn, claim and redeem. Every rate, role and gate is the policy's.
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}).
218
205
  */
219
- export type FPoolKind = "sponsor" | "pol" | "pad" | "orphan";
220
- const F_KIND_NAMES: readonly FPoolKind[] = ["sponsor", "pol", "pad", "orphan"];
221
- /** The policy's birth-time declaration that the seed's shares are the pool's (a pad's), in `flags`. */
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`. */
222
208
  export const SEED_TO_DEAD = 4;
223
209
 
224
- const kindCache = new Map<string, Promise<FPoolKind>>();
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
+ }
225
248
 
226
249
  /**
227
- * What a policy IS — its `kind()` tag, read once per policy address and cached for the client's
228
- * chain: a pool's kind is its policy's word, never the manager's. An unknown tag
229
- * (a policy that is not one of the protocol's four shapes) throws; the app has no screen for it.
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.
230
252
  */
231
- export async function fPoolKindOfPolicy(c: LogswapClient, policy: Address): Promise<FPoolKind> {
232
- // the chain id is part of the key: the policies sit at one address on every release chain
253
+ export async function fPolicyTermsOf(c: LogswapClient, policy: Address): Promise<FPolicyTerms> {
233
254
  const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
234
- let hit = kindCache.get(key);
255
+ let hit = termsCache.get(key);
235
256
  if (!hit) {
236
- hit = (c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "kind" } as never) as Promise<Hex>).then((word) => {
237
- const tag = bytes32ToText(word) as FPoolKind;
238
- if (!F_KIND_NAMES.includes(tag)) throw new Error(`logswap: policy ${policy} says it is "${tag}", which is no kind this SDK knows`);
239
- return tag;
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) };
240
286
  });
241
- kindCache.set(key, hit);
242
- hit.catch(() => kindCache.delete(key)); // a failed read is not a fact
287
+ termsCache.set(key, hit);
288
+ hit.catch(() => termsCache.delete(key)); // a failed read is not a fact
243
289
  }
244
290
  return hit;
245
291
  }
246
292
 
247
- /** The pool's label, as its policy holds it. "" when unnamed. */
248
- export async function fPoolNameOf(c: LogswapClient, poolId: Hex, policy?: Address): Promise<string> {
249
- const p = policy ?? (await fPoolPolicyOf(c, poolId));
250
- const word = (await c.public.readContract({ address: p, abi: fPolicyBaseAbi, functionName: "nameOf", args: [poolId] } as never)) as Hex;
251
- return bytes32ToText(word);
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) : "";
252
310
  }
253
311
 
254
312
  /**
255
- * The deployment's named policies (its artifact keys): the LOG's open sponsored instance (`public`: canonical, no gate available),
256
- * its gated sponsored instance (`private`: gates available, born gated), `pol`, `pad`. The first two are both of kind `"sponsor"`.
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.
257
316
  */
258
317
  export type FPolicySlot = "public" | "private" | "pol" | "pad";
259
318
 
@@ -271,53 +330,49 @@ export async function fPoolPolicyOf(c: LogswapClient, poolId: Hex): Promise<Addr
271
330
  }
272
331
 
273
332
  /**
274
- * A pool's roles, as its POLICY holds them (decision 098). `authority` is the pool's `key.creator` for life — no handover — and zero on an
275
- * orphaned pool. A sponsored policy also holds the pool's `operator` (appointed by the authority, admitted by the gates with no call and a runner
276
- * of the pool), its two gates and its whitelist; every other kind has none of them: those fields read zero / false / `"open"`.
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}).
277
337
  */
278
338
  export interface FPoolRoles {
279
339
  policy: Address;
340
+ /** The policy's authority now (`authority()`): its immutable, or the registry's LOG Authority when that is zero. */
280
341
  authority: Address;
281
- /** The sponsored policy's per-pool operator (`appointOperator`): zero when none, and on every other kind. */
342
+ /** The pool's operator (`operator(poolId)`): the authority at birth until re-appointed. Zero: the policy never held this pool. */
282
343
  operator: Address;
283
- /** The mint gate (sponsored policies, where gates are available): on, only the authority and the operator mint. */
284
- gateMint: boolean;
285
- /** Swap admission (sponsored policies, where gates are available): everyone, the operator only, or the whitelist (the operator always passes). */
286
- swapMode: FPoolSwapMode;
287
- /** The policy's own ceiling on a harvest now — the bid ({@link FPoolDescription.harvestable}) narrowed by the policy's rule. Zero on an orphaned pool. */
288
- maxHarvest: bigint;
289
- }
290
-
291
- /** `SponsorPolicyBase.SwapMode`: Open = 0, Operator = 1, Listed = 2. */
292
- export type FPoolSwapMode = "open" | "operator" | "listed";
293
- const SWAP_MODES: readonly FPoolSwapMode[] = ["open", "operator", "listed"];
294
- /** The swap modes in `SponsorPolicyBase.SwapMode` order — the index is the on-chain ordinal. */
295
- export const fPoolSwapModes: readonly FPoolSwapMode[] = SWAP_MODES;
296
-
297
- /** Read a pool's roles from its policy. `state` saves the `getPool` round trip when already in hand. */
298
- export async function getFPoolRoles(c: LogswapClient, poolId: Hex, state?: Pick<FPoolState, "policy" | "kind">): Promise<FPoolRoles> {
299
- const s = state ?? (await getFPool(c, poolId));
300
- const rdPolicy = <T>(abi: readonly unknown[], functionName: string) =>
301
- c.public.readContract({ address: s.policy, abi, functionName, args: [poolId] } as never) as Promise<T>;
302
- const [authority, maxHarvest] = await Promise.all([
303
- rdPolicy<Address>(fPolicyBaseAbi, "authority"),
304
- s.kind === "orphan" ? Promise.resolve(0n) : rdPolicy<bigint>(fPolicyBaseAbi, "maxHarvest"),
305
- ]);
306
- if (s.kind !== "sponsor") return { policy: s.policy, authority, operator: ZERO_ADDRESS, gateMint: false, swapMode: "open", maxHarvest };
307
- const [operator, gateMint, mode] = await Promise.all([
308
- rdPolicy<Address>(sponsorPolicyFAbi, "operator"),
309
- rdPolicy<boolean>(sponsorPolicyFAbi, "gateMint"),
310
- rdPolicy<number>(sponsorPolicyFAbi, "swapMode"),
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]),
311
366
  ]);
312
- return { policy: s.policy, authority, operator, gateMint, swapMode: SWAP_MODES[Number(mode)] ?? "open", maxHarvest };
367
+ return { policy, authority, operator, swapMode: MODES[Number(swap)] ?? "open", mintMode: MODES[Number(mint)] ?? "open" };
313
368
  }
314
369
 
315
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. */
316
371
  export type FPoolShape = "launch" | "basket";
317
372
 
318
373
  export interface FPoolDescription {
319
- shape: FPoolShape;
320
374
  /** The pad is the launch shape, by the kind. */
375
+ shape: FPoolShape;
321
376
  legs: number;
322
377
  /** True when the pool holds no quote: an all-base resting ask. base→quote is the one blocked path. */
323
378
  atFloor: boolean;
@@ -327,30 +382,42 @@ export interface FPoolDescription {
327
382
  * from the first wei after it.
328
383
  */
329
384
  unharvested: bigint;
330
- /**
331
- * The most a harvest may take now by the MANAGER's rule: the bid, `Q` once seeded (0 before).
332
- * The manager's `harvestable()` getter was cut in F version 21; this is the same number, read
333
- * off `getPool`. The policy may allow less (a pad: the income; a POL: above `minQuoteRatio`·L) —
334
- * {@link FPoolRoles.maxHarvest}.
335
- */
336
- harvestable: bigint;
337
- /** The dead shares' banked dividend — a pad's income, the creator's until a rung is climbed (decision 085: formerly the pot). */
385
+ /** What a harvest takes with `extra` 0: the income, at most the bid. */
338
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 };
339
407
  }
340
408
 
341
409
  export async function describeFPool(c: LogswapClient, s: FPoolState): Promise<FPoolDescription> {
342
- // an unfunded pool has no L: nothing earned, nothing to harvest, no income. The bid is the
343
- // manager's ceiling (`harvestable()` until F version 21, which cut the getter): Q once seeded.
344
- const harvestable = s.L > 0n ? s.Q : 0n;
345
- const unharvested = s.L > 0n ? s.unharvested : 0n;
346
- const income = s.L > 0n ? await fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, s.gen) : 0n;
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);
347
413
  return {
348
- shape: s.kind === "pad" ? "launch": "basket", // the kind, not n = 1
414
+ shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
349
415
  legs: s.bases.length,
350
416
  atFloor: s.Q === 0n,
351
- unharvested,
352
- harvestable,
417
+ unharvested: s.L > 0n ? s.unharvested : 0n,
353
418
  income,
419
+ capitalRoom: capital,
420
+ harvestable: income + capital,
354
421
  };
355
422
  }
356
423
 
@@ -614,18 +681,20 @@ export async function fPoolPreviewRollIn(
614
681
  return { dL, quoteShort, quoteExcess };
615
682
  }
616
683
 
617
- // ─── the floor lever (authority only) ─────────────────────────────────────────
684
+ // ─── the floor lever (the operator's) ─────────────────────────────────────────
618
685
 
619
686
  /**
620
- * Remove quote, lifting logFloor — price-neutral, no base moves, and a DIVIDEND to
621
- * every share: the amount goes into the pool's held income and each holder's slice is settled lazily on
622
- * their next transfer, mint or burn, or pulled with {@link fPoolClaim}. The sponsor's own slice —
623
- * its shares' and the locked seed's at 0xdead — is pushed to `to` at once. On a pad
624
- * the lift stops at the seed floor, refLogFloor (income only); nothing else bounds it — an
625
- * unlocked pool's authority may take Q to zero.
687
+ * Harvest (policy.md §9): take this generation's income — `L·(refLogFloor − logFloor)`, the fees since the floor was last
688
+ * referenced — and `extra` of capital on top of it, out of the bid; price-neutral, no base moves. Both accrue as a DIVIDEND to
689
+ * every share, settled lazily on each holder's next transfer, mint or burn or pulled with {@link fPoolClaim}; the income is taxed
690
+ * 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`.
691
+ * The operator's own settled dividend — this harvest's and anything pending — is paid to `to` in the same call: one transaction,
692
+ * and the operator (usually a contract) routes the payout through `to`. The operator's alone (`NotOperator`). `extra` must fit the
693
+ * room ({@link fPoolHarvestRoom}): 0 on a pad (`HarvestLimit`) and under an income-only policy (`IncomeOnly`), within the buffer
694
+ * otherwise (`QuoteTooThin`).
626
695
  */
627
- export async function fPoolHarvest(c: LogswapClient, a: { poolId: Hex; amount: bigint; to?: Address; account: Address }) {
628
- return writeFPool(c, a.poolId, "harvest", [a.amount, a.to ?? a.account], a.account);
696
+ export async function fPoolHarvest(c: LogswapClient, a: { poolId: Hex; extra?: bigint; to?: Address; account: Address }) {
697
+ return writeFPool(c, a.poolId, "harvest", [a.extra ?? 0n, a.to ?? a.account], a.account);
629
698
  }
630
699
 
631
700
  /**
@@ -657,7 +726,7 @@ export async function fPoolDividendOf(c: LogswapClient, poolId: Hex, holder: Add
657
726
  // A lending contract — the LOCKER — locks part of an owner's shares in place: no transfer, burn or
658
727
  // redeem past the free balance. The dividend the locked amount earns is HELD BY THE LIEN, claimable
659
728
  // by nobody while it stands; lifted, it goes with the lifted part — to the owner on a release (a
660
- // repaid loan gets it back), to the seizer on a seizure. A borrower frozen out by `regenerate` keeps
729
+ // repaid loan gets it back), to the seizer on a seizure. A borrower frozen into a bundle by `close` keeps
661
730
  // its lien on the old generation's id.
662
731
 
663
732
  /** A lien on one share id: the locker, the amount locked, and the dividend the lien holds (banked). */
@@ -994,32 +1063,26 @@ export interface FPoolCreateArgs {
994
1063
  quote: Address;
995
1064
  /** 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. */
996
1065
  bases: Address[];
997
- /** The swap fee, WAD. Base-for-base pays it once, like any swap (F 39). A curated policy admits only its listed tiers (decisions 059). */
998
- swapFee: bigint;
999
- /**
1000
- * The pool's mint fee, WAD of newly-minted L — the creator's pick, a key field fixed for life (F 38, decision
1001
- * 078): `2 * swapFee <= mintFee <= MINT_FEE_MAX`, checked by the manager (`BadParam`). Defaults to
1002
- * {@link presetMintFee}: twice the swap fee.
1003
- */
1004
- mintFee?: bigint;
1066
+ /** 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`. */
1067
+ swapFeeIdx?: number;
1068
+ /** The swap fee, WAD — one of the list's eight values ({@link fFeeIndexOf} throws otherwise); the index is what the key carries. */
1069
+ swapFee?: bigint;
1005
1070
  /**
1006
1071
  * Which of the deployment's policies the key names when `policy` is not given ({@link fPoolPolicyFor}). NOT a key
1007
- * field (decisions 049: the manager knows no kind): the policy is, and it says what it is ({@link FPoolKind}).
1072
+ * field (decisions 049: the manager knows no kind): the policy is, and its terms say what it is ({@link FPoolKind}).
1008
1073
  */
1009
1074
  kind: FPolicySlot;
1010
1075
  /**
1011
- * The pool's policy: the contract the key names, approved by the registry — the pool's kind. Defaults to the
1012
- * deployment's policy for `kind` ({@link fPoolPolicyFor}). A sponsored policy admits creation by its sponsor only
1013
- * (`SponsorOnly`), and the initializer must be `creator` (`NotCreator`).
1076
+ * The pool's policy for life: the contract the key names, approved by the registry (`PolicyNotApproved`). Defaults to the
1077
+ * deployment's policy for `kind`. An open policy admits anyone; a closed one its authority alone (`Refused`). The policy's
1078
+ * authority is the pool's operator at birth: the one account that then funds it ({@link fPoolDeploy}).
1014
1079
  */
1015
1080
  policy?: Address;
1016
- /** Who is born holding the pool: immutable identity, the pool's authority for life (the policy records it) and the initializer (`NotCreator`). */
1017
- creator: Address;
1018
1081
  /**
1019
- * The differentiator, and nothing else. Identity is the key's hash, so one sponsor cannot run
1020
- * two pools of the same shape without varying it — the second `initialize` would land on the
1021
- * first pool's id. Defaults to zero, which is the first book of any shape. A pool's NAME is not
1022
- * this: names are the policy's mutable state (`fPoolSetName`), so a rename forks nothing.
1082
+ * The differentiator, and nothing else. Identity is the key's hash, so a sponsor cannot run two pools of the same shape
1083
+ * without varying it — the second `initialize` would land on the first pool's id. Zero under an open policy (`NotCanonical`):
1084
+ * one public pool per shape and swap fee. Defaults to zero. A pool's NAME is not this: names are events on the policy
1085
+ * ({@link fPoolSetName}), so a rename forks nothing.
1023
1086
  */
1024
1087
  salt?: Hex;
1025
1088
  account: Address;
@@ -1027,6 +1090,59 @@ export interface FPoolCreateArgs {
1027
1090
 
1028
1091
  const ZERO_SALT = `0x${"0".repeat(64)}` as const;
1029
1092
 
1093
+ // ─── the fee list (policy.md §6) ──────────────────────────────────────────────
1094
+
1095
+ /** `FeeParams.FEE_LIST` in bp: the eight swap fees an F pool may be born with. The key carries the index. */
1096
+ export const F_FEE_LIST_BP = [1, 2, 5, 10, 20, 50, 100, 200] as const;
1097
+ /** The list in WAD (1 bp = 1e14). No zero: the fee-free pool cannot be born. */
1098
+ export const F_FEE_LIST: readonly bigint[] = F_FEE_LIST_BP.map((bp) => BigInt(bp) * 10n ** 14n);
1099
+
1100
+ /** The fee at `idx` of the list, WAD. Throws off the list. */
1101
+ export function fFeeOf(idx: number): bigint {
1102
+ const fee = Number.isInteger(idx) ? F_FEE_LIST[idx] : undefined;
1103
+ if (fee === undefined) throw new Error(`logswap: swap fee index ${idx} is off the F fee list (0..${F_FEE_LIST.length - 1})`);
1104
+ return fee;
1105
+ }
1106
+
1107
+ /** 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). */
1108
+ export function fMintFeeIdxOf(swapFeeIdx: number): number {
1109
+ fFeeOf(swapFeeIdx);
1110
+ return Math.min(swapFeeIdx + 1, F_FEE_LIST.length - 1);
1111
+ }
1112
+
1113
+ /** The mint fee, WAD of newly-minted L, a pool born at `swapFeeIdx` charges on outside mints. */
1114
+ export function fMintFeeOf(swapFeeIdx: number): bigint {
1115
+ return fFeeOf(fMintFeeIdxOf(swapFeeIdx));
1116
+ }
1117
+
1118
+ /** 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. */
1119
+ export function fFeeIndexOf(fee: bigint): number {
1120
+ const idx = F_FEE_LIST.indexOf(fee);
1121
+ if (idx < 0) throw new Error(`logswap: swap fee ${fee} is not on the F fee list (${F_FEE_LIST_BP.join(", ")} bp)`);
1122
+ return idx;
1123
+ }
1124
+
1125
+ /** Whether a policy's `feeMask` admits `idx`: a bit per index, an empty mask admitting all eight. */
1126
+ export function fFeeListed(feeMask: number, idx: number): boolean {
1127
+ return Number.isInteger(idx) && idx >= 0 && idx < F_FEE_LIST.length && (feeMask === 0 || ((feeMask >> idx) & 1) === 1);
1128
+ }
1129
+
1130
+ /** The indices a policy's `feeMask` admits, ascending. */
1131
+ export function fFeesAllowed(feeMask: number): number[] {
1132
+ return F_FEE_LIST.map((_, i) => i).filter((i) => fFeeListed(feeMask, i));
1133
+ }
1134
+
1135
+ /** The swap fee index of create arguments given either way; both given must agree. */
1136
+ export function fPoolSwapFeeIdxOf(a: { swapFeeIdx?: number; swapFee?: bigint }): number {
1137
+ if (a.swapFeeIdx !== undefined) {
1138
+ const fee = fFeeOf(a.swapFeeIdx);
1139
+ 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})`);
1140
+ return a.swapFeeIdx;
1141
+ }
1142
+ if (a.swapFee !== undefined) return fFeeIndexOf(a.swapFee);
1143
+ throw new Error("logswap: an F pool needs its swap fee — `swapFeeIdx` (into the list) or `swapFee` (WAD, on the list)");
1144
+ }
1145
+
1030
1146
  /** `bytes32` ⇄ short UTF-8 text, for the pool and sponsor labels. */
1031
1147
  export function textToBytes32(text: string): Hex {
1032
1148
  const b = new TextEncoder().encode(text);
@@ -1049,69 +1165,60 @@ export function sortFPoolLegs<T>(bases: Address[], ...companions: T[][]): { base
1049
1165
  }
1050
1166
 
1051
1167
  /**
1052
- * The tuple an F pool's id hashes — `src/types/FPoolKey.sol`, field order load-bearing (it is
1053
- * the ABI encoding order). Stored by the manager at `initialize` and never in calldata again,
1054
- * except `PolicyRegistry.migrate`, which is handed it to check against the id. Since F 38 it holds no weights and no
1055
- * cap: those belong to a generation's `deployLiquidity` (decision 075), and the mint fee is part of identity (078).
1168
+ * The tuple an F pool's id hashes — `src/types/PoolKeyF.sol`, field order load-bearing (it is the ABI encoding order).
1169
+ * Stored by the manager at `initialize` and never in calldata again. No creator, no mint fee, no weights and no cap
1170
+ * (policy.md §5): both fees follow from `swapFeeIdx`, the book belongs to a generation's `deployLiquidity`.
1056
1171
  */
1057
1172
  export interface FPoolKey {
1058
1173
  quote: Address;
1059
- /** Sorted ascending, unique; fixed for the pool's life. */
1174
+ /** Sorted ascending, unique, 1..8; fixed for the pool's life. */
1060
1175
  bases: Address[];
1061
- swapFee: bigint;
1062
- /** The policy AT BIRTH — not the live one after a move. */
1176
+ /** Into {@link F_FEE_LIST}; the mint fee is the next entry ({@link fMintFeeIdxOf}). */
1177
+ swapFeeIdx: number;
1178
+ /** The pool's policy for life. */
1063
1179
  policy: Address;
1064
- creator: Address;
1180
+ /** Zero under an open policy. */
1065
1181
  salt: Hex;
1066
- /** The creator-selected mint fee, WAD, fixed for life: `2 * swapFee <= mintFee <= MINT_FEE_MAX`. */
1067
- mintFee: bigint;
1068
1182
  }
1069
1183
 
1070
- const F_POOL_KEY_ABI = [
1184
+ /** The key's ABI as `abi.encode(key)` lays it out: what {@link fPoolIdOfKey} hashes. */
1185
+ export const F_POOL_KEY_ABI = [
1071
1186
  {
1072
1187
  type: "tuple",
1073
1188
  components: [
1074
1189
  { name: "quote", type: "address" },
1075
1190
  { name: "bases", type: "address[]" },
1076
- { name: "swapFee", type: "uint256" },
1191
+ { name: "swapFeeIdx", type: "uint8" },
1077
1192
  { name: "policy", type: "address" },
1078
- { name: "creator", type: "address" },
1079
1193
  { name: "salt", type: "bytes32" },
1080
- { name: "mintFee", type: "uint256" },
1081
1194
  ],
1082
1195
  },
1083
1196
  ] as const;
1084
1197
 
1085
1198
  /**
1086
1199
  * An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
1087
- * manager's `idOf(FPoolKey)` getter was cut in F version 21; this is the same hash (checked
1088
- * against Foundry's encoder and the local deployment's pools in the tests). The key must be the
1089
- * one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them), the birth policy.
1200
+ * manager's `idOf` getter was cut in F version 21; this is the same hash (checked against Foundry's encoder in the
1201
+ * tests). The key must be the one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them).
1090
1202
  */
1091
1203
  export function fPoolIdOfKey(key: FPoolKey): Hex {
1092
1204
  return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
1093
1205
  }
1094
1206
 
1095
- /** The key as the manager hashes it: bases sorted, the kind's policy filled in when none is named, the mint fee preset when none is given. No kind in it (049). */
1207
+ /** 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). */
1096
1208
  export function fPoolKeyOf(c: LogswapClient, a: Omit<FPoolCreateArgs, "account">): FPoolKey {
1097
1209
  const { bases } = sortFPoolLegs(a.bases);
1098
- return {
1099
- quote: a.quote,
1100
- bases,
1101
- swapFee: a.swapFee,
1102
- policy: a.policy ?? fPoolPolicyFor(c, a.kind),
1103
- creator: a.creator,
1104
- salt: a.salt ?? ZERO_SALT,
1105
- mintFee: a.mintFee ?? presetMintFee(a.swapFee),
1106
- };
1210
+ return { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy ?? fPoolPolicyFor(c, a.kind), salt: a.salt ?? ZERO_SALT };
1107
1211
  }
1108
1212
 
1109
- /** Create the pool (no funds move — `deployLiquidity` funds it). Returns the tx hash; read the id with `fPoolIdOf`. */
1213
+ /**
1214
+ * List the pool — `initialize(key)` (policy.md §9): no funds move; the pool is inactive until its operator funds it
1215
+ * ({@link fPoolDeploy}). Anyone under an open policy (salt zero), the policy's authority alone under a closed one
1216
+ * (`Refused`); refused past the policy's sunset (`PolicyNotApproved`), off the policy's fee mask (`FeeNotListed`), quote or
1217
+ * base list (`QuoteNotListed`, `BaseNotListed`), or with more legs than it allows (`TooManyLegs`). Returns the tx hash;
1218
+ * read the id with {@link fPoolIdOf}.
1219
+ */
1110
1220
  export async function fPoolInitialize(c: LogswapClient, a: FPoolCreateArgs) {
1111
1221
  const key = fPoolKeyOf(c, a);
1112
- if (!isValidMintFee(key.swapFee, key.mintFee)) {
1113
- throw new Error(`logswap: mint fee ${key.mintFee} is outside 2 × the swap fee (${2n * key.swapFee}) … ${MINT_FEE_MAX}`);
1114
- }
1115
1222
  const wallet = requireWallet(c);
1116
1223
  const { request } = await c.public.simulateContract({
1117
1224
  address: c.addresses.managerF,
@@ -1133,39 +1240,19 @@ export async function fPoolIdOf(c: LogswapClient, a: Omit<FPoolCreateArgs, "acco
1133
1240
  }
1134
1241
 
1135
1242
  /**
1136
- * Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field but the salt,
1137
- * which is taken from `opts.salt` (zero by default — every pool the SDK's create flow makes
1138
- * without naming one; a pad's carries its split, so it is rebuilt from the policy's record with nonce 0 — pass `opts.salt` for another nonce). The result is checked against the id, so a wrong salt throws rather than
1139
- * returning a key that names another pool. What {@link fPoolMigrate} needs when handed an id.
1243
+ * Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field, the salt included (F 41). The result
1244
+ * is checked against the id.
1140
1245
  */
1141
- export async function fPoolKeyOfPool(c: LogswapClient, poolId: Hex, opts: { salt?: Hex; fromBlock?: bigint; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. The salt is in neither (the event does not carry it). */ indexer?: string } = {}): Promise<FPoolKey> {
1246
+ 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> {
1142
1247
  type Ev = Extract<(typeof managerFAbi)[number], { type: "event"; name: "PoolCreated" }>;
1143
1248
  const ev = managerFAbi.find((x): x is Ev => x.type === "event" && x.name === "PoolCreated")!;
1144
1249
  const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev as never, args: { poolId }, fromBlock: opts.fromBlock });
1145
1250
  const l = logs[0];
1146
1251
  if (!l) throw new Error(`logswap: no PoolCreated for F pool ${poolId}`);
1147
- const a = l.args as unknown as { quote: Address; creator: Address; bases: readonly Address[]; swapFee: bigint; policy: Address; mintFee: bigint };
1148
- const key: FPoolKey = {
1149
- quote: a.quote,
1150
- bases: [...a.bases],
1151
- swapFee: a.swapFee,
1152
- policy: a.policy,
1153
- creator: a.creator,
1154
- salt: opts.salt ?? ZERO_SALT,
1155
- mintFee: a.mintFee,
1156
- };
1157
- if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
1158
- // a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
1159
- try {
1160
- const creatorShare = BigInt((await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "creatorShareOf", args: [poolId] } as never)) as bigint | number);
1161
- const padKey = { ...key, salt: padSalt({ creatorShare }) };
1162
- if (fPoolIdOfKey(padKey).toLowerCase() === poolId.toLowerCase()) return padKey;
1163
- } catch {
1164
- /* not a pad: fall through to the error */
1165
- }
1166
- }
1252
+ const a = l.args as unknown as { quote: Address; policy: Address; bases: readonly Address[]; swapFeeIdx: number | bigint; salt: Hex };
1253
+ const key: FPoolKey = { quote: a.quote, bases: [...a.bases], swapFeeIdx: Number(a.swapFeeIdx), policy: a.policy, salt: a.salt };
1167
1254
  if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase()) {
1168
- throw new Error(`logswap: F pool ${poolId} was not born with salt ${key.salt} — pass its salt, or its whole key`);
1255
+ 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`);
1169
1256
  }
1170
1257
  return key;
1171
1258
  }
@@ -1335,86 +1422,75 @@ export function fPoolBookL(baseAssets: readonly BaseAsset[], lnCapOverSeed: numb
1335
1422
  * carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
1336
1423
  * carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
1337
1424
  */
1425
+ /**
1426
+ * Fund the pool — `deployLiquidity(poolId, baseAssets, quoteAmount, lnCapOverSeed)` (policy.md §9): the book of this generation,
1427
+ * on an INACTIVE pool — listed and never funded, or closed (`PoolActive` otherwise). The operator's alone (`NotOperator`): it pays
1428
+ * every leg's amount and `quoteAmount` by plain allowance to the manager ({@link approveTokenForFPoolManager}) and holds the shares —
1429
+ * all but `MIN_SHARES`, which go to 0xdead; every share does on a pad. Refused past the policy's sunset (`PolicyNotApproved`),
1430
+ * under its buffer (`QuoteTooThin`), with a cap under its `lnCapMin` (`CapTooClose`). An amount of 0 leaves a leg dormant. Pass the
1431
+ * book raw (`baseAssets` + `lnCapOverSeed`) or as a {@link FPoolBookSpec}.
1432
+ */
1338
1433
  export async function fPoolDeploy(
1339
1434
  c: LogswapClient,
1340
- a: { poolId: Hex; quoteAmount: bigint; to?: Address; account: Address } & (
1341
- | { baseAssets: BaseAsset[]; lnCapOverSeed: number }
1342
- | FPoolBookSpec
1343
- ),
1435
+ a: { poolId: Hex; quoteAmount: bigint; account: Address } & ({ baseAssets: BaseAsset[]; lnCapOverSeed: number } | FPoolBookSpec),
1344
1436
  ) {
1345
1437
  const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
1346
- return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed, a.to ?? a.account], a.account);
1438
+ return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed], a.account);
1347
1439
  }
1348
1440
 
1349
1441
  /**
1350
- * Close the pool — the raw entry (`retire` before F 38). Allowed only at an empty bid, Q ≤ L/1e9, on every pool but a
1351
- * pad: the market took it, or the operator harvested it out first ({@link fPoolClose} does both in one transaction).
1352
- * Income settles to `to` first. The live (S, Q, R_j) become a frozen bundle every share of this generation redeems
1353
- * ({@link fPoolRedeem}), forever; the pool is unfunded until the next {@link fPoolDeploy}, which opens generation
1354
- * `gen + 1` under the same id, policy, roles, gates and lists. Whoever runs the pool.
1442
+ * Close the pool (policy.md §9) — at any bid. The manager harvests the income first (a dividend to every share, the operator's
1443
+ * paid to `to`), freezes every reserve and the bid into generation `gen`'s bundle — every share of it redeems pro rata
1444
+ * ({@link fPoolRedeem}), forever — and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens under
1445
+ * the same id, policy, roles and gates. The operator's alone. Throws before sending on a pad: a pad never closes
1446
+ * (`PadNeverCloses`). Pass `flags` when in hand to save the read.
1355
1447
  */
1356
- export async function fPoolCloseRaw(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address }) {
1448
+ export async function fPoolClose(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address; flags?: number }) {
1449
+ const flags = a.flags ?? (await getFPool(c, a.poolId)).flags;
1450
+ if ((flags & SEED_TO_DEAD) !== 0) throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
1357
1451
  return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
1358
1452
  }
1359
1453
 
1360
1454
  /**
1361
- * Close the pool as ONE transaction: the harvest that empties the bid
1362
- * ({@link fPoolEmptyingHarvests} — a dividend to every share; none when it is already empty),
1363
- * then `close` — the manager's `multicall`, the operator as sender. What a sponsor's "close" button
1364
- * should call. Throws before sending on a pad: a pad never closes.
1365
- */
1366
- export async function fPoolClose(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address }) {
1367
- const harvests = await fPoolEmptyingHarvests(c, a.poolId);
1368
- if (harvests.length === 0) return fPoolCloseRaw(c, a);
1369
- const enc = (functionName: string, args: unknown[]) =>
1370
- encodeFunctionData({ abi: managerFAbi, functionName, args } as never) as Hex;
1371
- const calls: Hex[] = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("close", [a.poolId, a.to ?? a.account])];
1372
- return writeFPool0(c, "multicall", [calls], a.account);
1373
- }
1374
-
1375
- /**
1376
- * The harvests that empty an unlocked pool's bid, in order — what a close sends before its
1377
- * `close` (a close needs an empty bid on every pool). One `harvest(Q)` does it: the income tax leaves the pool with
1378
- * the income part (with no treasury there is none). `[]` when the bid is already empty. Throws on a pad (a pad
1379
- * never closes, whatever its bid), and when the pool's policy keeps a floor on the bid
1380
- * (`PolPolicy.minQuoteRatio`): a `close` under that policy waits for the market.
1455
+ * The relaunch's calls — what `regenerate` was (policy.md §9): `close(poolId, to)`, `redeem(poolId, gen, operator, shares)` for the
1456
+ * operator's own shares of the generation closed (left out at 0), then `deployLiquidity` with the next book. Pure, so a form can show
1457
+ * what it is about to send; {@link fPoolRelaunch} sends them as one `multicall`.
1381
1458
  */
1382
- export async function fPoolEmptyingHarvests(c: LogswapClient, poolId: Hex): Promise<bigint[]> {
1383
- const s = await getFPool(c, poolId);
1384
- // `PadPolicy` refuses `close` at any bid — a pad graduates (regenerate), it never closes; a fresh start is a new pad
1385
- if (s.kind === "pad") throw new Error("logswap: a pad never closes — it graduates by regenerate; a fresh start is a new pad");
1386
- if (s.Q === 0n) return [];
1387
- const { maxHarvest } = await getFPoolRoles(c, poolId, s);
1388
- if (maxHarvest < s.Q) throw new Error("logswap: the pool's policy keeps a floor on the bid — it cannot be harvested empty");
1389
- return [s.Q];
1459
+ export function fPoolRelaunchCalls(
1460
+ a: { poolId: Hex; gen: number | bigint; shares: bigint; quoteAmount: bigint; to?: Address; account: Address } & (
1461
+ | { baseAssets: BaseAsset[]; lnCapOverSeed: number }
1462
+ | FPoolBookSpec
1463
+ ),
1464
+ ): Hex[] {
1465
+ const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
1466
+ const enc = (functionName: string, args: unknown[]) => encodeFunctionData({ abi: managerFAbi, functionName, args } as never) as Hex;
1467
+ const calls = [enc("close", [a.poolId, a.to ?? a.account])];
1468
+ if (a.shares > 0n) calls.push(enc("redeem", [a.poolId, BigInt(a.gen), a.account, a.shares]));
1469
+ calls.push(enc("deployLiquidity", [a.poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
1470
+ return calls;
1390
1471
  }
1391
1472
 
1392
1473
  /**
1393
- * The GENERATION STEP — on a pad, its graduation (F 38: `deployLiquidity` with nothing changed). The manager
1394
- * harvests the generation's income first, releases the dead shares' income, and asks the policy
1395
- * (`onRegenerate`), whose {@link FPolicyTerms} name a `carried` holder. Then, for live
1396
- * generation `g`:
1397
- *
1398
- * - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
1399
- * as the pool;
1400
- * - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`GenerationRetired`)
1401
- * and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
1402
- * dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
1403
- * lists them;
1404
- * - the income released (`IncomeReleased`), all in quote: `toPayee` to the payee and the rest into the bid
1405
- * (the floor down). No share is minted; L does not move. The book keeps its reserves, marks and cap.
1406
- *
1407
- * A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and a non-canonical sponsored pool carry the
1408
- * authority and send it the whole income; a canonical sponsored pool (the LOG's open instance) refuses (`Refused`). A carried holder with no
1409
- * share is `BadTerms`. Whoever runs the pool. To change the book (reserves, prices, cap) use {@link fPoolDeploy}.
1474
+ * Relaunch the pool as ONE transaction: close generation `gen`, redeem the operator's own shares of it (its funds come back),
1475
+ * fund `gen + 1` with the book given — the manager's `multicall`, the operator as sender. Every other holder is frozen into the
1476
+ * bundle and redeems it ({@link fPoolRedeem}); the new book may re-weight any of the key's bases and pick its own cap. The
1477
+ * deploy pulls its amounts and `quoteAmount` from the operator in the same transaction the redeem pays it, so the allowances
1478
+ * must cover the pull. Not on a pad (a pad never closes); not on an inactive pool (fund it with {@link fPoolDeploy}).
1410
1479
  */
1411
- export async function fPoolRegenerate(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address }) {
1412
- return writeFPool(c, a.poolId, "regenerate", [a.to ?? a.account], a.account);
1480
+ export async function fPoolRelaunch(
1481
+ c: LogswapClient,
1482
+ a: { poolId: Hex; quoteAmount: bigint; to?: Address; account: Address } & ({ baseAssets: BaseAsset[]; lnCapOverSeed: number } | FPoolBookSpec),
1483
+ ) {
1484
+ const s = await getFPool(c, a.poolId);
1485
+ if ((s.flags & SEED_TO_DEAD) !== 0) throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
1486
+ if (!s.seeded) throw new Error("logswap: the pool is inactive — nothing to close; fund it with fPoolDeploy");
1487
+ const shares = await fPoolShareBalance(c, a.poolId, a.account, s.gen);
1488
+ return writeFPool0(c, "multicall", [fPoolRelaunchCalls({ ...a, gen: s.gen, shares })], a.account);
1413
1489
  }
1414
1490
 
1415
- /** Where a pad's seed lives: `seed` mints every share of a pad here itself. */
1491
+ /** Where a pad's seed lives: `deployLiquidity` mints every share of a pad here itself. */
1416
1492
  export const DEAD_ADDRESS: Address = "0x000000000000000000000000000000000000dEaD";
1417
- /** The manager's `MIN_SHARES`: the seed mints this much to 0xdead on every pool, the rest to the seeder — or, on a pad, to 0xdead too. */
1493
+ /** 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. */
1418
1494
  export const F_MIN_SHARES = 1000n;
1419
1495
 
1420
1496
  /**
@@ -1470,7 +1546,7 @@ export interface FPoolLaunchArgs extends Omit<FPoolCreateArgs, "account"> {
1470
1546
  * `followup`: always left to it. Ignored when no row names a recipient.
1471
1547
  */
1472
1548
  deliver?: "auto" | "followup";
1473
- /** The pool's label (≤ 31 bytes of UTF-8) — the policy's word (049), written right after the batch by {@link fPoolLaunch}; not in the batch. */
1549
+ /** 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. */
1474
1550
  name?: string;
1475
1551
  /**
1476
1552
  * The pool already exists (a previous launch got as far as `initialize` and no further — a seed
@@ -1496,30 +1572,21 @@ export function fPoolLaunchCalls(
1496
1572
  if (!a.policy) throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
1497
1573
  const { baseAssets, lnCapOverSeed } = fPoolBook(a);
1498
1574
  const bases = baseAssets.map((x) => x.base);
1499
- const key: FPoolKey = {
1500
- quote: a.quote,
1501
- bases,
1502
- swapFee: a.swapFee,
1503
- policy: a.policy,
1504
- creator: a.creator,
1505
- salt: a.salt ?? ZERO_SALT,
1506
- mintFee: a.mintFee ?? presetMintFee(a.swapFee),
1507
- };
1575
+ const key: FPoolKey = { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy, salt: a.salt ?? ZERO_SALT };
1508
1576
  const enc = (functionName: string, args: unknown[]) =>
1509
1577
  encodeFunctionData({ abi: managerFAbi, functionName, args } as never) as Hex;
1510
1578
  const calls: Hex[] = [];
1511
1579
  if (!a.initialized) calls.push(enc("initialize", [key]));
1512
- calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed, a.account]));
1513
- // gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the live pool.
1580
+ calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
1581
+ // gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the closed pool.
1514
1582
  // No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
1515
1583
  for (const row of fPoolGenesisRows(a)) {
1516
1584
  const j = bases.indexOf(a.bases[row.j]!);
1517
1585
  if (j < 0) throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
1518
1586
  calls.push(enc(row.side === "buy" ? "swapQuoteIn" : "swapBaseIn", [poolId, BigInt(j), row.amountIn, row.minOut ?? 0n, a.account]));
1519
1587
  }
1520
- // the name, a sponsored policy's gates and its whitelist are the POLICY's, not the
1521
- // manager's: they cannot ride in this batch — `fPoolLaunch` and `fPoolDeskOpening` send them
1522
- // right after, as the same creator
1588
+ // the name and the gate modes are the POLICY's, not the manager's: they cannot ride in this batch — `fPoolLaunch`
1589
+ // sends the name right after, as the same operator; the modes are `fPoolSetSwapMode` / `fPoolSetMintMode`
1523
1590
  calls.push(...(a.extra ?? []));
1524
1591
  return calls;
1525
1592
  }
@@ -1606,30 +1673,21 @@ export async function fPoolWalletBatchesAtomically(c: LogswapClient, account: Ad
1606
1673
  }
1607
1674
 
1608
1675
  /**
1609
- * The desk's opening posture, on its sponsored policy: gated minting (only the authority and the operator mint). The swap gate is
1610
- * the policy's own birth (the gated instance is born with `GATE_SWAP` and the creator its operator, decision 098); this is the one write
1611
- * that cannot ride in the launch batch (it is not a manager call).
1612
- */
1613
- export async function fPoolDeskOpening(c: LogswapClient, a: { poolId: Hex; account: Address; policy?: Address }): Promise<Hash[]> {
1614
- const policy = a.policy ?? fPoolPolicyFor(c, "private");
1615
- return [await fPoolSetMintGate(c, { poolId: a.poolId, gated: true, account: a.account, policy })];
1616
- }
1617
-
1618
- /**
1619
- * Create a pool as ONE transaction: `initialize`, `seed`, the seed lock, the opening buy, the
1620
- * name — the manager's `multicall`, the creator as sender throughout (the creator is the initializer, `NotCreator`).
1621
- * Either every call lands or none does; there is no half-built pool to resume.
1676
+ * Create a pool as ONE transaction: `initialize`, `deployLiquidity`, the opening buys — the manager's `multicall`, one sender
1677
+ * throughout. Either every call lands or none does; there is no half-built pool to resume. The sender must be the policy's
1678
+ * AUTHORITY: it is the pool's operator at birth, and `deployLiquidity` is the operator's (`NotOperator`). Under an open
1679
+ * policy anyone may list a pool ({@link fPoolInitialize}) but only the LOG — its authority — funds it, so a launch under the
1680
+ * public policy is the LOG's; a sponsor launches under its own policy.
1622
1681
  *
1623
- * Why the manager and not the router: every one of these entries authenticates by `msg.sender`
1624
- * (`seed` is authority-only, so is everything after it). Routed, the router would be the sender
1625
- * — the authority, the holder of the seed shares — and `initialize` would refuse it (`NotCreator`). `multicall` is delegatecall-to-self, so the
1626
- * sender survives, which is what the manager's own doc says a router cannot do.
1682
+ * Why the manager and not the router: every one of these entries authenticates by `msg.sender`. Routed, the router would be
1683
+ * the sender — the operator, the holder of the seed shares. `multicall` is delegatecall-to-self, so the sender survives.
1627
1684
  *
1628
- * What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base,
1629
- * `Q0` of quote, plus `openBuy.amountIn` of quote. Grant those first — one `approve` per token,
1630
- * once ever ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
1685
+ * What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base, `quoteAmount` of quote, plus
1686
+ * each opening buy's `amountIn` of quote. Grant those first — one `approve` per token, once ever
1687
+ * ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
1631
1688
  *
1632
- * Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}).
1689
+ * Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}). The name, when given, is a second transaction on
1690
+ * the policy ({@link fPoolSetName}); the gate modes are {@link fPoolSetSwapMode} / {@link fPoolSetMintMode} after it.
1633
1691
  */
1634
1692
  export async function fPoolLaunch(
1635
1693
  c: LogswapClient,
@@ -1674,70 +1732,80 @@ export async function fPoolLaunch(
1674
1732
 
1675
1733
  // ─── the roles, on the policy ─────────────────────────────────────────────
1676
1734
  //
1677
- // Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy`
1678
- // may be passed when in hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once.
1735
+ // Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy` may be passed when in
1736
+ // hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once. The policy syncs the manager itself
1737
+ // (`setGates`), which stamps the block: no swap lands in the block of a change (047). Every mode and list write reverts
1738
+ // `GatesUnavailable` on an open policy: a public pool can never be gated.
1679
1739
 
1680
- /** A write keyed by poolId, on the pool's policy. */
1681
- async function writePolicy(c: LogswapClient, abi: readonly unknown[], a: { poolId: Hex; policy?: Address; account: Address }, functionName: string, args: unknown[]) {
1740
+ /** A write on a policy. */
1741
+ async function writePolicy(c: LogswapClient, policy: Address, functionName: string, args: unknown[], account: Address) {
1682
1742
  const wallet = requireWallet(c);
1683
- const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
1684
- const { request } = await c.public.simulateContract({
1685
- address: policy,
1686
- abi,
1687
- functionName,
1688
- args: [a.poolId, ...args],
1689
- account: signerFor(c, a.account),
1690
- } as never);
1743
+ const { request } = await c.public.simulateContract({ address: policy, abi: policyFAbi, functionName, args, account: signerFor(c, account) } as never);
1691
1744
  return wallet.writeContract(request as never);
1692
1745
  }
1693
1746
 
1694
- // ─── a sponsored policy's per-pool settings (the authority's; decision 098) ───────────────
1695
- //
1696
- // `SponsorPolicyF` and `SponsorPolicyC` share these functions, so one ABI writes both: for a C market pass `policy: key.policy`
1697
- // (the default policy lookup reads F's lens). Where the policy offers no gates (`gatesAvailable` false: the LOG's open
1698
- // instance) the mode, gate and list writes revert with `GatesUnavailable`.
1747
+ /** A write keyed by poolId, on the pool's policy. */
1748
+ async function writePoolPolicy(c: LogswapClient, a: { poolId: Hex; policy?: Address; account: Address }, functionName: string, args: unknown[]) {
1749
+ const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
1750
+ return writePolicy(c, policy, functionName, [a.poolId, ...args], a.account);
1751
+ }
1699
1752
 
1700
1753
  /**
1701
- * Appoint the pool's operator (the authority's; zero revokes, refused in `operator` swap mode): admitted by the gates with no policy call and a
1702
- * runner of the pool; it may be a contract (an executor). Immediate, with no acceptance step, so check the address. Stamps the block.
1754
+ * Appoint the pool's operator (the AUTHORITY's; zero resets it to the authority): the account that funds, harvests, closes and sets the
1755
+ * 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
1756
+ * a contract (an executor). `InactivePool` on a pool the policy never held.
1703
1757
  */
1704
1758
  export async function fPoolAppointOperator(c: LogswapClient, a: { poolId: Hex; operator: Address; account: Address; policy?: Address }) {
1705
- return writePolicy(c, sponsorPolicyFAbi, a, "appointOperator", [a.operator]);
1759
+ return writePoolPolicy(c, a, "appointOperator", [a.operator]);
1706
1760
  }
1707
1761
 
1708
1762
  /**
1709
- * Set swap admission (the authority's, where the policy offers gates): `open`, `operator` (only the operator swaps — needs one appointed) or
1710
- * `listed` (the whitelist, {@link fPoolSetListed}; the operator always passes). `burn` is never gated.
1763
+ * Set the pool's swap gate (the OPERATOR's): `open`, `listed` (the policy's swap list, {@link fPolicySetRights}; the operator always
1764
+ * passes) or `operator`. The mint mode must stay at least as restrictive (`ModeOrder`). `burn`, `redeem` and `claim` are never gated.
1711
1765
  */
1712
- export async function fPoolSetSwapMode(c: LogswapClient, a: { poolId: Hex; mode: FPoolSwapMode; account: Address; policy?: Address }) {
1713
- return writePolicy(c, sponsorPolicyFAbi, a, "setSwapMode", [SWAP_MODES.indexOf(a.mode)]);
1766
+ export async function fPoolSetSwapMode(c: LogswapClient, a: { poolId: Hex; mode: FPoolMode; account: Address; policy?: Address }) {
1767
+ return writePoolPolicy(c, a, "setSwapMode", [MODES.indexOf(a.mode)]);
1768
+ }
1769
+
1770
+ /** 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. */
1771
+ export async function fPoolSetMintMode(c: LogswapClient, a: { poolId: Hex; mode: FPoolMode; account: Address; policy?: Address }) {
1772
+ return writePoolPolicy(c, a, "setMintMode", [MODES.indexOf(a.mode)]);
1773
+ }
1774
+
1775
+ /** The bits of `PolicyF.rights`: listed for swaps; listed for mints, which implies swaps. */
1776
+ export const RIGHT_SWAP = 1;
1777
+ export const RIGHT_MINT = 2;
1778
+ /** What a policy lists an address for: nothing, swaps, or mints (and so swaps). */
1779
+ export type FPolicyRight = "none" | "swap" | "mint";
1780
+
1781
+ /** The on-chain bits of a right (`MINT` is written as `MINT | SWAP`, as the policy does). */
1782
+ export function fPolicyRightBits(right: FPolicyRight): number {
1783
+ return right === "none" ? 0 : right === "swap" ? RIGHT_SWAP : RIGHT_SWAP | RIGHT_MINT;
1714
1784
  }
1715
1785
 
1716
- /** Turn the mint gate on or off (the authority's, where the policy offers gates): on, only the authority and the operator mint. */
1717
- export async function fPoolSetMintGate(c: LogswapClient, a: { poolId: Hex; gated: boolean; account: Address; policy?: Address }) {
1718
- return writePolicy(c, sponsorPolicyFAbi, a, "setMintGate", [a.gated]);
1786
+ /** The right the bits spell. */
1787
+ export function fPolicyRightOf(bits: number | bigint): FPolicyRight {
1788
+ const b = Number(bits);
1789
+ return (b & RIGHT_MINT) !== 0 ? "mint" : (b & RIGHT_SWAP) !== 0 ? "swap" : "none";
1719
1790
  }
1720
1791
 
1721
1792
  /**
1722
- * Add to or remove from the pool's swap WHITELIST in one call (the authority's, where the policy offers gates; consulted in `listed` mode).
1723
- * The one list: the free-form minter and taker lists are gone. Stamps the block: no swap lands in it (047).
1793
+ * 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
1794
+ * — 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);
1795
+ * the modes are each pool's. Stamps nothing: an address removed in a block can still swap in that block.
1724
1796
  */
1725
- export async function fPoolSetListed(
1726
- c: LogswapClient,
1727
- a: { poolId: Hex; who: readonly Address[]; listed: boolean; account: Address; policy?: Address },
1728
- ) {
1729
- return writePolicy(c, sponsorPolicyFAbi, a, "setListed", [a.who, a.listed]);
1797
+ export async function fPolicySetRights(c: LogswapClient, a: { policy: Address; who: readonly Address[]; right: FPolicyRight; account: Address }) {
1798
+ return writePolicy(c, a.policy, "setRights", [a.who, fPolicyRightBits(a.right)], a.account);
1730
1799
  }
1731
1800
 
1732
- /** On the pool's swap whitelist now (the sponsored policy's `listed`). */
1733
- export async function fPoolIsListed(c: LogswapClient, poolId: Hex, who: Address, policy?: Address): Promise<boolean> {
1734
- const address = policy ?? (await fPoolPolicyOf(c, poolId));
1735
- return (await c.public.readContract({ address, abi: sponsorPolicyFAbi, functionName: "listed", args: [poolId, who] } as never)) as boolean;
1801
+ /** What `policy` lists `who` for now (`rights`). */
1802
+ export async function fPolicyRightsOf(c: LogswapClient, policy: Address, who: Address): Promise<FPolicyRight> {
1803
+ return fPolicyRightOf((await c.public.readContract({ address: policy, abi: policyFAbi, functionName: "rights", args: [who] } as never)) as number | bigint);
1736
1804
  }
1737
1805
 
1738
- /** Label the pool — the authority's own words on the pool's POLICY, mutable, never identity. At most 31 bytes of UTF-8. */
1806
+ /** Label the pool (the OPERATOR's): a `NameSet` event on the policy, nothing stored — mutable, never identity. At most 31 bytes of UTF-8. */
1739
1807
  export async function fPoolSetName(c: LogswapClient, a: { poolId: Hex; name: string; account: Address; policy?: Address }) {
1740
- return writePolicy(c, fPolicyBaseAbi, a, "setName", [textToBytes32(a.name)]);
1808
+ return writePoolPolicy(c, a, "setName", [textToBytes32(a.name)]);
1741
1809
  }
1742
1810
 
1743
1811
  /**
@@ -1778,9 +1846,9 @@ async function registryAddress(c: LogswapClient): Promise<Address> {
1778
1846
  return registry;
1779
1847
  }
1780
1848
 
1781
- /** Who may run the pool (decision 073): the authority always, and the optional delegate. */
1782
- export function fPoolRunners(s: Pick<FPoolRoles, "authority" | "operator">): Address[] {
1783
- return s.operator === ZERO_ADDRESS ? [s.authority] : [s.authority, s.operator];
1849
+ /** 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. */
1850
+ export function fPoolRunners(s: Pick<FPoolRoles, "operator">): Address[] {
1851
+ return s.operator === ZERO_ADDRESS ? [] : [s.operator];
1784
1852
  }
1785
1853
 
1786
1854
  /**
@@ -1812,16 +1880,19 @@ export interface DiscoveredFPool {
1812
1880
  bases: Address[];
1813
1881
  /** The generation-0 allocation, from the pool's first `LiquidityDeployed` ({@link fPoolBookWeights}); `[]` until it is deployed — F 38 keeps no weights in the key. */
1814
1882
  weights: bigint[];
1883
+ /** The key's swap fee index (policy.md §6). */
1884
+ swapFeeIdx: number;
1885
+ /** The swap fee, WAD: `F_FEE_LIST[swapFeeIdx]`. */
1815
1886
  swapFee: bigint;
1816
- /** The creator-selected mint fee, fixed for life (F 38, decision 078). */
1887
+ /** The mint fee, WAD: the list's next entry ({@link fMintFeeOf}). */
1817
1888
  mintFee: bigint;
1818
1889
  /** The generation-0 cap as ln(cap price / seed price), in 1e-6 log units; 0 uncapped, cap ∞ (decisions 061); 0 until deployed. */
1819
1890
  lnCapOverSeed: number;
1820
1891
  kind: FPoolKind;
1821
- /** The pool's policy AT BIRTH — the contract the key names. The LIVE one is {@link getFPool}'s `policy`: the registry's owner may have moved the pool (046, `PolicyMigrated`). */
1892
+ /** The pool's policy for life — the contract the key names. */
1822
1893
  policy: Address;
1823
- /** Who was born holding the pool: the key's creator, its authority for life (098) unless the LOG orphans it ({@link getFPoolRoles}). */
1824
- creator: Address;
1894
+ /** The key's salt: zero under an open policy. */
1895
+ salt: Hex;
1825
1896
  /** The block the pool was initialized in — its age, for annualising realized income. */
1826
1897
  block: bigint;
1827
1898
  /** Whether `deployLiquidity` has run; an unfunded pool has no floor and no float, so nothing to show. */
@@ -1838,11 +1909,10 @@ export interface DiscoveredFPool {
1838
1909
  }
1839
1910
 
1840
1911
  /**
1841
- * Every F pool ever created, from `PoolCreated` logs alone — plus one `kind()` read per distinct
1842
- * policy, cached. Possible only because the event carries the full key preimage (quote, creator, bases,
1843
- * swapFee, policy, mintFee) — the poolId is a hash and could never be inverted; contracts PR #17
1844
- * exists for exactly this call. With `indexer`, the logs come from it (the node when it fails):
1845
- * a scan from block 0 per call is what made the first load wait on the node.
1912
+ * Every F pool ever created, from `PoolCreated` logs alone — plus the terms of each distinct policy, read once and cached.
1913
+ * Possible only because the event carries the full key (quote, policy, bases, swapFeeIdx, salt) — the poolId is a hash and
1914
+ * could never be inverted; contracts PR #17 exists for exactly this call. With `indexer`, the logs come from it (the node
1915
+ * when it fails): a scan from block 0 per call is what made the first load wait on the node.
1846
1916
  */
1847
1917
  export async function discoverFPools(
1848
1918
  c: LogswapClient,
@@ -1867,23 +1937,22 @@ export async function discoverFPools(
1867
1937
  }
1868
1938
  return Promise.all(
1869
1939
  logs.map(async (l) => {
1870
- const a = l.args as {
1871
- poolId: Hex; quote: Address; creator: Address; bases: readonly Address[];
1872
- swapFee: bigint; policy: Address; mintFee: bigint;
1873
- };
1940
+ const a = l.args as { poolId: Hex; quote: Address; policy: Address; bases: readonly Address[]; swapFeeIdx: number | bigint; salt: Hex };
1874
1941
  const g0 = first.get(a.poolId.toLowerCase());
1875
1942
  const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
1943
+ const swapFeeIdx = Number(a.swapFeeIdx);
1876
1944
  return {
1877
1945
  poolId: a.poolId,
1878
1946
  quote: a.quote,
1879
1947
  bases: [...a.bases],
1880
1948
  weights: g0?.weights ?? [],
1881
- swapFee: a.swapFee,
1882
- mintFee: a.mintFee,
1949
+ swapFeeIdx,
1950
+ swapFee: fFeeOf(swapFeeIdx),
1951
+ mintFee: fMintFeeOf(swapFeeIdx),
1883
1952
  lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
1884
1953
  kind,
1885
1954
  policy: a.policy,
1886
- creator: a.creator,
1955
+ salt: a.salt,
1887
1956
  block: l.blockNumber,
1888
1957
  seeded: g0 !== undefined,
1889
1958
  q0: g0?.q0 ?? 0n,
@@ -1893,137 +1962,24 @@ export async function discoverFPools(
1893
1962
  );
1894
1963
  }
1895
1964
 
1896
- // ─── the policy page: what an authority controls ────────────────────────
1965
+ // ─── the policy page: what an account runs ────────────────────────
1897
1966
  //
1898
- // One policy serves every pool of its kind, so "the pools I control" is not a policy's list: it is
1899
- // every pool whose policy answers `authority(poolId) == me`. Discovery from the log stream (or the
1900
- // indexer), then one `authority` read per pool on its policy — viem multicalls them.
1967
+ // 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
1968
+ // `operator(poolId) == me` — and, for a sponsor, every pool under a policy whose `authority()` is me. Discovery from the log
1969
+ // stream (or the indexer), then the roles per pool on its policy — viem multicalls them.
1901
1970
 
1902
- /** A pool an authority controls, with what the policy page shows of it. */
1971
+ /** A pool an account runs or sponsors, with what the policy page shows of it. */
1903
1972
  export interface FPoolControlled {
1904
1973
  pool: DiscoveredFPool;
1905
1974
  roles: FPoolRoles;
1906
1975
  state: FPoolState;
1907
- /** The policy's numbers for this pool's kind — a pad's gen (its rung) and threshold, a POL's floors, a sponsored policy's immutables and the pool's gates. */
1908
- rules: FPoolRules;
1909
- }
1910
-
1911
- /** What a pool's policy says about it, by kind: the terms a buyer reads before entering. */
1912
- export type FPoolRules =
1913
- | {
1914
- kind: "pad";
1915
- /** The pad's graduation count: the pool's generation (F version 21 — `PadPolicy.rung` is gone). */
1916
- gen: number;
1917
- /** @deprecated Equal to {@link gen} since F version 21, kept for callers; read `gen`. */
1918
- rung: number;
1919
- /** The income the next graduation needs, in the pad's quote: `PadPolicy.threshold(poolId, gen)` (T(0) is per quote, decision 070). */
1920
- threshold: bigint;
1921
- /** The dead shares' income held for the next graduation, in the pad's quote. */
1922
- income: bigint;
1923
- /** This pad's creator share, recorded at its birth from the key's salt and never changed (decisions 056, 057, 067): a fraction of the income released. The rest deepens the bid; nothing is bought or burnt (067). */
1924
- creatorShare: bigint;
1925
- /** The income tax the dead shares pay on their own new income dividend (decisions 073, 085), WAD. */
1926
- incomeTaxRate: bigint;
1927
- /** The ranges the LOG Authority set on the policy NOW for the pads born after this read: what a new creator may choose. */
1928
- ranges: PadRanges;
1929
- }
1930
- | { kind: "pol"; /** The reserve a harvest leaves in the bid and a redeployment must keep, a multiple of L (WAD). */ minQuoteRatio: bigint; /** The income tax the pool's authority pays on its own new income dividend (decisions 073, 085), WAD. */ incomeTaxRate: bigint }
1931
- | {
1932
- kind: "sponsor";
1933
- /** The sponsor (`sponsor()`): the account allowed to create under the policy (the LOG's own instances: the LOG Authority of the day). */
1934
- sponsor: Address;
1935
- /** `salt` must be zero and the book uncapped (`NotCanonical`): the LOG's open instance. */
1936
- canonical: boolean;
1937
- /** The authority may gate swaps and mints (false on the open instance: a public pool can never be gated). */
1938
- gatesAvailable: boolean;
1939
- /** The pool is born with `GATE_SWAP` and its creator as operator. */
1940
- bornGated: boolean;
1941
- /** The swap-fee tiers a pool may be born with, a mask over the family's table (0: any fee in the manager's domain). */
1942
- swapTiers: bigint;
1943
- /** The mint-fee tiers, the same (0: any). */
1944
- mintTiers: bigint;
1945
- /** The pool's own state: the mint gate, the swap mode and the operator. */
1946
- gateMint: boolean;
1947
- swapMode: FPoolSwapMode;
1948
- operator: Address;
1949
- }
1950
- | { kind: "orphan" };
1951
-
1952
- /** The LOG Authority's range on a pad's creator choice (`PadPolicy`, decisions 056, 067), WAD fractions of the income released. */
1953
- export interface PadRanges {
1954
- creatorShareMin: bigint;
1955
- /** At most the F manager's `PAYEE_CUT_MAX` (50%), which bounds a pad's payee whatever the policy (067). */
1956
- creatorShareMax: bigint;
1976
+ /** The policy's immutables: the terms a holder reads before entering. */
1977
+ terms: FPolicyTerms;
1957
1978
  }
1958
1979
 
1959
- const MAX_U64 = (1n << 64n) - 1n;
1960
- const MAX_U128 = (1n << 128n) - 1n;
1961
-
1962
1980
  /**
1963
- * The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
1964
- * bits (a WAD fraction of the income), zero in the next 64 — the burn share's place before F version 28, refused by the policy if
1965
- * set — and a nonce in the low 128 that tells two otherwise identical pads apart. It is part of the pool's identity, so it is
1966
- * chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
1967
- */
1968
- export function padSalt(s: { creatorShare: bigint; nonce?: bigint; /** @deprecated F version 28 has no burn (067): only 0 is accepted. */ burnShare?: bigint }): Hex {
1969
- const nonce = s.nonce ?? 0n;
1970
- if (s.burnShare !== undefined && s.burnShare !== 0n) throw new Error("logswap: a pad has no burn share since F version 28 (decision 067)");
1971
- if (s.creatorShare < 0n || s.creatorShare > MAX_U64) throw new Error("logswap: a pad's creator share is a WAD fraction that fits 64 bits");
1972
- if (nonce < 0n || nonce > MAX_U128) throw new Error("logswap: a pad salt's nonce fits 128 bits");
1973
- return `0x${((s.creatorShare << 192n) | nonce).toString(16).padStart(64, "0")}` as Hex;
1974
- }
1975
-
1976
- /** The inverse of {@link padSalt}. `burnShare` is the old field's bits, nonzero only on a salt the F version 28 policy refuses. */
1977
- export function padSplitOfSalt(salt: Hex): { creatorShare: bigint; burnShare: bigint; nonce: bigint } {
1978
- const v = BigInt(salt);
1979
- return { creatorShare: v >> 192n, burnShare: (v >> 128n) & MAX_U64, nonce: v & MAX_U128 };
1980
- }
1981
-
1982
- /** The policy's terms for one pool, by its kind. */
1983
- export async function getFPoolRules(c: LogswapClient, s: Pick<FPoolState, "poolId" | "policy" | "kind" | "gen">, roles?: FPoolRoles): Promise<FPoolRules> {
1984
- const rd = <T>(abi: readonly unknown[], functionName: string, args: readonly unknown[] = []) =>
1985
- c.public.readContract({ address: s.policy, abi, functionName, args } as never) as Promise<T>;
1986
- switch (s.kind) {
1987
- case "pad": {
1988
- // the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
1989
- const gen = s.gen;
1990
- const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
1991
- rd<bigint | number>(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
1992
- fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
1993
- rd<bigint>(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
1994
- rd<bigint>(padPolicyAbi, "incomeTaxRate"),
1995
- rd<bigint>(padPolicyAbi, "creatorShareMin"),
1996
- rd<bigint>(padPolicyAbi, "creatorShareMax"),
1997
- ]);
1998
- const ranges: PadRanges = { creatorShareMin, creatorShareMax };
1999
- return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
2000
- }
2001
- case "pol": {
2002
- const [minQuoteRatio, incomeTaxRate] = await Promise.all([rd<bigint>(polPolicyAbi, "minQuoteRatio"), rd<bigint>(polPolicyAbi, "incomeTaxRate")]);
2003
- return { kind: "pol", minQuoteRatio, incomeTaxRate };
2004
- }
2005
- case "sponsor": {
2006
- const r = roles ?? (await getFPoolRoles(c, s.poolId, s));
2007
- const [sponsor, canonical, gatesAvailable, bornGated, swapTiers, mintTiers] = await Promise.all([
2008
- rd<Address>(sponsorPolicyFAbi, "sponsor"),
2009
- rd<boolean>(sponsorPolicyFAbi, "canonical"),
2010
- rd<boolean>(sponsorPolicyFAbi, "gatesAvailable"),
2011
- rd<boolean>(sponsorPolicyFAbi, "bornGated"),
2012
- rd<bigint>(sponsorPolicyFAbi, "swapTiers"),
2013
- rd<bigint>(sponsorPolicyFAbi, "mintTiers"),
2014
- ]);
2015
- return { kind: "sponsor", sponsor, canonical, gatesAvailable, bornGated, swapTiers, mintTiers, gateMint: r.gateMint, swapMode: r.swapMode, operator: r.operator };
2016
- }
2017
- case "orphan": {
2018
- return { kind: "orphan" };
2019
- }
2020
- }
2021
- }
2022
-
2023
- /**
2024
- * Every F pool `who` is the AUTHORITY of, across the policies — the policy page's list. The authority is `key.creator` for
2025
- * life (decision 098), so these are the pools `who` created, minus any the LOG orphaned. `pools` may be passed (from the
2026
- * indexer, say) to skip the log scan.
1981
+ * Every F pool `who` runs (its operator) or sponsors (the authority of its policy) — the policy page's list. `roles` tells
1982
+ * which. `pools` may be passed (from the indexer, say) to skip the log scan.
2027
1983
  */
2028
1984
  export async function fPoolsControlledBy(
2029
1985
  c: LogswapClient,
@@ -2031,20 +1987,15 @@ export async function fPoolsControlledBy(
2031
1987
  opts: { pools?: DiscoveredFPool[]; fromBlock?: bigint } = {},
2032
1988
  ): Promise<FPoolControlled[]> {
2033
1989
  const pools = opts.pools ?? (await discoverFPools(c, { fromBlock: opts.fromBlock }));
2034
- // the LIVE policy answers for the authority: a moved pool (046) is on another one than its birth's
2035
1990
  const states = await Promise.all(pools.map((p) => getFPool(c, p.poolId)));
2036
- const authorities = await Promise.all(
2037
- states.map((s) =>
2038
- c.public.readContract({ address: s.policy, abi: fPolicyBaseAbi, functionName: "authority", args: [s.poolId] } as never) as Promise<Address>,
2039
- ),
2040
- );
1991
+ const roles = await Promise.all(states.map((s) => getFPoolRoles(c, s.poolId, s)));
1992
+ const me = who.toLowerCase();
2041
1993
  const out: FPoolControlled[] = [];
2042
1994
  for (let i = 0; i < pools.length; ++i) {
2043
- if (authorities[i]!.toLowerCase() !== who.toLowerCase()) continue;
1995
+ const r = roles[i]!;
1996
+ if (r.operator.toLowerCase() !== me && r.authority.toLowerCase() !== me) continue;
2044
1997
  const state = states[i]!;
2045
- const roles = await getFPoolRoles(c, state.poolId, state);
2046
- const rules = await getFPoolRules(c, state, roles);
2047
- out.push({ pool: pools[i]!, roles, state, rules });
1998
+ out.push({ pool: pools[i]!, roles: r, state, terms: await fPolicyTermsOf(c, state.policy) });
2048
1999
  }
2049
2000
  return out;
2050
2001
  }
@@ -2092,18 +2043,6 @@ export async function fPoolShareHolders(
2092
2043
  .sort((a, b) => (b.shares > a.shares ? 1 : -1));
2093
2044
  }
2094
2045
 
2095
- /**
2096
- * What a policy answers `onRegenerate` with: `IFPolicy.Terms` — four words, exactly 128 bytes since F version 28 (decision 067
2097
- * removed `burn`). `carried` is the holder the next generation carries beside the dead shares; on a pad the manager requires
2098
- * `0xdead` and caps `toPayee` at `PAYEE_CUT_MAX` of the income.
2099
- */
2100
- export interface FPolicyTerms {
2101
- payee: Address;
2102
- toPayee: bigint;
2103
- protocolCut: bigint;
2104
- carried: Address;
2105
- }
2106
-
2107
2046
  /** 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). */
2108
2047
  export async function getFPoolsRaw(c: LogswapClient, poolIds: Hex[]): Promise<readonly unknown[]> {
2109
2048
  const { lensFAbi } = await import("./generated.js");