@logswap/sdk 0.5.91 → 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.
package/dist/fpool.js 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
@@ -33,28 +35,18 @@
33
35
  * `onboardToken(c, "F", token, need)`.
34
36
  */
35
37
  import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, erc20Abi, keccak256 } from "viem";
36
- import { managerFAbi, lensFAbi, routerFAbi, orphanPolicyFAbi, padPolicyAbi, polPolicyAbi, policyRegistryAbi, sponsorPolicyFAbi } from "./generated.js";
38
+ import { managerFAbi, lensFAbi, routerFAbi, policyFAbi, policyRegistryAbi } from "./generated.js";
37
39
  /**
38
- * One contract, one ABI (F version 12): `harvest`, `claim`, `regenerate`, `close`, `deployLiquidity`,
39
- * the fee parameters are `ManagerF`'s own code. The roles left it for the policies in F version 15:
40
- * {@link fPolicyBaseAbi} is what the policies share, {@link sponsorPolicyFAbi} the sponsored one (kind
41
- * `"sponsor"`, decision 098), {@link padPolicyAbi} / {@link polPolicyAbi} the other kinds', and
42
- * {@link orphanPolicyFAbi} the neutral policy of a pool the LOG orphaned.
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.
43
43
  */
44
- export { managerFAbi, orphanPolicyFAbi, padPolicyAbi, polPolicyAbi, sponsorPolicyFAbi };
45
- /**
46
- * What the protocol's policies share: `authority`, `nameOf` / `setName`, `kind`, `maxHarvest`
47
- * (a harvest has no cut, decisions 056). `polPolicyAbi` is a superset of it, so it stands in for the base: a call
48
- * through it to any F policy decodes the base's functions (`maxHarvest` is absent on the orphan policy, which refuses every harvest).
49
- */
50
- export const fPolicyBaseAbi = polPolicyAbi;
44
+ export { managerFAbi, policyFAbi };
51
45
  import { clientChainId } from "./client.js";
52
46
  import { findQuoteResult } from "./quote.js";
53
47
  import { fallBackUnlessRejected, signerFor } from "./write.js";
54
48
  import { getEventLogs } from "./history.js";
55
49
  import { poolHolders } from "./views.js";
56
- import { presetMintFee } from "./positions.js";
57
- import { isValidMintFee, MINT_FEE_MAX } from "./keys.js";
58
50
  const WAD = 10n ** 18n;
59
51
  const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
60
52
  /**
@@ -80,7 +72,7 @@ async function rawFPool(c, poolId) {
80
72
  throw new Error(`logswap: no F pool with id ${poolId}`);
81
73
  return p;
82
74
  }
83
- /** Read a basket pool whole: one lens call (`pool`, 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}. */
84
76
  export async function getFPool(c, poolId) {
85
77
  const v = await c.public.readContract({
86
78
  address: c.addresses.lensF,
@@ -96,7 +88,7 @@ export async function getFPool(c, poolId) {
96
88
  // cannot be a check on `seeded`.
97
89
  if (/^0x0{40}$/i.test(p.quote))
98
90
  throw new Error(`logswap: no F pool with id ${poolId}`);
99
- const [kind, name] = await Promise.all([fPoolKindOfPolicy(c, p.policy), fPoolNameOf(c, poolId, p.policy)]);
91
+ const kind = await fPoolKindOfPolicy(c, p.policy);
100
92
  return {
101
93
  poolId,
102
94
  quote: p.quote,
@@ -116,7 +108,6 @@ export async function getFPool(c, poolId) {
116
108
  policy: p.policy,
117
109
  flags: Number(p.flags),
118
110
  operator: p.operator,
119
- name,
120
111
  restructureTime: Number(p.restructureTime),
121
112
  kind,
122
113
  seeded: p.seeded,
@@ -127,36 +118,78 @@ export async function getFPool(c, poolId) {
127
118
  kappa: v.baseAssets.map((l) => l.kappa),
128
119
  };
129
120
  }
130
- const F_KIND_NAMES = ["sponsor", "pol", "pad", "orphan"];
131
- /** The policy's birth-time declaration that the seed's shares are the pool's (a pad's), in `flags`. */
121
+ /** The policy's birth-time declaration that the deploy's shares are the pool's (`seedToDead`, a pad's), in `flags`. */
132
122
  export const SEED_TO_DEAD = 4;
133
- 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
+ }
134
134
  /**
135
- * What a policy IS — its `kind()` tag, read once per policy address and cached for the client's
136
- * chain: a pool's kind is its policy's word, never the manager's. An unknown tag
137
- * (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.
138
137
  */
139
- export async function fPoolKindOfPolicy(c, policy) {
140
- // 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) {
141
139
  const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
142
- let hit = kindCache.get(key);
140
+ let hit = termsCache.get(key);
143
141
  if (!hit) {
144
- hit = c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "kind" }).then((word) => {
145
- const tag = bytes32ToText(word);
146
- if (!F_KIND_NAMES.includes(tag))
147
- throw new Error(`logswap: policy ${policy} says it is "${tag}", which is no kind this SDK knows`);
148
- 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) };
149
171
  });
150
- kindCache.set(key, hit);
151
- 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
152
174
  }
153
175
  return hit;
154
176
  }
