@logswap/sdk 0.5.90 → 0.5.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +136 -31
  2. package/dist/actions.js +4 -3
  3. package/dist/admin.d.ts +96 -925
  4. package/dist/admin.js +113 -194
  5. package/dist/chains.d.ts +13 -4
  6. package/dist/chains.js +22 -9
  7. package/dist/claims.d.ts +1 -1
  8. package/dist/claims.js +11 -9
  9. package/dist/client.d.ts +42 -20
  10. package/dist/client.js +86 -26
  11. package/dist/fees.d.ts +1 -1
  12. package/dist/fees.js +5 -4
  13. package/dist/fpool.d.ts +327 -1120
  14. package/dist/fpool.js +408 -475
  15. package/dist/generated.d.ts +5017 -7631
  16. package/dist/generated.js +3040 -4879
  17. package/dist/history.js +12 -14
  18. package/dist/index.d.ts +5 -7
  19. package/dist/index.js +5 -7
  20. package/dist/indexer.d.ts +2 -2
  21. package/dist/indexer.js +12 -9
  22. package/dist/keys.d.ts +15 -3
  23. package/dist/keys.js +5 -1
  24. package/dist/liquidity.d.ts +1 -1
  25. package/dist/liquidity.js +16 -9
  26. package/dist/onboard.d.ts +16 -11
  27. package/dist/onboard.js +27 -21
  28. package/dist/pools.d.ts +2 -0
  29. package/dist/pools.js +21 -13
  30. package/dist/positions.d.ts +1 -1
  31. package/dist/positions.js +18 -17
  32. package/dist/quote.d.ts +15 -0
  33. package/dist/quote.js +36 -0
  34. package/dist/swap.d.ts +7 -9
  35. package/dist/swap.js +40 -25
  36. package/dist/views.d.ts +1 -1
  37. package/dist/write.d.ts +7 -2
  38. package/dist/write.js +10 -7
  39. package/package.json +3 -3
  40. package/src/actions.ts +4 -3
  41. package/src/admin.ts +143 -249
  42. package/src/chains.ts +32 -13
  43. package/src/claims.ts +11 -10
  44. package/src/client.ts +111 -39
  45. package/src/fees.ts +6 -6
  46. package/src/fpool.ts +555 -648
  47. package/src/generated.ts +3063 -4904
  48. package/src/history.ts +11 -11
  49. package/src/index.ts +5 -7
  50. package/src/indexer.ts +13 -11
  51. package/src/keys.ts +19 -3
  52. package/src/liquidity.ts +16 -10
  53. package/src/onboard.ts +29 -21
  54. package/src/pools.ts +23 -15
  55. package/src/positions.ts +18 -18
  56. package/src/quote.ts +36 -0
  57. package/src/swap.ts +46 -25
  58. package/src/views.ts +1 -2
  59. package/src/write.ts +11 -10
package/dist/fpool.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * fpool.ts — the `FPoolManager` surface: n bases, one quote, one shared floor.
2
+ * fpool.ts — the `ManagerF` surface: n bases, one quote, one shared floor.
3
3
  *
4
- * The other primitive. `CPoolManager` gives every position its own floor on a tick ladder;
5
- * `FPoolManager` gives every share the SAME floor and deletes the ladder, the accumulators and the
4
+ * The other primitive. `ManagerC` gives every position its own floor on a tick ladder;
5
+ * `ManagerF` gives every share the SAME floor and deletes the ladder, the accumulators and the
6
6
  * per-position accounting with it. Reading the two side by side is the fastest way to understand
7
7
  * either.
8
8
  *
@@ -18,65 +18,66 @@
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, operator, gate or list: it asks the pool's policy `may(who, action)` and acts on the
23
- * answer. So `getFPool` carries the policy and what it declared, {@link getFPoolRoles} reads the
24
- * roles FROM the policy, and every role write — the handover, the operator, the gates, the list —
25
- * is a write to the policy ({@link fPoolProposeAuthority}, {@link fPoolSetGates}, …).
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.
26
31
  *
27
- * **Zaps live on the ROUTER, not here.** Permit2 is AllowanceTransfer mode, whose standing
28
- * allowance is keyed by spender, so a second router would cost the user an allowance per token
29
- * twice, forever. One router is one spender — see `fPoolZapIn`/`fPoolZapOut` below, which target
30
- * `addresses.router`.
32
+ * **Zaps live on the ROUTER, not here.** `RouterF` is F's own router and its own Permit2 spender (decision 096: one
33
+ * router per manager; a second spender is a second signature, not a second on-chain approval). See
34
+ * `fPoolZapIn`/`fPoolZapOut` below, which target `addresses.routerF`; a wallet's Permit2 allowance for it is
35
+ * `onboardToken(c, "F", token, need)`.
31
36
  */
32
- import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256, toFunctionSelector } from "viem";
33
- import { fPoolManagerAbi, lensAbi, routerAbi, padPolicyAbi, polPolicyAbi, policyRegistryAbi, privatePolicyAbi, publicPolicyAbi } from "./generated.js";
37
+ import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256 } from "viem";
38
+ import { managerFAbi, lensFAbi, routerFAbi, policyFAbi, policyRegistryAbi } from "./generated.js";
34
39
  /**
35
- * One contract, one ABI (F version 12): `harvest`, `claim`, `retire`, `regenerate`,
36
- * `setLegs`, the names, the fee parameters are `FPoolManager`'s own code. The roles left it for
37
- * the policies in F version 15: {@link fPolicyBaseAbi} is what every policy shares,
38
- * {@link privatePolicyAbi} the desk's, {@link padPolicyAbi} / {@link polPolicyAbi} / {@link publicPolicyAbi}
39
- * the kinds'.
40
+ * One contract, one ABI (F version 12): `harvest`, `claim`, `close`, `deployLiquidity`, the fee list are `ManagerF`'s own
41
+ * code. The roles left it for the policy in F version 15; since F 41 there is one policy contract, {@link policyFAbi}
42
+ * (`PolicyF`, policy.md): every F pool's operator, gate modes and lists.
40
43
  */
41
- export { fPoolManagerAbi, padPolicyAbi, polPolicyAbi, privatePolicyAbi, publicPolicyAbi };
42
- /**
43
- * What every protocol policy shares (`FPolicyBase`): the roles and their handover and the
44
- * `maxHarvest` readout (a harvest has no cut, decisions 056). `polPolicyAbi` is a superset of it and carries nothing that collides, so it stands
45
- * in for the base — a call through it to any of the four policies decodes the base's functions.
46
- */
47
- export const fPolicyBaseAbi = polPolicyAbi;
44
+ export { managerFAbi, policyFAbi };
48
45
  import { clientChainId } from "./client.js";
46
+ import { findQuoteResult } from "./quote.js";
49
47
  import { fallBackUnlessRejected, signerFor } from "./write.js";
50
48
  import { getEventLogs } from "./history.js";
51
49
  import { poolHolders } from "./views.js";
52
- import { presetMintFee } from "./positions.js";
53
- import { isValidMintFee, MINT_FEE_MAX } from "./keys.js";
54
50
  const WAD = 10n ** 18n;
55
51
  const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
56
- /** The optional questions a policy declared at birth, as bits of `Pool.asks`. */
57
- export const ASK_SWAP = 1;
58
- export const ASK_MINT = 2;
52
+ /**
53
+ * The bits a policy declares at birth, in `Pool.flags` (decision 098; `ASK_SWAP` / `ASK_MINT` before): with a gate bit off nothing is
54
+ * asked; with it on the manager admits the cached operator with no policy call and asks the policy about everyone else.
55
+ */
56
+ export const GATE_SWAP = 1;
57
+ export const GATE_MINT = 2;
58
+ /** `GATE_SWAP | GATE_MINT`: the bits `setGates` carries (`SEED_TO_DEAD` is the birth's alone). */
59
+ export const GATES = GATE_SWAP | GATE_MINT;
59
60
  /**
60
61
  * The lens's raw F pool struct — what the manager's `getPool` returned. Since F version 25 the
61
62
  * manager's typed views are behind `extsload` (decisions 062) and the lens reads them; one call.
62
63
  */
63
64
  async function rawFPool(c, poolId) {
64
65
  const [p] = await c.public.readContract({
65
- address: c.addresses.lens,
66
- abi: lensAbi,
67
- functionName: "getFPools",
66
+ address: c.addresses.lensF,
67
+ abi: lensFAbi,
68
+ functionName: "getPools",
68
69
  args: [[poolId]],
69
70
  });
70
71
  if (!p || /^0x0{40}$/i.test(p.quote))
71
72
  throw new Error(`logswap: no F pool with id ${poolId}`);
72
73
  return p;
73
74
  }