155
- /** The pool's label, as its policy holds it. "" when unnamed. */
156
- export async function fPoolNameOf(c, poolId, policy) {
157
- const p = policy ?? (await fPoolPolicyOf(c, poolId));
158
- const word = (await c.public.readContract({ address: p, abi: fPolicyBaseAbi, functionName: "nameOf", args: [poolId] }));
159
- 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) : "";
160
193
  }
161
194
  /** The deployment's policy for a slot — the one a key names when no `policy` is given. */
162
195
  export function fPoolPolicyFor(c, slot) {
@@ -170,39 +203,47 @@ export function fPoolPolicyFor(c, slot) {
170
203
  export async function fPoolPolicyOf(c, poolId) {
171
204
  return (await rawFPool(c, poolId)).policy;
172
205
  }
173
- const SWAP_MODES = ["open", "operator", "listed"];
174
- /** The swap modes in `SponsorPolicyBase.SwapMode` order — the index is the on-chain ordinal. */
175
- export const fPoolSwapModes = SWAP_MODES;
176
- /** 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. */
177
210
  export async function getFPoolRoles(c, poolId, state) {
178
- const s = state ?? (await getFPool(c, poolId));
179
- const rdPolicy = (abi, functionName) => c.public.readContract({ address: s.policy, abi, functionName, args: [poolId] });
180
- const [authority, maxHarvest] = await Promise.all([
181
- rdPolicy(fPolicyBaseAbi, "authority"),
182
- s.kind === "orphan" ? Promise.resolve(0n) : 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]),
183
218
  ]);
184
- if (s.kind !== "sponsor")
185
- return { policy: s.policy, authority, operator: ZERO_ADDRESS, gateMint: false, swapMode: "open", maxHarvest };
186
- const [operator, gateMint, mode] = await Promise.all([
187
- rdPolicy(sponsorPolicyFAbi, "operator"),
188
- rdPolicy(sponsorPolicyFAbi, "gateMint"),
189
- rdPolicy(sponsorPolicyFAbi, "swapMode"),
190
- ]);
191
- return { policy: s.policy, authority, operator, gateMint, swapMode: SWAP_MODES[Number(mode)] ?? "open", 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 };
192
234
  }
193
235
  export async function describeFPool(c, s) {
194
- // an unfunded pool has no L: nothing earned, nothing to harvest, no income. The bid is the
195
- // manager's ceiling (`harvestable()` until F version 21, which cut the getter): Q once seeded.
196
- const harvestable = s.L > 0n ? s.Q : 0n;
197
- const unharvested = s.L > 0n ? s.unharvested : 0n;
198
- 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);
199
239
  return {
200
- shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
240
+ shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
201
241
  legs: s.bases.length,
202
242
  atFloor: s.Q === 0n,
203
- unharvested,
204
- harvestable,
243
+ unharvested: s.L > 0n ? s.unharvested : 0n,
205
244
  income,
245
+ capitalRoom: capital,
246
+ harvestable: income + capital,
206
247
  };
207
248
  }
208
249
  /** `p_j = e^{x_j}`, lossy the way any float conversion is. Compare in log space when it matters. */
@@ -375,17 +416,19 @@ export async function fPoolPreviewRollIn(c, poolId, gen, holder, shares) {
375
416
  }));
376
417
  return { dL, quoteShort, quoteExcess };
377
418
  }
378
- // ─── the floor lever (authority only) ─────────────────────────────────────────
419
+ // ─── the floor lever (the operator's) ─────────────────────────────────────────
379
420
  /**
380
- * Remove quote, lifting logFloor — price-neutral, no base moves, and a DIVIDEND to
381
- * every share: the amount goes into the pool's held income and each holder's slice is settled lazily on
382
- * their next transfer, mint or burn, or pulled with {@link fPoolClaim}. The sponsor's own slice —
383
- * its shares' and the locked seed's at 0xdead — is pushed to `to` at once. On a pad
384
- * the lift stops at the seed floor, refLogFloor (income only); nothing else bounds it — an
385
- * 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`).
386
429
  */
387
430
  export async function fPoolHarvest(c, a) {
388
- 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);
389
432
  }
390
433
  /**
391
434
  * Pull one's settled dividend on a generation's shares without moving them;
@@ -674,6 +717,54 @@ export async function fPoolQuoteSwap(c, a) {
674
717
  throw new Error("logswap: quoteSwap returned without reverting, which it must never do");
675
718
  }
676
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
+ }
677
768
  /** `bytes32` ⇄ short UTF-8 text, for the pool and sponsor labels. */
678
769
  export function textToBytes32(text) {
679
770
  const b = new TextEncoder().encode(text);
@@ -695,48 +786,41 @@ export function sortFPoolLegs(bases, ...companions) {
695
786
  const idx = bases.map((_, i) => i).sort((a, b) => (bases[a].toLowerCase() < bases[b].toLowerCase() ? -1 : 1));
696
787
  return { bases: idx.map((i) => bases[i]), companions: companions.map((arr) => idx.map((i) => arr[i])) };
697
788
  }
698
- 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 = [
699
791
  {
700
792
  type: "tuple",
701
793
  components: [
702
794
  { name: "quote", type: "address" },
703
795
  { name: "bases", type: "address[]" },
704
- { name: "swapFee", type: "uint256" },
796
+ { name: "swapFeeIdx", type: "uint8" },
705
797
  { name: "policy", type: "address" },
706
- { name: "creator", type: "address" },
707
798
  { name: "salt", type: "bytes32" },
708
- { name: "mintFee", type: "uint256" },
709
799
  ],
710
800
  },
711
801
  ];
712
802
  /**
713
803
  * An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
714
- * manager's `idOf(FPoolKey)` getter was cut in F version 21; this is the same hash (checked
715
- * against Foundry's encoder and the local deployment's pools in the tests). The key must be the
716
- * 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).
717
806
  */
718
807
  export function fPoolIdOfKey(key) {
719
808
  return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
720
809
  }
721
- /** 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). */
722
811
  export function fPoolKeyOf(c, a) {
723
812
  const { bases } = sortFPoolLegs(a.bases);
724
- return {
725
- quote: a.quote,
726
- bases,
727
- swapFee: a.swapFee,
728
- policy: a.policy ?? fPoolPolicyFor(c, a.kind),
729
- creator: a.creator,
730
- salt: a.salt ?? ZERO_SALT,
731
- mintFee: a.mintFee ?? presetMintFee(a.swapFee),
732
- };
813
+ return { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy ?? fPoolPolicyFor(c, a.kind), salt: a.salt ?? ZERO_SALT };
733
814
  }
734
- /** 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
+ */
735
822
  export async function fPoolInitialize(c, a) {
736
823
  const key = fPoolKeyOf(c, a);
737
- if (!isValidMintFee(key.swapFee, key.mintFee)) {
738
- throw new Error(`logswap: mint fee ${key.mintFee} is outside 2 × the swap fee (${2n * key.swapFee}) … ${MINT_FEE_MAX}`);
739
- }
740
824
  const wallet = requireWallet(c);
741
825
  const { request } = await c.public.simulateContract({
742
826
  address: c.addresses.managerF,
@@ -756,10 +840,8 @@ export async function fPoolIdOf(c, a) {
756
840
  return fPoolIdOfKey(fPoolKeyOf(c, a));
757
841
  }
758
842
  /**
759
- * Rebuild a live pool's KEY from its id: the `PoolCreated` log carries every field but the salt,
760
- * which is taken from `opts.salt` (zero by default — every pool the SDK's create flow makes
761
- * 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
762
- * 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.
763
845
  */
764
846
  export async function fPoolKeyOfPool(c, poolId, opts = {}) {
765
847
  const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
@@ -768,29 +850,9 @@ export async function fPoolKeyOfPool(c, poolId, opts = {}) {
768
850
  if (!l)
769
851
  throw new Error(`logswap: no PoolCreated for F pool ${poolId}`);
770
852
  const a = l.args;
771
- const key = {
772
- quote: a.quote,
773
- bases: [...a.bases],
774
- swapFee: a.swapFee,
775
- policy: a.policy,
776
- creator: a.creator,
777
- salt: opts.salt ?? ZERO_SALT,
778
- mintFee: a.mintFee,
779
- };
780
- if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
781
- // a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
782
- try {
783
- const creatorShare = BigInt((await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "creatorShareOf", args: [poolId] })));
784
- const padKey = { ...key, salt: padSalt({ creatorShare }) };
785
- if (fPoolIdOfKey(padKey).toLowerCase() === poolId.toLowerCase())
786
- return padKey;
787
- }
788
- catch {
789
- /* not a pad: fall through to the error */
790
- }
791
- }
853
+ const key = { quote: a.quote, bases: [...a.bases], swapFeeIdx: Number(a.swapFeeIdx), policy: a.policy, salt: a.salt };
792
854
  if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase()) {
793
- 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`);
794
856
  }
795
857
  return key;
796
858
  }
@@ -926,78 +988,64 @@ export function fPoolBookL(baseAssets, lnCapOverSeed) {
926
988
  * carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
927
989
  * carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
928
990
  */
991
+ /**
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}.
998
+ */
929
999
  export async function fPoolDeploy(c, a) {
930
1000
  const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
931
- return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed, a.to ?? a.account], a.account);
1001
+ return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed], a.account);
932
1002
  }
933
1003
  /**
934
- * Close the pool — the raw entry (`retire` before F 38). Allowed only at an empty bid, Q ≤ L/1e9, on every pool but a
935
- * pad: the market took it, or the operator harvested it out first ({@link fPoolClose} does both in one transaction).
936
- * Income settles to `to` first. The live (S, Q, R_j) become a frozen bundle every share of this generation redeems
937
- * ({@link fPoolRedeem}), forever; the pool is unfunded until the next {@link fPoolDeploy}, which opens generation
938
- * `gen + 1` under the same id, policy, roles, gates and lists. Whoever runs the pool.
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.
939
1009
  */
940
- export async function fPoolCloseRaw(c, a) {
1010
+ export async function fPoolClose(c, a) {
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");
941
1014
  return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
942
1015
  }
943
1016
  /**
944
- * Close the pool as ONE transaction: the harvest that empties the bid
945
- * ({@link fPoolEmptyingHarvests} — a dividend to every share; none when it is already empty),
946
- * then `close` — the manager's `multicall`, the operator as sender. What a sponsor's "close" button
947
- * should call. Throws before sending on a pad: a pad never closes.
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`.
948
1020
  */
949
- export async function fPoolClose(c, a) {
950
- const harvests = await fPoolEmptyingHarvests(c, a.poolId);
951
- if (harvests.length === 0)
952
- return fPoolCloseRaw(c, a);
1021
+ export function fPoolRelaunchCalls(a) {
1022
+ const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
953
1023
  const enc = (functionName, args) => encodeFunctionData({ abi: managerFAbi, functionName, args });
954
- const calls = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("close", [a.poolId, a.to ?? a.account])];
955
- return writeFPool0(c, "multicall", [calls], a.account);
956
- }
957
- /**
958
- * The harvests that empty an unlocked pool's bid, in order — what a close sends before its
959
- * `close` (a close needs an empty bid on every pool). One `harvest(Q)` does it: the income tax leaves the pool with
960
- * the income part (with no treasury there is none). `[]` when the bid is already empty. Throws on a pad (a pad
961
- * never closes, whatever its bid), and when the pool's policy keeps a floor on the bid
962
- * (`PolPolicy.minQuoteRatio`): a `close` under that policy waits for the market.
963
- */
964
- export async function fPoolEmptyingHarvests(c, poolId) {
965
- const s = await getFPool(c, poolId);
966
- // `PadPolicy` refuses `close` at any bid — a pad graduates (regenerate), it never closes; a fresh start is a new pad
967
- if (s.kind === "pad")
968
- throw new Error("logswap: a pad never closes — it graduates by regenerate; a fresh start is a new pad");
969
- if (s.Q === 0n)
970
- return [];
971
- const { maxHarvest } = await getFPoolRoles(c, poolId, s);
972
- if (maxHarvest < s.Q)
973
- throw new Error("logswap: the pool's policy keeps a floor on the bid — it cannot be harvested empty");
974
- return [s.Q];
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;
975
1029
  }
976
1030
  /**
977
- * The GENERATION STEP — on a pad, its graduation (F 38: `deployLiquidity` with nothing changed). The manager
978
- * harvests the generation's income first, releases the dead shares' income, and asks the policy
979
- * (`onRegenerate`), whose {@link FPolicyTerms} name a `carried` holder. Then, for live
980
- * generation `g`:
981
- *
982
- * - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
983
- * as the pool;
984
- * - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`GenerationRetired`)
985
- * and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
986
- * dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
987
- * lists them;
988
- * - the income released (`IncomeReleased`), all in quote: `toPayee` to the payee and the rest into the bid
989
- * (the floor down). No share is minted; L does not move. The book keeps its reserves, marks and cap.
990
- *
991
- * A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and a non-canonical sponsored pool carry the
992
- * authority and send it the whole income; a canonical sponsored pool (the LOG's open instance) refuses (`Refused`). A carried holder with no
993
- * 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}).
994
1036
  */
995
- export async function fPoolRegenerate(c, a) {
996
- return writeFPool(c, a.poolId, "regenerate", [a.to ?? a.account], a.account);
997
- }
998
- /** 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. */
999
1047
  export const DEAD_ADDRESS = "0x000000000000000000000000000000000000dEaD";
1000
- /** 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. */
1001
1049
  export const F_MIN_SHARES = 1000n;
1002
1050
  /**
1003
1051
  * The launch's calls, in order — the batch {@link fPoolLaunch} sends. Pure, so a form can show
@@ -1010,21 +1058,13 @@ export function fPoolLaunchCalls(poolId, a) {
1010
1058
  throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
1011
1059
  const { baseAssets, lnCapOverSeed } = fPoolBook(a);
1012
1060
  const bases = baseAssets.map((x) => x.base);
1013
- const key = {
1014
- quote: a.quote,
1015
- bases,
1016
- swapFee: a.swapFee,
1017
- policy: a.policy,
1018
- creator: a.creator,
1019
- salt: a.salt ?? ZERO_SALT,
1020
- mintFee: a.mintFee ?? presetMintFee(a.swapFee),
1021
- };
1061
+ const key = { quote: a.quote, bases, swapFeeIdx: fPoolSwapFeeIdxOf(a), policy: a.policy, salt: a.salt ?? ZERO_SALT };
1022
1062
  const enc = (functionName, args) => encodeFunctionData({ abi: managerFAbi, functionName, args });
1023
1063
  const calls = [];
1024
1064
  if (!a.initialized)
1025
1065
  calls.push(enc("initialize", [key]));
1026
- calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed, a.account]));
1027
- // 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.
1028
1068
  // No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
1029
1069
  for (const row of fPoolGenesisRows(a)) {
1030
1070
  const j = bases.indexOf(a.bases[row.j]);
@@ -1032,9 +1072,8 @@ export function fPoolLaunchCalls(poolId, a) {
1032
1072
  throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
1033
1073
  calls.push(enc(row.side === "buy" ? "swapQuoteIn" : "swapBaseIn", [poolId, BigInt(j), row.amountIn, row.minOut ?? 0n, a.account]));
1034
1074
  }
1035
- // the name, a sponsored policy's gates and its whitelist are the POLICY's, not the
1036
- // manager's: they cannot ride in this batch — `fPoolLaunch` and `fPoolDeskOpening` send them
1037
- // 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`
1038
1077
  calls.push(...(a.extra ?? []));
1039
1078
  return calls;
1040
1079
  }
@@ -1113,29 +1152,21 @@ export async function fPoolWalletBatchesAtomically(c, account) {
1113
1152
  }
1114
1153
  }
1115
1154
  /**
1116
- * The desk's opening posture, on its sponsored policy: gated minting (only the authority and the operator mint). The swap gate is
1117
- * 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
1118
- * that cannot ride in the launch batch (it is not a manager call).
1119
- */
1120
- export async function fPoolDeskOpening(c, a) {
1121
- const policy = a.policy ?? fPoolPolicyFor(c, "private");
1122
- return [await fPoolSetMintGate(c, { poolId: a.poolId, gated: true, account: a.account, policy })];
1123
- }
1124
- /**
1125
- * Create a pool as ONE transaction: `initialize`, `seed`, the seed lock, the opening buy, the
1126
- * name — the manager's `multicall`, the creator as sender throughout (the creator is the initializer, `NotCreator`).
1127
- * 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.
1128
1160
  *
1129
- * Why the manager and not the router: every one of these entries authenticates by `msg.sender`
1130
- * (`seed` is authority-only, so is everything after it). Routed, the router would be the sender
1131
- * — the authority, the holder of the seed shares — and `initialize` would refuse it (`NotCreator`). `multicall` is delegatecall-to-self, so the
1132
- * 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.
1133
1163
  *
1134
- * What the batch PULLS, by plain allowance to the manager (never Permit2): `r0[j]` of each base,
1135
- * `Q0` of quote, plus `openBuy.amountIn` of quote. Grant those first — one `approve` per token,
1136
- * 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}).
1137
1167
  *
1138
- * 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.
1139
1170
  */
1140
1171
  export async function fPoolLaunch(c, a) {
1141
1172
  const poolId = await fPoolIdOf(c, a);
@@ -1179,59 +1210,67 @@ export async function fPoolLaunch(c, a) {
1179
1210
  }
1180
1211
  // ─── the roles, on the policy ─────────────────────────────────────────────
1181
1212
  //
1182
- // Every write here goes to the pool's POLICY, not the manager: the manager holds no role. `policy`
1183
- // may be passed when in hand (`FPoolState.policy`, `FPoolRoles.policy`); otherwise it is read once.
1184
- /** A write keyed by poolId, on the pool's policy. */
1185
- 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) {
1186
1219
  const wallet = requireWallet(c);
1187
- const policy = a.policy ?? (await fPoolPolicyOf(c, a.poolId));
1188
- const { request } = await c.public.simulateContract({
1189
- address: policy,
1190
- abi,
1191
- functionName,
1192
- args: [a.poolId, ...args],
1193
- account: signerFor(c, a.account),
1194
- });
1220
+ const { request } = await c.public.simulateContract({ address: policy, abi: policyFAbi, functionName, args, account: signerFor(c, account) });
1195
1221
  return wallet.writeContract(request);
1196
1222
  }
1197
- // ─── a sponsored policy's per-pool settings (the authority's; decision 098) ───────────────
1198
- //
1199
- // `SponsorPolicyF` and `SponsorPolicyC` share these functions, so one ABI writes both: for a C market pass `policy: key.policy`
1200
- // (the default policy lookup reads F's lens). Where the policy offers no gates (`gatesAvailable` false: the LOG's open
1201
- // instance) the mode, gate and list writes revert with `GatesUnavailable`.
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);
1227
+ }
1202
1228
  /**
1203
- * 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
1204
- * runner of the pool; it may be a contract (an executor). Immediate, with no acceptance step, so check the address. Stamps the block.
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.
1205
1232
  */
1206
1233
  export async function fPoolAppointOperator(c, a) {
1207
- return writePolicy(c, sponsorPolicyFAbi, a, "appointOperator", [a.operator]);
1234
+ return writePoolPolicy(c, a, "appointOperator", [a.operator]);
1208
1235
  }
1209
1236
  /**
1210
- * Set swap admission (the authority's, where the policy offers gates): `open`, `operator` (only the operator swaps — needs one appointed) or
1211
- * `listed` (the whitelist, {@link fPoolSetListed}; the operator always passes). `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.
1212
1239
  */
1213
1240
  export async function fPoolSetSwapMode(c, a) {
1214
- return writePolicy(c, sponsorPolicyFAbi, a, "setSwapMode", [SWAP_MODES.indexOf(a.mode)]);
1241
+ return writePoolPolicy(c, a, "setSwapMode", [MODES.indexOf(a.mode)]);
1242
+ }
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)]);
1246
+ }
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;
1215
1253
  }