74
- /** Read a basket pool whole: one lens call (`fPool`, F version 25) plus the policy's kind and name. */
75
+ /** 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}. */
75
76
  export async function getFPool(c, poolId) {
76
77
  const v = await c.public.readContract({
77
- address: c.addresses.lens,
78
- abi: lensAbi,
79
- functionName: "fPool",
78
+ address: c.addresses.lensF,
79
+ abi: lensFAbi,
80
+ functionName: "pool",
80
81
  args: [poolId],
81
82
  });
82
83
  const p = v.pool;
@@ -87,7 +88,7 @@ export async function getFPool(c, poolId) {
87
88
  // cannot be a check on `seeded`.
88
89
  if (/^0x0{40}$/i.test(p.quote))
89
90
  throw new Error(`logswap: no F pool with id ${poolId}`);
90
- const [kind, name] = await Promise.all([fPoolKindOfPolicy(c, p.policy), fPoolNameOf(c, poolId, p.policy)]);
91
+ const kind = await fPoolKindOfPolicy(c, p.policy);
91
92
  return {
92
93
  poolId,
93
94
  quote: p.quote,
@@ -105,8 +106,8 @@ export async function getFPool(c, poolId) {
105
106
  lnCapOverSeed: Number(p.lnCapOverSeed),
106
107
  realizedVariance: p.realizedVariance,
107
108
  policy: p.policy,
108
- asks: Number(p.asks),
109
- name,
109
+ flags: Number(p.flags),
110
+ operator: p.operator,
110
111
  restructureTime: Number(p.restructureTime),
111
112
  kind,
112
113
  seeded: p.seeded,
@@ -117,80 +118,132 @@ export async function getFPool(c, poolId) {
117
118
  kappa: v.baseAssets.map((l) => l.kappa),
118
119
  };
119
120
  }
120
- const F_KIND_NAMES = ["public", "private", "pol", "pad"];
121
- /** The policy's birth-time declaration that the seed's shares are the pool's (a pad's), in `asks`. */
121
+ /** The policy's birth-time declaration that the deploy's shares are the pool's (`seedToDead`, a pad's), in `flags`. */
122
122
  export const SEED_TO_DEAD = 4;
123
- const kindCache = new Map();
123
+ const termsCache = new Map();
124
+ /** The label a policy's terms spell (see {@link FPoolKind}). Pure. */
125
+ export function fPolicyKindOf(t) {
126
+ if (t.open)
127
+ return "public";
128
+ if (t.seedToDead)
129
+ return "pad";
130
+ if (t.quoteBuffer > 0n)
131
+ return "pol";
132
+ return "desk";
133
+ }
124
134
  /**
125
- * What a policy IS — its `kind()` tag, read once per policy address and cached for the client's
126
- * chain: a pool's kind is its policy's word, never the manager's. An unknown tag
127
- * (a policy that is not one of the protocol's four shapes) throws; the app has no screen for it.
135
+ * A policy's terms, read once per policy address and cached for the client's chain (the policies sit at one address on
136
+ * every release chain): every field is an immutable, so the first read is the last. A failed read is not cached.
128
137
  */
129
- export async function fPoolKindOfPolicy(c, policy) {
130
- // the chain id is part of the key: the policies sit at one address on every release chain
138
+ export async function fPolicyTermsOf(c, policy) {
131
139
  const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
132
- let hit = kindCache.get(key);
140
+ let hit = termsCache.get(key);
133
141
  if (!hit) {
134
- hit = c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "kind" }).then((word) => {
135
- const tag = bytes32ToText(word);
136
- if (!F_KIND_NAMES.includes(tag))
137
- throw new Error(`logswap: policy ${policy} says it is "${tag}", which is no kind this SDK knows`);
138
- return tag;
142
+ const rd = (functionName) => c.public.readContract({ address: policy, abi: policyFAbi, functionName });
143
+ hit = Promise.all([
144
+ rd("fixedAuthority"),
145
+ rd("open"),
146
+ rd("seedToDead"),
147
+ rd("incomeHarvestOnly"),
148
+ rd("incomeTaxRate"),
149
+ rd("feeMask"),
150
+ rd("lenMax"),
151
+ rd("lnCapMin"),
152
+ rd("quoteBuffer"),
153
+ rd("quoteCurated"),
154
+ rd("baseCurated"),
155
+ ]).then(([fixedAuthority, open, seedToDead, incomeHarvestOnly, incomeTaxRate, feeMask, lenMax, lnCapMin, quoteBuffer, quoteCurated, baseCurated]) => {
156
+ const t = {
157
+ policy,
158
+ fixedAuthority,
159
+ open,
160
+ seedToDead,
161
+ incomeHarvestOnly,
162
+ incomeTaxRate,
163
+ feeMask: Number(feeMask),
164
+ lenMax: Number(lenMax),
165
+ lnCapMin: Number(lnCapMin),
166
+ quoteBuffer,
167
+ quoteCurated,
168
+ baseCurated,
169
+ };
170
+ return { ...t, kind: fPolicyKindOf(t) };
139
171
  });
140
- kindCache.set(key, hit);
141
- hit.catch(() => kindCache.delete(key)); // a failed read is not a fact
172
+ termsCache.set(key, hit);
173
+ hit.catch(() => termsCache.delete(key)); // a failed read is not a fact
142
174
  }
143
175
  return hit;
144
176
  }
145
- /** The pool's label, as its policy holds it. "" when unnamed. */
146
- export async function fPoolNameOf(c, poolId, policy) {
147
- const p = policy ?? (await fPoolPolicyOf(c, poolId));
148
- const word = (await c.public.readContract({ address: p, abi: fPolicyBaseAbi, functionName: "nameOf", args: [poolId] }));
149
- return bytes32ToText(word);
177
+ /** What a policy IS, as a label: {@link fPolicyTermsOf}'s `kind`. One read per policy address, cached. */
178
+ export async function fPoolKindOfPolicy(c, policy) {
179
+ return (await fPolicyTermsOf(c, policy)).kind;
180
+ }
181
+ /**
182
+ * The pool's label — the last `NameSet` its policy emitted for it: the operator's word, mutable, never identity. Nothing is
183
+ * stored on chain (policy.md §4.3), so this is a log query — pass `indexer`, or set the client's. "" when never named.
184
+ */
185
+ export async function fPoolNameOf(c, poolId, opts = {}) {
186
+ const policy = opts.policy ?? (await fPoolPolicyOf(c, poolId));
187
+ const ev = policyFAbi.find((x) => x.type === "event" && x.name === "NameSet");
188
+ if (!ev)
189
+ throw new Error("logswap: NameSet event missing from the generated ABI");
190
+ const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: policy, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
191
+ const last = logs[logs.length - 1];
192
+ return last ? bytes32ToText(last.args.name) : "";
150
193
  }
151
- /** The deployment's policy for a kind: the protocol's policy that IS that kind. */
152
- export function fPoolPolicyFor(c, kind) {
194
+ /** The deployment's policy for a slot — the one a key names when no `policy` is given. */
195
+ export function fPoolPolicyFor(c, slot) {
153
196
  const a = c.addresses;
154
- const policy = kind === "public" ? a.publicPolicy : kind === "private" ? a.privatePolicy : kind === "pol" ? a.polPolicy : a.padPolicy;
197
+ const policy = slot === "public" ? a.publicPolicy : slot === "private" ? a.privatePolicy : slot === "pol" ? a.polPolicy : a.padPolicy;
155
198
  if (!policy)
156
- throw new Error(`logswap: this deployment carries no ${kind} policy`);
199
+ throw new Error(`logswap: this deployment carries no ${slot} policy`);
157
200
  return policy;
158
201
  }
159
202
  /** The policy a pool named in its key — one read; {@link getFPool} carries it too. */
160
203
  export async function fPoolPolicyOf(c, poolId) {
161
204
  return (await rawFPool(c, poolId)).policy;
162
205
  }
163
- const SWAP_MODES = ["open", "listed", "executor"];
164
- /** Read a pool's roles from its policy. `state` saves the `getPool` round trip when already in hand. */
206
+ const MODES = ["open", "listed", "operator"];
207
+ /** The gate modes in `IPolicyF.Mode` order — the index is the on-chain ordinal. */
208
+ export const fPoolModes = MODES;
209
+ /** Read a pool's roles from its policy. `state` saves the `getPool` round trip when the policy is already in hand. */
165
210
  export async function getFPoolRoles(c, poolId, state) {
166
- const s = state ?? (await getFPool(c, poolId));
167
- const rdPolicy = (abi, functionName) => c.public.readContract({ address: s.policy, abi, functionName, args: [poolId] });
168
- const [creator, authority, pendingAuthority, maxHarvest] = await Promise.all([
169
- rdPolicy(fPolicyBaseAbi, "creator"),
170
- rdPolicy(fPolicyBaseAbi, "authority"),
171
- rdPolicy(fPolicyBaseAbi, "pendingAuthority"),
172
- rdPolicy(fPolicyBaseAbi, "maxHarvest"),
211
+ const policy = state?.policy ?? (await fPoolPolicyOf(c, poolId));
212
+ const rd = (functionName, args = []) => c.public.readContract({ address: policy, abi: policyFAbi, functionName, args });
213
+ const [authority, operator, swap, mint] = await Promise.all([
214
+ rd("authority"),
215
+ rd("operator", [poolId]),
216
+ rd("swapMode", [poolId]),
217
+ rd("mintMode", [poolId]),
173
218
  ]);
174
- const desk = s.kind === "private";
175
- const permissions = desk
176
- ? (await c.public.readContract({ address: s.policy, abi: privatePolicyAbi, functionName: "permissionsOf", args: [poolId] }))
177
- : undefined;
178
- const [mode, swapExecutor, gateMint, , operator] = permissions ?? [0, ZERO_ADDRESS, false, ZERO_ADDRESS, ZERO_ADDRESS];
179
- return { policy: s.policy, creator, authority, pendingAuthority, operator, gateMint, swapMode: SWAP_MODES[Number(mode)] ?? "open", swapExecutor, maxHarvest };
219
+ return { policy, authority, operator, swapMode: MODES[Number(swap)] ?? "open", mintMode: MODES[Number(mint)] ?? "open" };
220
+ }
221
+ /**
222
+ * What a harvest may take now (policy.md §9): the income `I = min(unharvested, Q)` always; capital on top of it up to
223
+ * `Q − I − quoteBuffer·L` (`QuoteTooThin` past it), none where the policy is income-only (`IncomeOnly`) or the pool a pad
224
+ * (`SEED_TO_DEAD`: the manager's own rule, `HarvestLimit`). Nothing on an unfunded pool.
225
+ */
226
+ export function fPoolHarvestRoom(s, t) {
227
+ if (s.L === 0n)
228
+ return { income: 0n, capital: 0n };
229
+ const income = s.unharvested < s.Q ? s.unharvested : s.Q;
230
+ if (t.incomeHarvestOnly || (s.flags & SEED_TO_DEAD) !== 0)
231
+ return { income, capital: 0n };
232
+ const keep = income + (s.L * t.quoteBuffer + WAD - 1n) / WAD; // `mulWadUp`, as the policy rounds
233
+ return { income, capital: s.Q > keep ? s.Q - keep : 0n };
180
234
  }
181
235
  export async function describeFPool(c, s) {
182
- // an unfunded pool has no L: nothing earned, nothing to harvest, no income. The bid is the
183
- // manager's ceiling (`harvestable()` until F version 21, which cut the getter): Q once seeded.
184
- const harvestable = s.L > 0n ? s.Q : 0n;
185
- const unharvested = s.L > 0n ? s.unharvested : 0n;
186
- const income = s.L > 0n ? await fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, s.gen) : 0n;
236
+ // an unfunded pool has no L: nothing earned, nothing to harvest
237
+ const terms = await fPolicyTermsOf(c, s.policy);
238
+ const { income, capital } = fPoolHarvestRoom(s, terms);
187
239
  return {
188
- shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
240
+ shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
189
241
  legs: s.bases.length,
190
242
  atFloor: s.Q === 0n,
191
- unharvested,
192
- harvestable,
243
+ unharvested: s.L > 0n ? s.unharvested : 0n,
193
244
  income,
245
+ capitalRoom: capital,
246
+ harvestable: income + capital,
194
247
  };
195
248
  }
196
249
  /** `p_j = e^{x_j}`, lossy the way any float conversion is. Compare in log space when it matters. */
@@ -282,11 +335,11 @@ export function fPoolPreviewMintQuote(st, dL) {
282
335
  * and expect change back — do not treat it as exact.
283
336
  */
284
337
  export async function fPoolPreviewZapIn(c, poolId, dL) {
285
- // read-only lives on the LENS (the router's F flows moved to a facet; its previews came here)
286
- const { lensAbi } = await import("./generated.js");
338
+ // read-only lives on the LENS (LensF: the previews)
339
+ const { lensFAbi } = await import("./generated.js");
287
340
  return c.public.readContract({
288
- address: c.addresses.lens,
289
- abi: lensAbi,
341
+ address: c.addresses.lensF,
342
+ abi: lensFAbi,
290
343
  functionName: "previewZapIn",
291
344
  args: [poolId, dL],
292
345
  });
@@ -324,8 +377,8 @@ a) {
324
377
  */
325
378
  export async function fPoolPreviewZapOut(c, a) {
326
379
  const { result } = await c.public.simulateContract({
327
- address: c.addresses.router,
328
- abi: routerAbi,
380
+ address: c.addresses.routerF,
381
+ abi: routerFAbi,
329
382
  functionName: "zapOut",
330
383
  args: [a.poolId, a.shares, a.tokenOut, 0n, a.account, defaultDeadline()],
331
384
  account: a.account,
@@ -354,26 +407,28 @@ export async function fPoolRollIn(c, a) {
354
407
  * seed.
355
408
  */
356
409
  export async function fPoolPreviewRollIn(c, poolId, gen, holder, shares) {
357
- const { lensAbi } = await import("./generated.js");
410
+ const { lensFAbi } = await import("./generated.js");
358
411
  const [dL, quoteShort, quoteExcess] = (await c.public.readContract({
359
- address: c.addresses.lens,
360
- abi: lensAbi,
412
+ address: c.addresses.lensF,
413
+ abi: lensFAbi,
361
414
  functionName: "previewRollIn",
362
415
  args: [poolId, BigInt(gen), holder, shares],
363
416
  }));
364
417
  return { dL, quoteShort, quoteExcess };
365
418
  }
366
- // ─── the floor lever (authority only) ─────────────────────────────────────────
419
+ // ─── the floor lever (the operator's) ─────────────────────────────────────────
367
420
  /**
368
- * Remove quote, lifting logFloor — price-neutral, no base moves, and a DIVIDEND to
369
- * every share: the amount goes into the pool's held income and each holder's slice is settled lazily on
370
- * their next transfer, mint or burn, or pulled with {@link fPoolClaim}. The sponsor's own slice —
371
- * its shares' and the locked seed's at 0xdead — is pushed to `to` at once. On a pad
372
- * the lift stops at the seed floor, refLogFloor (income only); nothing else bounds it — an
373
- * unlocked pool's authority may take Q to zero.
421
+ * Harvest (policy.md §9): take this generation's income — `L·(refLogFloor − logFloor)`, the fees since the floor was last
422
+ * referenced — and `extra` of capital on top of it, out of the bid; price-neutral, no base moves. Both accrue as a DIVIDEND to
423
+ * every share, settled lazily on each holder's next transfer, mint or burn or pulled with {@link fPoolClaim}; the income is taxed
424
+ * 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`.
425
+ * The operator's own settled dividend — this harvest's and anything pending — is paid to `to` in the same call: one transaction,
426
+ * and the operator (usually a contract) routes the payout through `to`. The operator's alone (`NotOperator`). `extra` must fit the
427
+ * room ({@link fPoolHarvestRoom}): 0 on a pad (`HarvestLimit`) and under an income-only policy (`IncomeOnly`), within the buffer
428
+ * otherwise (`QuoteTooThin`).
374
429
  */
375
430
  export async function fPoolHarvest(c, a) {
376
- return writeFPool(c, a.poolId, "harvest", [a.amount, a.to ?? a.account], a.account);
431
+ return writeFPool(c, a.poolId, "harvest", [a.extra ?? 0n, a.to ?? a.account], a.account);
377
432
  }
378
433
  /**
379
434
  * Pull one's settled dividend on a generation's shares without moving them;
@@ -392,9 +447,9 @@ export async function fPoolClaim(c, a) {
392
447
  export async function fPoolDividendOf(c, poolId, holder, gen) {
393
448
  const g = gen ?? (await fPoolGen(c, poolId));
394
449
  return c.public.readContract({
395
- address: c.addresses.lens,
396
- abi: lensAbi,
397
- functionName: "fDividendOf",
450
+ address: c.addresses.lensF,
451
+ abi: lensFAbi,
452
+ functionName: "dividendOf",
398
453
  args: [poolId, BigInt(g), holder],
399
454
  });
400
455
  }
@@ -406,9 +461,9 @@ export async function fPoolDividendOf(c, poolId, holder, gen) {
406
461
  export async function fPoolLienOf(c, poolId, owner, gen) {
407
462
  const g = gen ?? (await fPoolGen(c, poolId));
408
463
  const [locker, amount, owed] = await c.public.readContract({
409
- address: c.addresses.lens,
410
- abi: lensAbi,
411
- functionName: "fLienOf",
464
+ address: c.addresses.lensF,
465
+ abi: lensFAbi,
466
+ functionName: "lienOf",
412
467
  args: [fPoolShareId(poolId, g), owner],
413
468
  });
414
469
  return { locker, amount, owed };
@@ -453,8 +508,8 @@ function requireWallet(c) {
453
508
  async function writeFPool(c, poolId, functionName, args, account) {
454
509
  const wallet = requireWallet(c);
455
510
  const { request } = await c.public.simulateContract({
456
- address: c.addresses.fPoolManager,
457
- abi: fPoolManagerAbi,
511
+ address: c.addresses.managerF,
512
+ abi: managerFAbi,
458
513
  functionName,
459
514
  // Every manager write is keyed by poolId as its FIRST parameter; prepending it here, in the
460
515
  // one place all seven helpers share, is what keeps a caller from ever omitting it. The `as
@@ -468,8 +523,8 @@ async function writeFPool(c, poolId, functionName, args, account) {
468
523
  async function writeFPool0(c, functionName, args, account) {
469
524
  const wallet = requireWallet(c);
470
525
  const { request } = await c.public.simulateContract({
471
- address: c.addresses.fPoolManager,
472
- abi: fPoolManagerAbi,
526
+ address: c.addresses.managerF,
527
+ abi: managerFAbi,
473
528
  functionName,
474
529
  args,
475
530
  account: signerFor(c, account),
@@ -484,17 +539,17 @@ pullTokens = []) {
484
539
  let sendArgs = args;
485
540
  if (pullTokens.length) {
486
541
  const { permit2SigCalls } = await import("./onboard.js");
487
- const sigCalls = await permit2SigCalls(c, pullTokens).catch(fallBackUnlessRejected);
542
+ const sigCalls = await permit2SigCalls(c, "F", pullTokens).catch(fallBackUnlessRejected);
488
543
  if (sigCalls.length) {
489
544
  const { encodeFunctionData } = await import("viem");
490
- const inner = encodeFunctionData({ abi: routerAbi, functionName, args });
545
+ const inner = encodeFunctionData({ abi: routerFAbi, functionName, args });
491
546
  fn = "multicall";
492
547
  sendArgs = [[...sigCalls, inner]];
493
548
  }
494
549
  }
495
550
  const { request } = await c.public.simulateContract({
496
- address: c.addresses.router,
497
- abi: routerAbi,
551
+ address: c.addresses.routerF,
552
+ abi: routerFAbi,
498
553
  functionName: fn,
499
554
  args: sendArgs,
500
555
  account: signerFor(c, account),
@@ -515,7 +570,7 @@ export async function approveTokenForFPoolManager(c, token) {
515
570
  address: token,
516
571
  abi: [{ type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "s", type: "address" }, { name: "a", type: "uint256" }], outputs: [{ type: "bool" }] }],
517
572
  functionName: "approve",
518
- args: [c.addresses.fPoolManager, (1n << 256n) - 1n],
573
+ args: [c.addresses.managerF, (1n << 256n) - 1n],
519
574
  account: wallet.account,
520
575
  chain: c.wallet.chain,
521
576
  });
@@ -526,7 +581,7 @@ export async function fPoolManagerAllowanceOk(c, token, owner, need) {
526
581
  address: token,
527
582
  abi: [{ type: "function", name: "allowance", stateMutability: "view", inputs: [{ name: "o", type: "address" }, { name: "s", type: "address" }], outputs: [{ type: "uint256" }] }],
528
583
  functionName: "allowance",
529
- args: [owner, c.addresses.fPoolManager],
584
+ args: [owner, c.addresses.managerF],
530
585
  }));
531
586
  return allowance >= need;
532
587
  }
@@ -538,20 +593,20 @@ export async function fPoolManagerAllowanceOk(c, token, owner, need) {
538
593
  // first `fPoolZapOut` revert with something unreadable.
539
594
  export async function isRouterOperatorForFPool(c, owner) {
540
595
  return c.public.readContract({
541
- address: c.addresses.fPoolManager,
542
- abi: fPoolManagerAbi,
596
+ address: c.addresses.managerF,
597
+ abi: managerFAbi,
543
598
  functionName: "isOperator",
544
- args: [owner, c.addresses.router],
599
+ args: [owner, c.addresses.routerF],
545
600
  });
546
601
  }
547
602
  /** Approve the router to move this account's F-pool shares. Needed once, before any `fPoolZapOut`. */
548
603
  export async function approveRouterForFPool(c, account) {
549
604
  const wallet = requireWallet(c);
550
605
  const { request } = await c.public.simulateContract({
551
- address: c.addresses.fPoolManager,
552
- abi: fPoolManagerAbi,
606
+ address: c.addresses.managerF,
607
+ abi: managerFAbi,
553
608
  functionName: "setOperator",
554
- args: [c.addresses.router, true],
609
+ args: [c.addresses.routerF, true],
555
610
  account: signerFor(c, account),
556
611
  });
557
612
  return wallet.writeContract(request);
@@ -585,8 +640,8 @@ export function fPoolClaimId(token) {
585
640
  export async function fPoolShareBalance(c, poolId, owner, gen) {
586
641
  const g = gen ?? (await fPoolGen(c, poolId));
587
642
  return c.public.readContract({
588
- address: c.addresses.fPoolManager,
589
- abi: fPoolManagerAbi,
643
+ address: c.addresses.managerF,
644
+ abi: managerFAbi,
590
645
  functionName: "balanceOf",
591
646
  args: [owner, fPoolShareId(poolId, g)],
592
647
  });
@@ -594,20 +649,20 @@ export async function fPoolShareBalance(c, poolId, owner, gen) {
594
649
  /** A retired generation's bundle: what is left to redeem — supply, quote, base per leg index. */
595
650
  export async function fPoolBundleOf(c, poolId, gen) {
596
651
  const [supply, quote, base] = await c.public.readContract({
597
- address: c.addresses.lens,
598
- abi: lensAbi,
599
- functionName: "fBundleOf",
652
+ address: c.addresses.lensF,
653
+ abi: lensFAbi,
654
+ functionName: "bundleOf",
600
655
  args: [poolId, BigInt(gen)],
601
656
  });
602
657
  return { supply, quote, base: [...base] };
603
658
  }
604
659
  /** A holder's claims on a pool's retired generations — one row per generation still held. */
605
660
  export async function fPoolClaimsOf(c, poolId, owner) {
606
- const { lensAbi } = await import("./generated.js");
661
+ const { lensFAbi } = await import("./generated.js");
607
662
  const rows = (await c.public.readContract({
608
- address: c.addresses.lens,
609
- abi: lensAbi,
610
- functionName: "fClaimsOf",
663
+ address: c.addresses.lensF,
664
+ abi: lensFAbi,
665
+ functionName: "claimsOf",
611
666
  args: [poolId, owner],
612
667
  }));
613
668
  return rows.map((r) => ({ gen: Number(r.gen), shares: r.shares, base: [...r.base], quote: r.quote, dividend: r.dividend }));
@@ -622,8 +677,8 @@ export async function fPoolRedeem(c, a) {
622
677
  }
623
678
  export async function fPoolClaimBalance(c, token, owner) {
624
679
  return c.public.readContract({
625
- address: c.addresses.fPoolManager,
626
- abi: fPoolManagerAbi,
680
+ address: c.addresses.managerF,
681
+ abi: managerFAbi,
627
682
  functionName: "balanceOf",
628
683
  args: [owner, fPoolClaimId(token)],
629
684
  });
@@ -646,8 +701,8 @@ export var FPoolQuoteKind;
646
701
  export async function fPoolQuoteSwap(c, a) {
647
702
  try {
648
703
  await c.public.simulateContract({
649
- address: c.addresses.router,
650
- abi: routerAbi,
704
+ address: c.addresses.routerF,
705
+ abi: routerFAbi,
651
706
  functionName: "quoteSwap",
652
707
  // the taker matters only on a gated pool: the connected account, or the zero address
653
708
  args: [a.poolId, a.kind, BigInt(a.j), BigInt(a.k ?? 0), a.amountIn, a.taker ?? c.wallet?.account?.address ?? ZERO_ADDRESS],
@@ -661,35 +716,55 @@ export async function fPoolQuoteSwap(c, a) {
661
716
  }
662
717
  throw new Error("logswap: quoteSwap returned without reverting, which it must never do");
663
718
  }
664
- /**
665
- * `QuoteResult(uint256)` — selector then one word. viem nests the revert data several layers deep
666
- * depending on the transport, so walk for it rather than guessing the shape.
667
- *
668
- * The selector is DERIVED, not written down. A hardcoded one is wrong silently: the decode simply
669
- * never matches and every quote rethrows as if the swap had failed.
670
- */
671
- function findQuoteResult(err) {
672
- const SELECTOR = toFunctionSelector("QuoteResult(uint256)");
673
- const seen = new Set();
674
- const walk = (e) => {
675
- if (!e || typeof e !== "object" || seen.has(e))
676
- return null;
677
- seen.add(e);
678
- const anyE = e;
679
- const data = anyE.data;
680
- if (typeof data === "string" && data.startsWith(SELECTOR) && data.length >= 10 + 64) {
681
- return BigInt("0x" + data.slice(10, 10 + 64));
682
- }
683
- for (const k of ["cause", "walk", "error", "details"]) {
684
- const found = walk(anyE[k]);
685
- if (found !== null)
686
- return found;
687
- }
688
- return null;
689
- };
690
- return walk(err);
691
- }
692
719
  const ZERO_SALT = `0x${"0".repeat(64)}`;
720
+ // ─── the fee list (policy.md §6) ──────────────────────────────────────────────
721
+ /** `FeeParams.FEE_LIST` in bp: the eight swap fees an F pool may be born with. The key carries the index. */
722
+ export const F_FEE_LIST_BP = [1, 2, 5, 10, 20, 50, 100, 200];
723
+ /** The list in WAD (1 bp = 1e14). No zero: the fee-free pool cannot be born. */
724
+ export const F_FEE_LIST = F_FEE_LIST_BP.map((bp) => BigInt(bp) * 10n ** 14n);
725
+ /** The fee at `idx` of the list, WAD. Throws off the list. */
726
+ export function fFeeOf(idx) {
727
+ const fee = Number.isInteger(idx) ? F_FEE_LIST[idx] : undefined;
728
+ if (fee === undefined)
729
+ throw new Error(`logswap: swap fee index ${idx} is off the F fee list (0..${F_FEE_LIST.length - 1})`);
730
+ return fee;
731
+ }
732
+ /** 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). */
733
+ export function fMintFeeIdxOf(swapFeeIdx) {
734
+ fFeeOf(swapFeeIdx);
735
+ return Math.min(swapFeeIdx + 1, F_FEE_LIST.length - 1);
736
+ }
737
+ /** The mint fee, WAD of newly-minted L, a pool born at `swapFeeIdx` charges on outside mints. */
738
+ export function fMintFeeOf(swapFeeIdx) {
739
+ return fFeeOf(fMintFeeIdxOf(swapFeeIdx));
740
+ }
741
+ /** 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. */
742
+ export function fFeeIndexOf(fee) {
743
+ const idx = F_FEE_LIST.indexOf(fee);
744
+ if (idx < 0)
745
+ throw new Error(`logswap: swap fee ${fee} is not on the F fee list (${F_FEE_LIST_BP.join(", ")} bp)`);
746
+ return idx;
747
+ }
748
+ /** Whether a policy's `feeMask` admits `idx`: a bit per index, an empty mask admitting all eight. */
749
+ export function fFeeListed(feeMask, idx) {
750
+ return Number.isInteger(idx) && idx >= 0 && idx < F_FEE_LIST.length && (feeMask === 0 || ((feeMask >> idx) & 1) === 1);
751
+ }
752
+ /** The indices a policy's `feeMask` admits, ascending. */
753
+ export function fFeesAllowed(feeMask) {
754
+ return F_FEE_LIST.map((_, i) => i).filter((i) => fFeeListed(feeMask, i));
755
+ }
756
+ /** The swap fee index of create arguments given either way; both given must agree. */
757
+ export function fPoolSwapFeeIdxOf(a) {
758
+ if (a.swapFeeIdx !== undefined) {
759
+ const fee = fFeeOf(a.swapFeeIdx);
760
+ if (a.swapFee !== undefined && a.swapFee !== fee)
761
+ throw new Error(`logswap: swap fee ${a.swapFee} is not the F fee list's entry ${a.swapFeeIdx} (${fee})`);
762
+ return a.swapFeeIdx;
763
+ }
764
+ if (a.swapFee !== undefined)
765
+ return fFeeIndexOf(a.swapFee);
766
+ throw new Error("logswap: an F pool needs its swap fee — `swapFeeIdx` (into the list) or `swapFee` (WAD, on the list)");
767
+ }
693
768
  /** `bytes32` ⇄ short UTF-8 text, for the pool and sponsor labels. */
694
769
  export function textToBytes32(text) {
695
770
  const b = new TextEncoder().encode(text);
@@ -711,52 +786,45 @@ export function sortFPoolLegs(bases, ...companions) {
711
786
  const idx = bases.map((_, i) => i).sort((a, b) => (bases[a].toLowerCase() < bases[b].toLowerCase() ? -1 : 1));
712
787
  return { bases: idx.map((i) => bases[i]), companions: companions.map((arr) => idx.map((i) => arr[i])) };
713
788
  }
714
- const F_POOL_KEY_ABI = [
789
+ /** The key's ABI as `abi.encode(key)` lays it out: what {@link fPoolIdOfKey} hashes. */
790
+ export const F_POOL_KEY_ABI = [
715
791
  {
716
792
  type: "tuple",
717
793
  components: [
718
794
  { name: "quote", type: "address" },
719
795
  { name: "bases", type: "address[]" },
720
- { name: "swapFee", type: "uint256" },
796
+ { name: "swapFeeIdx", type: "uint8" },
721
797
  { name: "policy", type: "address" },
722
- { name: "creator", type: "address" },
723
798
  { name: "salt", type: "bytes32" },
724
- { name: "mintFee", type: "uint256" },
725
799
  ],
726
800
  },
727
801
  ];
728
802
  /**
729
803
  * An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
730
- * manager's `idOf(FPoolKey)` getter was cut in F version 21; this is the same hash (checked
731
- * against Foundry's encoder and the local deployment's pools in the tests). The key must be the
732
- * one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them), the birth policy.
804
+ * manager's `idOf` getter was cut in F version 21; this is the same hash (checked against Foundry's encoder in the
805
+ * tests). The key must be the one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them).
733
806
  */
734
807
  export function fPoolIdOfKey(key) {
735
808
  return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
736
809
  }
737
- /** 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). */
810
+ /** 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). */
738
811
  export function fPoolKeyOf(c, a) {
739
812
  const { bases } = sortFPoolLegs(a.bases);
740
- return {
741
- quote: a.quote,
742
- bases,
743
- swapFee: a.swapFee,
744
- policy: a.policy ?? fPoolPolicyFor(c, a.kind),
745
- creator: a.creator,
746
- salt: a.salt ?? ZERO_SALT,
747
- mintFee: a.mintFee ?? presetMintFee(a.swapFee),
748
- };
813
+ return { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy ?? fPoolPolicyFor(c, a.kind), salt: a.salt ?? ZERO_SALT };
749
814
  }
750
- /** Create the pool (no funds move — `deployLiquidity` funds it). Returns the tx hash; read the id with `fPoolIdOf`. */
815
+ /**
816
+ * List the pool — `initialize(key)` (policy.md §9): no funds move; the pool is inactive until its operator funds it
817
+ * ({@link fPoolDeploy}). Anyone under an open policy (salt zero), the policy's authority alone under a closed one
818
+ * (`Refused`); refused past the policy's sunset (`PolicyNotApproved`), off the policy's fee mask (`FeeNotListed`), quote or
819
+ * base list (`QuoteNotListed`, `BaseNotListed`), or with more legs than it allows (`TooManyLegs`). Returns the tx hash;
820
+ * read the id with {@link fPoolIdOf}.
821
+ */
751
822
  export async function fPoolInitialize(c, a) {
752
823
  const key = fPoolKeyOf(c, a);
753
- if (!isValidMintFee(key.swapFee, key.mintFee)) {
754
- throw new Error(`logswap: mint fee ${key.mintFee} is outside 2 × the swap fee (${2n * key.swapFee}) … ${MINT_FEE_MAX}`);
755
- }
756
824
  const wallet = requireWallet(c);
757
825
  const { request } = await c.public.simulateContract({
758
- address: c.addresses.fPoolManager,
759
- abi: fPoolManagerAbi,
826
+ address: c.addresses.managerF,
827
+ abi: managerFAbi,
760
828
  functionName: "initialize",
761
829
  args: [key],
762
830
  account: wallet.account,
@@ -772,41 +840,19 @@ export async function fPoolIdOf(c, a) {
772
840
  return fPoolIdOfKey(fPoolKeyOf(c, a));
773
841
  }
774
842
  /**
775
- * Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field but the salt,
776
- * which is taken from `opts.salt` (zero by default — every pool the SDK's create flow makes
777
- * 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
778
- * returning a key that names another pool. What {@link fPoolMigrate} needs when handed an id.
843
+ * Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field, the salt included (F 41). The result
844
+ * is checked against the id.
779
845
  */
780
846
  export async function fPoolKeyOfPool(c, poolId, opts = {}) {
781
- const ev = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
782
- const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.fPoolManager, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
847
+ const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
848
+ const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
783
849
  const l = logs[0];
784
850
  if (!l)
785
851
  throw new Error(`logswap: no PoolCreated for F pool ${poolId}`);
786
852
  const a = l.args;
787
- const key = {
788
- quote: a.quote,
789
- bases: [...a.bases],
790
- swapFee: a.swapFee,
791
- policy: a.policy,
792
- creator: a.creator,
793
- salt: opts.salt ?? ZERO_SALT,
794
- mintFee: a.mintFee,
795
- };
796
- if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
797
- // a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
798
- try {
799
- const creatorShare = BigInt((await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "creatorShareOf", args: [poolId] })));
800
- const padKey = { ...key, salt: padSalt({ creatorShare }) };
801
- if (fPoolIdOfKey(padKey).toLowerCase() === poolId.toLowerCase())
802
- return padKey;
803
- }
804
- catch {
805
- /* not a pad: fall through to the error */
806
- }
807
- }
853
+ const key = { quote: a.quote, bases: [...a.bases], swapFeeIdx: Number(a.swapFeeIdx), policy: a.policy, salt: a.salt };
808
854
  if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase()) {
809
- throw new Error(`logswap: F pool ${poolId} was not born with salt ${key.salt} — pass its salt, or its whole key`);
855
+ 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`);
810
856
  }
811
857
  return key;
812
858
  }
@@ -942,78 +988,64 @@ export function fPoolBookL(baseAssets, lnCapOverSeed) {
942
988
  * carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
943
989
  * carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
944
990
  */
945
- export async function fPoolDeploy(c, a) {
946
- const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
947
- return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed, a.to ?? a.account], a.account);
948
- }
949
991
  /**
950
- * Close the pool — the raw entry (`retire` before F 38). Allowed only at an empty bid, Q ≤ L/1e9, on every pool but a
951
- * pad: the market took it, or the operator harvested it out first ({@link fPoolClose} does both in one transaction).
952
- * Income settles to `to` first. The live (S, Q, R_j) become a frozen bundle every share of this generation redeems
953
- * ({@link fPoolRedeem}), forever; the pool is unfunded until the next {@link fPoolDeploy}, which opens generation
954
- * `gen + 1` under the same id, policy, roles, gates and lists. Whoever runs the pool.
992
+ * Fund the pool — `deployLiquidity(poolId, baseAssets, quoteAmount, lnCapOverSeed)` (policy.md §9): the book of this generation,
993
+ * on an INACTIVE pool — listed and never funded, or closed (`PoolActive` otherwise). The operator's alone (`NotOperator`): it pays
994
+ * every leg's amount and `quoteAmount` by plain allowance to the manager ({@link approveTokenForFPoolManager}) and holds the shares —
995
+ * all but `MIN_SHARES`, which go to 0xdead; every share does on a pad. Refused past the policy's sunset (`PolicyNotApproved`),
996
+ * under its buffer (`QuoteTooThin`), with a cap under its `lnCapMin` (`CapTooClose`). An amount of 0 leaves a leg dormant. Pass the
997
+ * book raw (`baseAssets` + `lnCapOverSeed`) or as a {@link FPoolBookSpec}.
955
998
  */
956
- export async function fPoolCloseRaw(c, a) {
957
- return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
999
+ export async function fPoolDeploy(c, a) {
1000
+ const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
1001
+ return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed], a.account);
958
1002
  }
959
1003
  /**
960
- * Close the pool as ONE transaction: the harvest that empties the bid
961
- * ({@link fPoolEmptyingHarvests} — a dividend to every share; none when it is already empty),
962
- * then `close` — the manager's `multicall`, the operator as sender. What a sponsor's "close" button
963
- * should call. Throws before sending on a pad: a pad never closes.
1004
+ * Close the pool (policy.md §9) — at any bid. The manager harvests the income first (a dividend to every share, the operator's
1005
+ * paid to `to`), freezes every reserve and the bid into generation `gen`'s bundle — every share of it redeems pro rata
1006
+ * ({@link fPoolRedeem}), forever — and moves the counter to `gen + 1`, the generation the next {@link fPoolDeploy} opens under
1007
+ * the same id, policy, roles and gates. The operator's alone. Throws before sending on a pad: a pad never closes
1008
+ * (`PadNeverCloses`). Pass `flags` when in hand to save the read.
964
1009
  */
965
1010
  export async function fPoolClose(c, a) {
966
- const harvests = await fPoolEmptyingHarvests(c, a.poolId);
967
- if (harvests.length === 0)
968
- return fPoolCloseRaw(c, a);
969
- const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
970
- const calls = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("close", [a.poolId, a.to ?? a.account])];
971
- return writeFPool0(c, "multicall", [calls], a.account);
1011
+ const flags = a.flags ?? (await getFPool(c, a.poolId)).flags;
1012
+ if ((flags & SEED_TO_DEAD) !== 0)
1013
+ throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
1014
+ return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
972
1015
  }
973
1016
  /**
974
- * The harvests that empty an unlocked pool's bid, in order — what a close sends before its
975
- * `close` (a close needs an empty bid on every pool). One `harvest(Q)` does it: the income tax leaves the pool with
976
- * the income part (with no treasury there is none). `[]` when the bid is already empty. Throws on a pad (a pad
977
- * never closes, whatever its bid), and when the pool's policy keeps a floor on the bid
978
- * (`PolPolicy.minQuoteRatio`): a `close` under that policy waits for the market.
1017
+ * The relaunch's calls — what `regenerate` was (policy.md §9): `close(poolId, to)`, `redeem(poolId, gen, operator, shares)` for the
1018
+ * operator's own shares of the generation closed (left out at 0), then `deployLiquidity` with the next book. Pure, so a form can show
1019
+ * what it is about to send; {@link fPoolRelaunch} sends them as one `multicall`.
979
1020
  */
980
- export async function fPoolEmptyingHarvests(c, poolId) {
981
- const s = await getFPool(c, poolId);
982
- // `PadPolicy` refuses `close` at any bid — a pad graduates (regenerate), it never closes; a fresh start is a new pad
983
- if (s.kind === "pad")
984
- throw new Error("logswap: a pad never closes — it graduates by regenerate; a fresh start is a new pad");
985
- if (s.Q === 0n)
986
- return [];
987
- const { maxHarvest } = await getFPoolRoles(c, poolId, s);
988
- if (maxHarvest < s.Q)
989
- throw new Error("logswap: the pool's policy keeps a floor on the bid — it cannot be harvested empty");
990
- return [s.Q];
1021
+ export function fPoolRelaunchCalls(a) {
1022
+ const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
1023
+ const enc = (functionName, args) => encodeFunctionData({ abi: managerFAbi, functionName, args });
1024
+ const calls = [enc("close", [a.poolId, a.to ?? a.account])];
1025
+ if (a.shares > 0n)
1026
+ calls.push(enc("redeem", [a.poolId, BigInt(a.gen), a.account, a.shares]));
1027
+ calls.push(enc("deployLiquidity", [a.poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
1028
+ return calls;
991
1029
  }
992
1030
  /**
993
- * The GENERATION STEP — on a pad, its graduation (F 38: `deployLiquidity` with nothing changed). The manager
994
- * harvests the generation's income first, releases the dead shares' income, and asks the policy
995
- * (`onRegenerate`), whose {@link FPolicyTerms} name a `carried` holder. Then, for live
996
- * generation `g`:
997
- *
998
- * - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
999
- * as the pool;
1000
- * - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`GenerationRetired`)
1001
- * and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
1002
- * dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
1003
- * lists them;
1004
- * - the income released (`IncomeReleased`), all in quote: `toPayee` to the payee and the rest into the bid
1005
- * (the floor down). No share is minted; L does not move. The book keeps its reserves, marks and cap.
1006
- *
1007
- * A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and private carry the
1008
- * authority and send it the whole income; a public pool refuses (`Refused`). A carried holder with no
1009
- * share is `BadTerms`. Whoever runs the pool. To change the book (reserves, prices, cap) use {@link fPoolDeploy}.
1031
+ * Relaunch the pool as ONE transaction: close generation `gen`, redeem the operator's own shares of it (its funds come back),
1032
+ * fund `gen + 1` with the book given — the manager's `multicall`, the operator as sender. Every other holder is frozen into the
1033
+ * bundle and redeems it ({@link fPoolRedeem}); the new book may re-weight any of the key's bases and pick its own cap. The
1034
+ * deploy pulls its amounts and `quoteAmount` from the operator in the same transaction the redeem pays it, so the allowances
1035
+ * must cover the pull. Not on a pad (a pad never closes); not on an inactive pool (fund it with {@link fPoolDeploy}).
1010
1036
  */
1011
- export async function fPoolRegenerate(c, a) {
1012
- return writeFPool(c, a.poolId, "regenerate", [a.to ?? a.account], a.account);
1013
- }
1014
- /** Where a pad's seed lives: `seed` mints every share of a pad here itself. */
1037
+ export async function fPoolRelaunch(c, a) {
1038
+ const s = await getFPool(c, a.poolId);
1039
+ if ((s.flags & SEED_TO_DEAD) !== 0)
1040
+ throw new Error("logswap: a pad never closes (PadNeverCloses) — a fresh start is a new pad");
1041
+ if (!s.seeded)
1042
+ throw new Error("logswap: the pool is inactive — nothing to close; fund it with fPoolDeploy");
1043
+ const shares = await fPoolShareBalance(c, a.poolId, a.account, s.gen);
1044
+ return writeFPool0(c, "multicall", [fPoolRelaunchCalls({ ...a, gen: s.gen, shares })], a.account);
1045
+ }
1046
+ /** Where a pad's seed lives: `deployLiquidity` mints every share of a pad here itself. */
1015
1047
  export const DEAD_ADDRESS = "0x000000000000000000000000000000000000dEaD";
1016
- /** 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. */
1048
+ /** 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. */
1017
1049
  export const F_MIN_SHARES = 1000n;
1018
1050
  /**
1019
1051
  * The launch's calls, in order — the batch {@link fPoolLaunch} sends. Pure, so a form can show
@@ -1026,21 +1058,13 @@ export function fPoolLaunchCalls(poolId, a) {
1026
1058
  throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
1027
1059
  const { baseAssets, lnCapOverSeed } = fPoolBook(a);
1028
1060
  const bases = baseAssets.map((x) => x.base);
1029
- const key = {
1030
- quote: a.quote,
1031
- bases,
1032
- swapFee: a.swapFee,
1033
- policy: a.policy,
1034
- creator: a.creator,
1035
- salt: a.salt ?? ZERO_SALT,
1036
- mintFee: a.mintFee ?? presetMintFee(a.swapFee),
1037
- };
1038
- const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
1061
+ const key = { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy, salt: a.salt ?? ZERO_SALT };
1062
+ const enc = (functionName, args) => encodeFunctionData({ abi: managerFAbi, functionName, args });
1039
1063
  const calls = [];
1040
1064
  if (!a.initialized)
1041
1065
  calls.push(enc("initialize", [key]));
1042
- calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed, a.account]));
1043
- // gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the live pool.
1066
+ calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed]));
1067
+ // gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the closed pool.
1044
1068
  // No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
1045
1069
  for (const row of fPoolGenesisRows(a)) {
1046
1070
  const j = bases.indexOf(a.bases[row.j]);
@@ -1048,9 +1072,8 @@ export function fPoolLaunchCalls(poolId, a) {
1048
1072
  throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
1049
1073
  calls.push(enc(row.side === "buy" ? "swapQuoteIn" : "swapBaseIn", [poolId, BigInt(j), row.amountIn, row.minOut ?? 0n, a.account]));
1050
1074
  }
1051
- // the name, the desk's gates and its list are the POLICY's, not the
1052
- // manager's: they cannot ride in this batch — `fPoolLaunch` and `fPoolDeskOpening` send them
1053
- // right after, as the same creator
1075
+ // the name and the gate modes are the POLICY's, not the manager's: they cannot ride in this batch — `fPoolLaunch`
1076
+ // sends the name right after, as the same operator; the modes are `fPoolSetSwapMode` / `fPoolSetMintMode`
1054
1077
  calls.push(...(a.extra ?? []));
1055
1078
  return calls;
1056
1079
  }
@@ -1070,8 +1093,8 @@ export async function fPoolGenesisOutputs(c, poolId, a) {
1070
1093
  return [];
1071
1094
  const calls = fPoolLaunchCalls(poolId, a);
1072
1095
  const { result } = await c.public.simulateContract({
1073
- address: c.addresses.fPoolManager,
1074
- abi: fPoolManagerAbi,
1096
+ address: c.addresses.managerF,
1097
+ abi: managerFAbi,
1075
1098
  functionName: "multicall",
1076
1099
  args: [calls],
1077
1100
  account: signerFor(c, a.account),
@@ -1129,33 +1152,21 @@ export async function fPoolWalletBatchesAtomically(c, account) {
1129
1152
  }
1130
1153
  }
1131
1154
  /**
1132
- * The desk's opening posture, on its policy: gated minting, the creator a
1133
- * minter. No appointment: the authority is the operator until one is appointed.
1134
- * Two writes to `PrivatePolicy`; the launch batch cannot carry them (they are not manager calls).
1135
- */
1136
- export async function fPoolDeskOpening(c, a) {
1137
- const policy = a.policy ?? fPoolPolicyFor(c, "private");
1138
- return [
1139
- await fPoolSetMintGate(c, { poolId: a.poolId, gated: true, account: a.account, policy }),
1140
- await fPoolSetMinters(c, { poolId: a.poolId, who: [a.account], allowed: true, account: a.account, policy }),
1141
- ];
1142
- }
1143
- /**
1144
- * Create a pool as ONE transaction: `initialize`, `seed`, the seed lock, the opening buy, the
1145
- * name, the private-pool gates — the manager's `multicall`, the creator as sender throughout.
1146
- * Either every call lands or none does; there is no half-built pool to resume.
1155
+ * Create a pool as ONE transaction: `initialize`, `deployLiquidity`, the opening buys — the manager's `multicall`, one sender
1156
+ * throughout. Either every call lands or none does; there is no half-built pool to resume. The sender must be the policy's
1157
+ * AUTHORITY: it is the pool's operator at birth, and `deployLiquidity` is the operator's (`NotOperator`). Under an open
1158
+ * policy anyone may list a pool ({@link fPoolInitialize}) but only the LOG — its authority — funds it, so a launch under the
1159
+ * public policy is the LOG's; a sponsor launches under its own policy.
1147
1160
  *
1148
- * Why the manager and not the router: every one of these entries authenticates by `msg.sender`
1149
- * (`seed` is authority-only, so is everything after it). Routed, the router would be the sender
1150
- * — the authority, the holder of the seed shares — and the handover back is two-step, so it
1151
- * could not even close in the same transaction. `multicall` is delegatecall-to-self, so the
1152
- * sender survives, which is what the manager's own doc says a router cannot do.
1161
+ * Why the manager and not the router: every one of these entries authenticates by `msg.sender`. Routed, the router would be
1162
+ * the sender — the operator, the holder of the seed shares. `multicall` is delegatecall-to-self, so the sender survives.
1153
1163
  *
1154
- * What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base,
1155
- * `Q0` of quote, plus `openBuy.amountIn` of quote. Grant those first — one `approve` per token,
1156
- * once ever ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
1164
+ * What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base, `quoteAmount` of quote, plus
1165
+ * each opening buy's `amountIn` of quote. Grant those first — one `approve` per token, once ever
1166
+ * ({@link approveTokenForFPoolManager}, {@link fPoolManagerAllowanceOk}).
1157
1167
  *
1158
- * Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}).
1168
+ * Returns the hash and the pool's id (the key's hash, {@link fPoolIdOf}). The name, when given, is a second transaction on
1169
+ * the policy ({@link fPoolSetName}); the gate modes are {@link fPoolSetSwapMode} / {@link fPoolSetMintMode} after it.
1159
1170
  */
1160
1171
  export async function fPoolLaunch(c, a) {
1161
1172
  const poolId = await fPoolIdOf(c, a);
@@ -1179,7 +1190,7 @@ export async function fPoolLaunch(c, a) {
1179
1190
  account: signerFor(c, a.account),
1180
1191
  forceAtomic: true,
1181
1192
  calls: [
1182
- { to: c.addresses.fPoolManager, data: encodeFunctionData({ abi: fPoolManagerAbi, functionName: "multicall", args: [calls] }) },
1193
+ { to: c.addresses.managerF, data: encodeFunctionData({ abi: managerFAbi, functionName: "multicall", args: [calls] }) },
1183
1194
  ...transfers.map((t) => ({ to: t.token, data: encodeFunctionData({ abi: erc20Abi, functionName: "transfer", args: [t.to, t.amount] }) })),
1184
1195
  ],
1185
1196
  });
@@ -1199,82 +1210,67 @@ export async function fPoolLaunch(c, a) {
1199
1210
  }
1200
1211
  // ─── the roles, on the policy ─────────────────────────────────────────────
1201
1212
  //
1202
- // Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy`
1203
- // may be passed when in hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once.
1204
- /** A write keyed by poolId, on the pool's policy. */
1205
- async function writePolicy(c, abi, a, functionName, args) {
1213
+ // Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy` may be passed when in
1214
+ // hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once. The policy syncs the manager itself
1215
+ // (`setGates`), which stamps the block: no swap lands in the block of a change (047). Every mode and list write reverts
1216
+ // `GatesUnavailable` on an open policy: a public pool can never be gated.
1217
+ /** A write on a policy. */
1218
+ async function writePolicy(c, policy, functionName, args, account) {
1206
1219
  const wallet = requireWallet(c);
1207
- const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
1208
- const { request } = await c.public.simulateContract({
1209
- address: policy,
1210
- abi,
1211
- functionName,
1212
- args: [a.poolId, ...args],
1213
- account: signerFor(c, a.account),
1214
- });
1220
+ const { request } = await c.public.simulateContract({ address: policy, abi: policyFAbi, functionName, args, account: signerFor(c, account) });
1215
1221
  return wallet.writeContract(request);
1216
1222
  }
1217
- /**
1218
- * Propose the next authority — step one of two, on the pool's policy. Nothing moves
1219
- * until `next` accepts; proposing again (the zero address included) cancels a pending proposal.
1220
- * Indexed on-chain via the policy's AuthorityProposed.
1221
- */
1222
- export async function fPoolProposeAuthority(c, a) {
1223
- return writePolicy(c, fPolicyBaseAbi, a, "proposeAuthority", [a.next]);
1223
+ /** A write keyed by poolId, on the pool's policy. */
1224
+ async function writePoolPolicy(c, a, functionName, args) {
1225
+ const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
1226
+ return writePolicy(c, policy, functionName, [a.poolId, ...args], a.account);
1224
1227
  }
1225
1228
  /**
1226
- * Accept a pending proposal — step two; only the proposed address can. Indexed via the policy's
1227
- * AuthoritySet. On the desk's policy this clears the operator (pending and accepted) and voids the
1228
- * seller's list.
1229
+ * Appoint the pool's operator (the AUTHORITY's; zero resets it to the authority): the account that funds, harvests, closes and sets the
1230
+ * 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
1231
+ * a contract (an executor). `InactivePool` on a pool the policy never held.
1229
1232
  */
1230
- export async function fPoolAcceptAuthority(c, a) {
1231
- return writePolicy(c, fPolicyBaseAbi, a, "acceptAuthority", []);
1233
+ export async function fPoolAppointOperator(c, a) {
1234
+ return writePoolPolicy(c, a, "appointOperator", [a.operator]);
1232
1235
  }
1233
- // ─── the desk's controls (PrivatePolicy) ───────────────────────────────
1234
1236
  /**
1235
- * Set the desk's swap admission (the authority, on the desk's policy; decision 073): `open`, `listed` (the minters and takers
1236
- * lists) or `executor` (one address, cached on the manager, no policy call per swap). `executor` is required in `executor` mode
1237
- * and must be omitted otherwise. Preserves mint admission. `burn` is never gated.
1237
+ * Set the pool's swap gate (the OPERATOR's): `open`, `listed` (the policy's swap list, {@link fPolicySetRights}; the operator always
1238
+ * passes) or `operator`. The mint mode must stay at least as restrictive (`ModeOrder`). `burn`, `redeem` and `claim` are never gated.
1238
1239
  */
1239
1240
  export async function fPoolSetSwapMode(c, a) {
1240
- return writePolicy(c, privatePolicyAbi, a, "setSwapMode", [SWAP_MODES.indexOf(a.mode), a.executor ?? ZERO_ADDRESS]);
1241
- }
1242
- /** Turn mint admission on or off (the authority, on the desk's policy), preserving the swap mode and its executor. */
1243
- export async function fPoolSetMintGate(c, a) {
1244
- return writePolicy(c, privatePolicyAbi, a, "setMintGate", [a.gated]);
1245
- }
1246
- /**
1247
- * Add to or remove from the pool's MINTERS — who may mint, and swap (a zap in is both under one
1248
- * lock) — in one call (the authority, on the desk's policy). The list is keyed by
1249
- * the authority that granted it: a handover starts the buyer with an empty one. Stamps the
1250
- * block: no swap lands in it (047).
1251
- */
1252
- export async function fPoolSetMinters(c, a) {
1253
- return writePolicy(c, privatePolicyAbi, a, "setMinters", [a.who, a.allowed]);
1241
+ return writePoolPolicy(c, a, "setSwapMode", [MODES.indexOf(a.mode)]);
1254
1242
  }
1255
- /** Add to or remove from the pool's TAKERS — who may swap only — in one call (the authority). Stamps the block. */
1256
- export async function fPoolSetTakers(c, a) {
1257
- return writePolicy(c, privatePolicyAbi, a, "setTakers", [a.who, a.allowed]);
1243
+ /** 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. */
1244
+ export async function fPoolSetMintMode(c, a) {
1245
+ return writePoolPolicy(c, a, "setMintMode", [MODES.indexOf(a.mode)]);
1258
1246
  }
1259
- async function readDesk(c, poolId, who, functionName, policy) {
1260
- const address = policy ?? (await fPoolPolicyOf(c, poolId));
1261
- return (await c.public.readContract({ address, abi: privatePolicyAbi, functionName, args: [poolId, who] }));
1247
+ /** The bits of `PolicyF.rights`: listed for swaps; listed for mints, which implies swaps. */
1248
+ export const RIGHT_SWAP = 1;
1249
+ export const RIGHT_MINT = 2;
1250
+ /** The on-chain bits of a right (`MINT` is written as `MINT | SWAP`, as the policy does). */
1251
+ export function fPolicyRightBits(right) {
1252
+ return right === "none" ? 0 : right === "swap" ? RIGHT_SWAP : RIGHT_SWAP | RIGHT_MINT;
1262
1253
  }
1263
- /** On the pool's minters under its current authority: may mint, and swap. */
1264
- export async function fPoolIsMinter(c, poolId, who, policy) {
1265
- return readDesk(c, poolId, who, "isMinter", policy);
1254
+ /** The right the bits spell. */
1255
+ export function fPolicyRightOf(bits) {
1256
+ const b = Number(bits);
1257
+ return (b & RIGHT_MINT) !== 0 ? "mint" : (b & RIGHT_SWAP) !== 0 ? "swap" : "none";
1266
1258
  }
1267
- /** On the pool's takers under its current authority: may swap only. */
1268
- export async function fPoolIsTaker(c, poolId, who, policy) {
1269
- return readDesk(c, poolId, who, "isTaker", policy);
1259
+ /**
1260
+ * 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
1261
+ * — 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);
1262
+ * the modes are each pool's. Stamps nothing: an address removed in a block can still swap in that block.
1263
+ */
1264
+ export async function fPolicySetRights(c, a) {
1265
+ return writePolicy(c, a.policy, "setRights", [a.who, fPolicyRightBits(a.right)], a.account);
1270
1266
  }
1271
- /** May swap: a minter or a taker (consulted only while the swap gate is on). */
1272
- export async function fPoolIsAllowed(c, poolId, who, policy) {
1273
- return readDesk(c, poolId, who, "isAllowed", policy);
1267
+ /** What `policy` lists `who` for now (`rights`). */
1268
+ export async function fPolicyRightsOf(c, policy, who) {
1269
+ return fPolicyRightOf((await c.public.readContract({ address: policy, abi: policyFAbi, functionName: "rights", args: [who] })));
1274
1270
  }
1275
- /** Label the pool — the authority's own words on the pool's POLICY, mutable, never identity. At most 31 bytes of UTF-8. */
1271
+ /** Label the pool (the OPERATOR's): a `NameSet` event on the policy, nothing stored — mutable, never identity. At most 31 bytes of UTF-8. */
1276
1272
  export async function fPoolSetName(c, a) {
1277
- return writePolicy(c, fPolicyBaseAbi, a, "setName", [textToBytes32(a.name)]);
1273
+ return writePoolPolicy(c, a, "setName", [textToBytes32(a.name)]);
1278
1274
  }
1279
1275
  /**
1280
1276
  * What the PROTOCOL says an address is — "Keyrock" — on the REGISTRY. Only its
@@ -1305,7 +1301,7 @@ export async function fPoolSponsorName(c, who) {
1305
1301
  export async function fPoolRegistryOf(c) {
1306
1302
  if (c.addresses.policyRegistry)
1307
1303
  return c.addresses.policyRegistry;
1308
- return (await c.public.readContract({ address: c.addresses.fPoolManager, abi: fPoolManagerAbi, functionName: "registry" }));
1304
+ return (await c.public.readContract({ address: c.addresses.managerF, abi: managerFAbi, functionName: "registry" }));
1309
1305
  }
1310
1306
  async function registryAddress(c) {
1311
1307
  const registry = await fPoolRegistryOf(c);
@@ -1313,17 +1309,9 @@ async function registryAddress(c) {
1313
1309
  throw new Error("logswap: this deployment carries no policy registry");
1314
1310
  return registry;
1315
1311
  }
1316
- /** Who may run the pool (decision 073): the authority always, and the optional delegate. */
1312
+ /** 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. */
1317
1313
  export function fPoolRunners(s) {
1318
- return s.operator === ZERO_ADDRESS ? [s.authority] : [s.authority, s.operator];
1319
- }
1320
- /**
1321
- * Grant, replace or revoke the pool operator (the authority, on the desk's policy; decision 073): one optional delegate who may
1322
- * `harvest`, `retire`, `regenerate` and `setLegs` besides the authority. Immediate, with no acceptance step, so check the
1323
- * address; the zero address revokes. A handover or a policy move clears it.
1324
- */
1325
- export async function fPoolSetPoolOperator(c, a) {
1326
- return writePolicy(c, privatePolicyAbi, a, "setPoolOperator", [a.operator]);
1314
+ return s.operator === ZERO_ADDRESS ? [] : [s.operator];
1327
1315
  }
1328
1316
  /**
1329
1317
  * Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
@@ -1334,8 +1322,8 @@ export async function fPoolTransferShares(c, a) {
1334
1322
  const wallet = requireWallet(c);
1335
1323
  const gen = a.gen ?? (await fPoolGen(c, a.poolId));
1336
1324
  const { request } = await c.public.simulateContract({
1337
- address: c.addresses.fPoolManager,
1338
- abi: fPoolManagerAbi,
1325
+ address: c.addresses.managerF,
1326
+ abi: managerFAbi,
1339
1327
  functionName: "transfer",
1340
1328
  args: [a.to, fPoolShareId(a.poolId, gen), a.shares],
1341
1329
  account: signerFor(c, a.account),
@@ -1343,18 +1331,17 @@ export async function fPoolTransferShares(c, a) {
1343
1331
  return wallet.writeContract(request);
1344
1332
  }
1345
1333
  /**
1346
- * Every F pool ever created, from `PoolCreated` logs alone — plus one `kind()` read per distinct
1347
- * policy, cached. Possible only because the event carries the full key preimage (quote, creator, bases,
1348
- * swapFee, policy, mintFee) — the poolId is a hash and could never be inverted; contracts PR #17
1349
- * exists for exactly this call. With `indexer`, the logs come from it (the node when it fails):
1350
- * a scan from block 0 per call is what made the first load wait on the node.
1334
+ * Every F pool ever created, from `PoolCreated` logs alone — plus the terms of each distinct policy, read once and cached.
1335
+ * Possible only because the event carries the full key (quote, policy, bases, swapFeeIdx, salt) — the poolId is a hash and
1336
+ * could never be inverted; contracts PR #17 exists for exactly this call. With `indexer`, the logs come from it (the node
1337
+ * when it fails): a scan from block 0 per call is what made the first load wait on the node.
1351
1338
  */
1352
1339
  export async function discoverFPools(c, opts = {}) {
1353
- const ev = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
1340
+ const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
1354
1341
  if (!ev)
1355
1342
  throw new Error("logswap: F PoolCreated event missing from the generated ABI");
1356
- const deployEv = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "LiquidityDeployed");
1357
- const range = { indexer: opts.indexer, address: c.addresses.fPoolManager, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
1343
+ const deployEv = managerFAbi.find((x) => x.type === "event" && x.name === "LiquidityDeployed");
1344
+ const range = { indexer: opts.indexer, address: c.addresses.managerF, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
1358
1345
  const [{ logs }, { logs: deploys }] = await Promise.all([
1359
1346
  getEventLogs(c, { ...range, event: ev }),
1360
1347
  deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
@@ -1371,17 +1358,19 @@ export async function discoverFPools(c, opts = {}) {
1371
1358
  const a = l.args;
1372
1359
  const g0 = first.get(a.poolId.toLowerCase());
1373
1360
  const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
1361
+ const swapFeeIdx = Number(a.swapFeeIdx);
1374
1362
  return {
1375
1363
  poolId: a.poolId,
1376
1364
  quote: a.quote,
1377
1365
  bases: [...a.bases],
1378
1366
  weights: g0?.weights ?? [],
1379
- swapFee: a.swapFee,
1380
- mintFee: a.mintFee,
1367
+ swapFeeIdx,
1368
+ swapFee: fFeeOf(swapFeeIdx),
1369
+ mintFee: fMintFeeOf(swapFeeIdx),
1381
1370
  lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
1382
1371
  kind,
1383
1372
  policy: a.policy,
1384
- creator: a.creator,
1373
+ salt: a.salt,
1385
1374
  block: l.blockNumber,
1386
1375
  seeded: g0 !== undefined,
1387
1376
  q0: g0?.q0 ?? 0n,
@@ -1389,78 +1378,22 @@ export async function discoverFPools(c, opts = {}) {
1389
1378
  };
1390
1379
  }));
1391
1380
  }
1392
- const MAX_U64 = (1n << 64n) - 1n;
1393
- const MAX_U128 = (1n << 128n) - 1n;
1394
- /**
1395
- * The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
1396
- * 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
1397
- * 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
1398
- * chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
1399
- */
1400
- export function padSalt(s) {
1401
- const nonce = s.nonce ?? 0n;
1402
- if (s.burnShare !== undefined && s.burnShare !== 0n)
1403
- throw new Error("logswap: a pad has no burn share since F version 28 (decision 067)");
1404
- if (s.creatorShare < 0n || s.creatorShare > MAX_U64)
1405
- throw new Error("logswap: a pad's creator share is a WAD fraction that fits 64 bits");
1406
- if (nonce < 0n || nonce > MAX_U128)
1407
- throw new Error("logswap: a pad salt's nonce fits 128 bits");
1408
- return `0x${((s.creatorShare << 192n) | nonce).toString(16).padStart(64, "0")}`;
1409
- }
1410
- /** The inverse of {@link padSalt}. `burnShare` is the old field's bits, nonzero only on a salt the F version 28 policy refuses. */
1411
- export function padSplitOfSalt(salt) {
1412
- const v = BigInt(salt);
1413
- return { creatorShare: v >> 192n, burnShare: (v >> 128n) & MAX_U64, nonce: v & MAX_U128 };
1414
- }
1415
- /** The policy's terms for one pool, by its kind. */
1416
- export async function getFPoolRules(c, s, roles) {
1417
- const rd = (abi, functionName, args = []) => c.public.readContract({ address: s.policy, abi, functionName, args });
1418
- switch (s.kind) {
1419
- case "pad": {
1420
- // the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
1421
- const gen = s.gen;
1422
- const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
1423
- rd(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
1424
- fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
1425
- rd(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
1426
- rd(padPolicyAbi, "incomeTaxRate"),
1427
- rd(padPolicyAbi, "creatorShareMin"),
1428
- rd(padPolicyAbi, "creatorShareMax"),
1429
- ]);
1430
- const ranges = { creatorShareMin, creatorShareMax };
1431
- return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
1432
- }
1433
- case "pol": {
1434
- const [minQuoteRatio, incomeTaxRate] = await Promise.all([rd(polPolicyAbi, "minQuoteRatio"), rd(polPolicyAbi, "incomeTaxRate")]);
1435
- return { kind: "pol", minQuoteRatio, incomeTaxRate };
1436
- }
1437
- case "public": {
1438
- return { kind: "public" };
1439
- }
1440
- case "private": {
1441
- const r = roles ?? (await getFPoolRoles(c, s.poolId, s));
1442
- return { kind: "private", gateMint: r.gateMint, swapMode: r.swapMode, swapExecutor: r.swapExecutor, operator: r.operator };
1443
- }
1444
- }
1445
- }
1446
1381
  /**
1447
- * Every F pool `who` is the AUTHORITY of, across the four policies — the policy page's list. Pools
1448
- * `who` created and handed over are not here (the buyer's page shows them); pools handed TO
1449
- * `who` are. `pools` may be passed (from the indexer, say) to skip the log scan.
1382
+ * Every F pool `who` runs (its operator) or sponsors (the authority of its policy) — the policy page's list. `roles` tells
1383
+ * which. `pools` may be passed (from the indexer, say) to skip the log scan.
1450
1384
  */
1451
1385
  export async function fPoolsControlledBy(c, who, opts = {}) {
1452
1386
  const pools = opts.pools ?? (await discoverFPools(c, { fromBlock: opts.fromBlock }));
1453
- // the LIVE policy answers for the authority: a moved pool (046) is on another one than its birth's
1454
1387
  const states = await Promise.all(pools.map((p) => getFPool(c, p.poolId)));
1455
- const authorities = await Promise.all(states.map((s) => c.public.readContract({ address: s.policy, abi: fPolicyBaseAbi, functionName: "authority", args: [s.poolId] })));
1388
+ const roles = await Promise.all(states.map((s) => getFPoolRoles(c, s.poolId, s)));
1389
+ const me = who.toLowerCase();
1456
1390
  const out = [];
1457
1391
  for (let i = 0; i < pools.length; ++i) {
1458
- if (authorities[i].toLowerCase() !== who.toLowerCase())
1392
+ const r = roles[i];
1393
+ if (r.operator.toLowerCase() !== me && r.authority.toLowerCase() !== me)
1459
1394
  continue;
1460
1395
  const state = states[i];
1461
- const roles = await getFPoolRoles(c, state.poolId, state);
1462
- const rules = await getFPoolRules(c, state, roles);
1463
- out.push({ pool: pools[i], roles, state, rules });
1396
+ out.push({ pool: pools[i], roles: r, state, terms: await fPolicyTermsOf(c, state.policy) });
1464
1397
  }
1465
1398
  return out;
1466
1399
  }
@@ -1472,14 +1405,14 @@ export async function fPoolsControlledBy(c, who, opts = {}) {
1472
1405
  * holder minted before the cut.
1473
1406
  */
1474
1407
  export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
1475
- const ev = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "Transfer");
1408
+ const ev = managerFAbi.find((x) => x.type === "event" && x.name === "Transfer");
1476
1409
  if (!ev)
1477
1410
  throw new Error("logswap: 6909 Transfer event missing from the generated ABI");
1478
1411
  const gen = opts.gen ?? (await fPoolGen(c, poolIdHex));
1479
1412
  const indexer = opts.indexer ?? c.indexerUrl;
1480
1413
  if (indexer) {
1481
1414
  try {
1482
- const rows = await poolHolders(indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.fPoolManager.toLowerCase() } });
1415
+ const rows = await poolHolders(indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.managerF.toLowerCase() } });
1483
1416
  return rows
1484
1417
  .filter((r) => r.balance > 0n)
1485
1418
  .map((r) => ({ holder: r.holder, shares: r.balance }))
@@ -1490,7 +1423,7 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
1490
1423
  }
1491
1424
  }
1492
1425
  const id = fPoolShareId(poolIdHex, gen);
1493
- const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.fPoolManager, event: ev, args: { id }, fromBlock: opts.fromBlock });
1426
+ const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.managerF, event: ev, args: { id }, fromBlock: opts.fromBlock });
1494
1427
  const bal = new Map();
1495
1428
  for (const l of logs) {
1496
1429
  const a = l.args;
@@ -1504,13 +1437,13 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
1504
1437
  .map(([holder, shares]) => ({ holder: holder, shares }))
1505
1438
  .sort((a, b) => (b.shares > a.shares ? 1 : -1));
1506
1439
  }
1507
- /** Every F pool's raw state in one lens call (the manager's `Pool` struct: quote, swapFee, policy, seeded, gen, n, restructureTime, asks, lnCapOverSeed, Q, realizedVariance, L, shares, refLogFloor). */
1440
+ /** 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). */
1508
1441
  export async function getFPoolsRaw(c, poolIds) {
1509
- const { lensAbi } = await import("./generated.js");
1510
- return (await c.public.readContract({ address: c.addresses.lens, abi: lensAbi, functionName: "getFPools", args: [poolIds] }));
1442
+ const { lensFAbi } = await import("./generated.js");
1443
+ return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "getPools", args: [poolIds] }));
1511
1444
  }
1512
1445
  /** Share value from the lens — (L + Q)/shares, WAD per share — the same figure as `fPoolShareValue`, from one source. */
1513
1446
  export async function shareValueOnChain(c, poolId) {
1514
- const { lensAbi } = await import("./generated.js");
1515
- return (await c.public.readContract({ address: c.addresses.lens, abi: lensAbi, functionName: "shareValue", args: [poolId] }));
1447
+ const { lensFAbi } = await import("./generated.js");
1448
+ return (await c.public.readContract({ address: c.addresses.lensF, abi: lensFAbi, functionName: "shareValue", args: [poolId] }));
1516
1449
  }