1216
- /** Turn the mint gate on or off (the authority's, where the policy offers gates): on, only the authority and the operator mint. */
1217
- export async function fPoolSetMintGate(c, a) {
1218
- return writePolicy(c, sponsorPolicyFAbi, a, "setMintGate", [a.gated]);
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";
1219
1258
  }
1220
1259
  /**
1221
- * 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).
1222
- * The one list: the free-form minter and taker lists are gone. Stamps the block: no swap lands in it (047).
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.
1223
1263
  */
1224
- export async function fPoolSetListed(c, a) {
1225
- return writePolicy(c, sponsorPolicyFAbi, a, "setListed", [a.who, a.listed]);
1264
+ export async function fPolicySetRights(c, a) {
1265
+ return writePolicy(c, a.policy, "setRights", [a.who, fPolicyRightBits(a.right)], a.account);
1226
1266
  }
1227
- /** On the pool's swap whitelist now (the sponsored policy's `listed`). */
1228
- export async function fPoolIsListed(c, poolId, who, policy) {
1229
- const address = policy ?? (await fPoolPolicyOf(c, poolId));
1230
- return (await c.public.readContract({ address, abi: sponsorPolicyFAbi, functionName: "listed", args: [poolId, who] }));
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] })));
1231
1270
  }
1232
- /** 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. */
1233
1272
  export async function fPoolSetName(c, a) {
1234
- return writePolicy(c, fPolicyBaseAbi, a, "setName", [textToBytes32(a.name)]);
1273
+ return writePoolPolicy(c, a, "setName", [textToBytes32(a.name)]);
1235
1274
  }
1236
1275
  /**
1237
1276
  * What the PROTOCOL says an address is — "Keyrock" — on the REGISTRY. Only its
@@ -1270,9 +1309,9 @@ async function registryAddress(c) {
1270
1309
  throw new Error("logswap: this deployment carries no policy registry");
1271
1310
  return registry;
1272
1311
  }
1273
- /** 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. */
1274
1313
  export function fPoolRunners(s) {
1275
- return s.operator === ZERO_ADDRESS ? [s.authority] : [s.authority, s.operator];
1314
+ return s.operator === ZERO_ADDRESS ? [] : [s.operator];
1276
1315
  }
1277
1316
  /**
1278
1317
  * Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
@@ -1292,11 +1331,10 @@ export async function fPoolTransferShares(c, a) {
1292
1331
  return wallet.writeContract(request);
1293
1332
  }
1294
1333
  /**
1295
- * Every F pool ever created, from `PoolCreated` logs alone — plus one `kind()` read per distinct
1296
- * policy, cached. Possible only because the event carries the full key preimage (quote, creator, bases,
1297
- * swapFee, policy, mintFee) — the poolId is a hash and could never be inverted; contracts PR #17
1298
- * exists for exactly this call. With `indexer`, the logs come from it (the node when it fails):
1299
- * 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.
1300
1338
  */
1301
1339
  export async function discoverFPools(c, opts = {}) {
1302
1340
  const ev = managerFAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
@@ -1320,17 +1358,19 @@ export async function discoverFPools(c, opts = {}) {
1320
1358
  const a = l.args;
1321
1359
  const g0 = first.get(a.poolId.toLowerCase());
1322
1360
  const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
1361
+ const swapFeeIdx = Number(a.swapFeeIdx);
1323
1362
  return {
1324
1363
  poolId: a.poolId,
1325
1364
  quote: a.quote,
1326
1365
  bases: [...a.bases],
1327
1366
  weights: g0?.weights ?? [],
1328
- swapFee: a.swapFee,
1329
- mintFee: a.mintFee,
1367
+ swapFeeIdx,
1368
+ swapFee: fFeeOf(swapFeeIdx),
1369
+ mintFee: fMintFeeOf(swapFeeIdx),
1330
1370
  lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
1331
1371
  kind,
1332
1372
  policy: a.policy,
1333
- creator: a.creator,
1373
+ salt: a.salt,
1334
1374
  block: l.blockNumber,
1335
1375
  seeded: g0 !== undefined,
1336
1376
  q0: g0?.q0 ?? 0n,
@@ -1338,86 +1378,22 @@ export async function discoverFPools(c, opts = {}) {
1338
1378
  };
1339
1379
  }));
1340
1380
  }
1341
- const MAX_U64 = (1n << 64n) - 1n;
1342
- const MAX_U128 = (1n << 128n) - 1n;
1343
- /**
1344
- * The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
1345
- * 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
1346
- * 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
1347
- * chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
1348
- */
1349
- export function padSalt(s) {
1350
- const nonce = s.nonce ?? 0n;
1351
- if (s.burnShare !== undefined && s.burnShare !== 0n)
1352
- throw new Error("logswap: a pad has no burn share since F version 28 (decision 067)");
1353
- if (s.creatorShare < 0n || s.creatorShare > MAX_U64)
1354
- throw new Error("logswap: a pad's creator share is a WAD fraction that fits 64 bits");
1355
- if (nonce < 0n || nonce > MAX_U128)
1356
- throw new Error("logswap: a pad salt's nonce fits 128 bits");
1357
- return `0x${((s.creatorShare << 192n) | nonce).toString(16).padStart(64, "0")}`;
1358
- }
1359
- /** The inverse of {@link padSalt}. `burnShare` is the old field's bits, nonzero only on a salt the F version 28 policy refuses. */
1360
- export function padSplitOfSalt(salt) {
1361
- const v = BigInt(salt);
1362
- return { creatorShare: v >> 192n, burnShare: (v >> 128n) & MAX_U64, nonce: v & MAX_U128 };
1363
- }
1364
- /** The policy's terms for one pool, by its kind. */
1365
- export async function getFPoolRules(c, s, roles) {
1366
- const rd = (abi, functionName, args = []) => c.public.readContract({ address: s.policy, abi, functionName, args });
1367
- switch (s.kind) {
1368
- case "pad": {
1369
- // the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
1370
- const gen = s.gen;
1371
- const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
1372
- rd(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
1373
- fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
1374
- rd(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
1375
- rd(padPolicyAbi, "incomeTaxRate"),
1376
- rd(padPolicyAbi, "creatorShareMin"),
1377
- rd(padPolicyAbi, "creatorShareMax"),
1378
- ]);
1379
- const ranges = { creatorShareMin, creatorShareMax };
1380
- return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
1381
- }
1382
- case "pol": {
1383
- const [minQuoteRatio, incomeTaxRate] = await Promise.all([rd(polPolicyAbi, "minQuoteRatio"), rd(polPolicyAbi, "incomeTaxRate")]);
1384
- return { kind: "pol", minQuoteRatio, incomeTaxRate };
1385
- }
1386
- case "sponsor": {
1387
- const r = roles ?? (await getFPoolRoles(c, s.poolId, s));
1388
- const [sponsor, canonical, gatesAvailable, bornGated, swapTiers, mintTiers] = await Promise.all([
1389
- rd(sponsorPolicyFAbi, "sponsor"),
1390
- rd(sponsorPolicyFAbi, "canonical"),
1391
- rd(sponsorPolicyFAbi, "gatesAvailable"),
1392
- rd(sponsorPolicyFAbi, "bornGated"),
1393
- rd(sponsorPolicyFAbi, "swapTiers"),
1394
- rd(sponsorPolicyFAbi, "mintTiers"),
1395
- ]);
1396
- return { kind: "sponsor", sponsor, canonical, gatesAvailable, bornGated, swapTiers, mintTiers, gateMint: r.gateMint, swapMode: r.swapMode, operator: r.operator };
1397
- }
1398
- case "orphan": {
1399
- return { kind: "orphan" };
1400
- }
1401
- }
1402
- }
1403
1381
  /**
1404
- * Every F pool `who` is the AUTHORITY of, across the policies — the policy page's list. The authority is `key.creator` for
1405
- * life (decision 098), so these are the pools `who` created, minus any the LOG orphaned. `pools` may be passed (from the
1406
- * 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.
1407
1384
  */
1408
1385
  export async function fPoolsControlledBy(c, who, opts = {}) {
1409
1386
  const pools = opts.pools ?? (await discoverFPools(c, { fromBlock: opts.fromBlock }));
1410
- // the LIVE policy answers for the authority: a moved pool (046) is on another one than its birth's
1411
1387
  const states = await Promise.all(pools.map((p) => getFPool(c, p.poolId)));
1412
- 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();
1413
1390
  const out = [];
1414
1391
  for (let i = 0; i < pools.length; ++i) {
1415
- if (authorities[i].toLowerCase() !== who.toLowerCase())
1392
+ const r = roles[i];
1393
+ if (r.operator.toLowerCase() !== me && r.authority.toLowerCase() !== me)
1416
1394
  continue;
1417
1395
  const state = states[i];
1418
- const roles = await getFPoolRoles(c, state.poolId, state);
1419
- const rules = await getFPoolRules(c, state, roles);
1420
- out.push({ pool: pools[i], roles, state, rules });
1396
+ out.push({ pool: pools[i], roles: r, state, terms: await fPolicyTermsOf(c, state.policy) });
1421
1397
  }
1422
1398
  return out;
1423
1399
  }