@logswap/sdk 0.5.79 → 0.5.81

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
@@ -50,6 +50,7 @@ import { fallBackUnlessRejected, signerFor } from "./write.js";
50
50
  import { getEventLogs } from "./history.js";
51
51
  import { poolHolders } from "./views.js";
52
52
  import { presetMintFee } from "./positions.js";
53
+ import { isValidMintFee, MINT_FEE_MAX } from "./keys.js";
53
54
  const WAD = 10n ** 18n;
54
55
  const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
55
56
  /** The optional questions a policy declared at birth, as bits of `Pool.asks`. */
@@ -90,9 +91,9 @@ export async function getFPool(c, poolId) {
90
91
  return {
91
92
  poolId,
92
93
  quote: p.quote,
93
- bases: v.legs.map((l) => l.base),
94
- weights: v.legs.map((l) => l.weight),
95
- x: v.legs.map((l) => l.x), // derived by the manager: x_j = ln(w_j·L / R̃_j)
94
+ bases: v.baseLegs.map((l) => l.base),
95
+ weights: v.baseLegs.map((l) => l.weight),
96
+ x: v.baseLegs.map((l) => l.x), // derived by the manager: x_j = ln(w_j·L / R̃_j)
96
97
  Q: p.Q,
97
98
  L: p.L,
98
99
  swapFee: p.swapFee,
@@ -101,8 +102,8 @@ export async function getFPool(c, poolId) {
101
102
  logFloor: v.logFloor,
102
103
  compositeX: v.compositeX,
103
104
  unharvested: v.unharvested,
104
- lnCapOverFloor: Number(p.lnCapOverFloor),
105
- bigSigma: p.bigSigma,
105
+ lnCapOverSeed: Number(p.lnCapOverSeed),
106
+ realizedVariance: p.realizedVariance,
106
107
  policy: p.policy,
107
108
  asks: Number(p.asks),
108
109
  name,
@@ -111,9 +112,9 @@ export async function getFPool(c, poolId) {
111
112
  seeded: p.seeded,
112
113
  gen: Number(p.gen),
113
114
  totalSupply: p.shares,
114
- reserves: v.legs.map((l) => l.reserve), // the state
115
- virtualReserves: v.legs.map((l) => l.virtualReserve),
116
- kappa: v.legs.map((l) => l.kappa),
115
+ reserves: v.baseLegs.map((l) => l.reserve), // the state
116
+ virtualReserves: v.baseLegs.map((l) => l.virtualReserve),
117
+ kappa: v.baseLegs.map((l) => l.kappa),
117
118
  };
118
119
  }
119
120
  const F_KIND_NAMES = ["public", "private", "pol", "pad"];
@@ -159,6 +160,7 @@ export function fPoolPolicyFor(c, kind) {
159
160
  export async function fPoolPolicyOf(c, poolId) {
160
161
  return (await rawFPool(c, poolId)).policy;
161
162
  }
163
+ const SWAP_MODES = ["open", "listed", "executor"];
162
164
  /** Read a pool's roles from its policy. `state` saves the `getPool` round trip when already in hand. */
163
165
  export async function getFPoolRoles(c, poolId, state) {
164
166
  const s = state ?? (await getFPool(c, poolId));
@@ -170,29 +172,25 @@ export async function getFPoolRoles(c, poolId, state) {
170
172
  rdPolicy(fPolicyBaseAbi, "maxHarvest"),
171
173
  ]);
172
174
  const desk = s.kind === "private";
173
- const [operator, pendingOperator, gateMint, gateSwap] = desk
174
- ? await Promise.all([
175
- rdPolicy(privatePolicyAbi, "operator"),
176
- rdPolicy(privatePolicyAbi, "pendingOperator"),
177
- rdPolicy(privatePolicyAbi, "gateMint"),
178
- rdPolicy(privatePolicyAbi, "gateSwap"),
179
- ])
180
- : [ZERO_ADDRESS, ZERO_ADDRESS, false, false];
181
- return { policy: s.policy, creator, authority, pendingAuthority, operator, pendingOperator, gateMint, gateSwap, maxHarvest };
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 };
182
180
  }
183
181
  export async function describeFPool(c, s) {
184
- // an unseeded pool has no L: nothing earned, nothing to harvest, no pot. The bid is the
182
+ // an unfunded pool has no L: nothing earned, nothing to harvest, no income. The bid is the
185
183
  // manager's ceiling (`harvestable()` until F version 21, which cut the getter): Q once seeded.
186
184
  const harvestable = s.L > 0n ? s.Q : 0n;
187
185
  const unharvested = s.L > 0n ? s.unharvested : 0n;
188
- const pot = s.L > 0n ? await fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, s.gen) : 0n;
186
+ const income = s.L > 0n ? await fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, s.gen) : 0n;
189
187
  return {
190
188
  shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
191
189
  legs: s.bases.length,
192
190
  atFloor: s.Q === 0n,
193
191
  unharvested,
194
192
  harvestable,
195
- pot,
193
+ income,
196
194
  };
197
195
  }
198
196
  /** `p_j = e^{x_j}`, lossy the way any float conversion is. Compare in log space when it matters. */
@@ -208,7 +206,7 @@ export function fPoolShareValue(s) {
208
206
  if (s.totalSupply === 0n)
209
207
  return 0n;
210
208
  let v = s.L + s.Q;
211
- if (s.lnCapOverFloor !== 0) {
209
+ if (s.lnCapOverSeed !== 0) {
212
210
  v = s.Q;
213
211
  for (let j = 0; j < s.reserves.length; j++) {
214
212
  const rv = s.virtualReserves[j];
@@ -368,7 +366,7 @@ export async function fPoolPreviewRollIn(c, poolId, gen, holder, shares) {
368
366
  // ─── the floor lever (authority only) ─────────────────────────────────────────
369
367
  /**
370
368
  * Remove quote, lifting θ — price-neutral, no base moves, and a DIVIDEND to
371
- * every share: the amount goes into the pool's pot and each holder's slice is settled lazily on
369
+ * every share: the amount goes into the pool's held income and each holder's slice is settled lazily on
372
370
  * their next transfer, mint or burn, or pulled with {@link fPoolClaim}. The sponsor's own slice —
373
371
  * its shares' and the locked seed's at 0xdead — is pushed to `to` at once. On a pad
374
372
  * the lift stops at the seed floor θ₀ (income only); nothing else bounds it — an
@@ -423,7 +421,7 @@ export async function fPoolLienOf(c, poolId, owner, gen) {
423
421
  */
424
422
  export async function fPoolLock(c, a) {
425
423
  const g = a.gen ?? (await fPoolGen(c, a.poolId));
426
- return writeFPool0(c, "lock", [fPoolShareId(a.poolId, g), a.owner, a.amount], a.account);
424
+ return writeFPool0(c, "lienLock", [fPoolShareId(a.poolId, g), a.owner, a.amount], a.account);
427
425
  }
428
426
  /**
429
427
  * The locker's `unlock`: `amount` of the lien lifted with its share of the lien's dividend, credited
@@ -432,7 +430,7 @@ export async function fPoolLock(c, a) {
432
430
  */
433
431
  export async function fPoolUnlock(c, a) {
434
432
  const g = a.gen ?? (await fPoolGen(c, a.poolId));
435
- return writeFPool0(c, "unlock", [fPoolShareId(a.poolId, g), a.owner, a.amount, a.to], a.account);
433
+ return writeFPool0(c, "lienUnlock", [fPoolShareId(a.poolId, g), a.owner, a.amount, a.to], a.account);
436
434
  }
437
435
  /** Bank the owner's pending into the lien now — `unlock(id, owner, 0, owner)`: dividends bank lazily. The locker's. */
438
436
  export async function fPoolBankLien(c, a) {
@@ -719,12 +717,11 @@ const F_POOL_KEY_ABI = [
719
717
  components: [
720
718
  { name: "quote", type: "address" },
721
719
  { name: "bases", type: "address[]" },
722
- { name: "weights", type: "uint256[]" },
723
720
  { name: "swapFee", type: "uint256" },
724
721
  { name: "policy", type: "address" },
725
722
  { name: "creator", type: "address" },
726
723
  { name: "salt", type: "bytes32" },
727
- { name: "lnCapOverFloor", type: "uint24" },
724
+ { name: "mintFee", type: "uint256" },
728
725
  ],
729
726
  },
730
727
  ];
@@ -732,36 +729,36 @@ const F_POOL_KEY_ABI = [
732
729
  * An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
733
730
  * manager's `idOf(FPoolKey)` getter was cut in F version 21; this is the same hash (checked
734
731
  * against Foundry's encoder and the local deployment's pools in the tests). The key must be the
735
- * one the pool was initialized with: legs sorted ({@link fPoolKeyOf} sorts them), the birth policy.
732
+ * one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them), the birth policy.
736
733
  */
737
734
  export function fPoolIdOfKey(key) {
738
735
  return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
739
736
  }
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). */
740
738
  export function fPoolKeyOf(c, a) {
741
- const { bases, companions } = sortFPoolLegs(a.bases, a.weights);
739
+ const { bases } = sortFPoolLegs(a.bases);
742
740
  return {
743
741
  quote: a.quote,
744
742
  bases,
745
- weights: companions[0],
746
743
  swapFee: a.swapFee,
747
744
  policy: a.policy ?? fPoolPolicyFor(c, a.kind),
748
745
  creator: a.creator,
749
746
  salt: a.salt ?? ZERO_SALT,
750
- lnCapOverFloor: fPoolCapOfArgs(a),
747
+ mintFee: a.mintFee ?? presetMintFee(a.swapFee),
751
748
  };
752
749
  }
753
- /** Create the pool (no funds move — `seed` arms it). Returns the tx hash; read the id with `fPoolIdOf`. */
750
+ /** Create the pool (no funds move — `deployLiquidity` funds it). Returns the tx hash; read the id with `fPoolIdOf`. */
754
751
  export async function fPoolInitialize(c, a) {
755
- const sum = a.weights.reduce((x, y) => x + y, 0n);
756
- if (sum !== 10n ** 18n)
757
- throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
758
752
  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
+ }
759
756
  const wallet = requireWallet(c);
760
757
  const { request } = await c.public.simulateContract({
761
758
  address: c.addresses.fPoolManager,
762
759
  abi: fPoolManagerAbi,
763
760
  functionName: "initialize",
764
- args: [key, a.mintFee ?? presetMintFee(a.swapFee)],
761
+ args: [key],
765
762
  account: wallet.account,
766
763
  });
767
764
  return c.wallet.writeContract(request);
@@ -790,17 +787,16 @@ export async function fPoolKeyOfPool(c, poolId, opts = {}) {
790
787
  const key = {
791
788
  quote: a.quote,
792
789
  bases: [...a.bases],
793
- weights: [...a.weights],
794
790
  swapFee: a.swapFee,
795
791
  policy: a.policy,
796
792
  creator: a.creator,
797
793
  salt: opts.salt ?? ZERO_SALT,
798
- lnCapOverFloor: Number(a.lnCapOverFloor ?? a.cap ?? 0), // `cap` before F version 27
794
+ mintFee: a.mintFee,
799
795
  };
800
796
  if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
801
797
  // a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
802
798
  try {
803
- const [creatorShare] = (await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "splitOf", args: [poolId] }));
799
+ const creatorShare = BigInt((await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "creatorShareOf", args: [poolId] })));
804
800
  const padKey = { ...key, salt: padSalt({ creatorShare }) };
805
801
  if (fPoolIdOfKey(padKey).toLowerCase() === poolId.toLowerCase())
806
802
  return padKey;
@@ -815,35 +811,30 @@ export async function fPoolKeyOfPool(c, poolId, opts = {}) {
815
811
  return key;
816
812
  }
817
813
  /**
818
- * The reserve a leg holds at a mark: `R = Lj·e^{−x}`, WAD math. The seed names RESERVES —
819
- * the sponsor states holdings and the price follows, `p = Lj / R` — so this is
820
- * the one conversion from a price to what the pool will hold, done here, on the way in. Float
821
- * precision (~1e-16 relative) is what a seed needs: any reserve is a legal seed, and the mark
814
+ * The reserve a leg holds at a mark: `R = Lj·e^{−x}`, WAD math. A deployment names the TOTAL base
815
+ * reserve and the price that values it, and the price follows from the pair, `p = Lj / R` — so this is
816
+ * the one conversion from a wanted mark to what the pool will hold, done here, on the way in. Float
817
+ * precision (~1e-16 relative) is what a deployment needs: any reserve is legal, and the mark
822
818
  * the pool derives from it is the one the sponsor meant to within that.
823
819
  */
824
820
  export function fPoolReserveAt(Lj, x, k = 0) {
825
- // on a capped pool (decisions 061) the mark reads the virtual reserve R̃ = R + c, and the seed
826
- // puts c = R·k/(1 − k): so the REAL reserve for a mark is L_j·e^{−x}·(1 − k)
821
+ // on a capped pool (decisions 061) the mark reads the virtual reserve R̃ = R + c, and the
822
+ // deployment puts c = R·k/(1 − k): so the REAL reserve for a mark is L_j·e^{−x}·(1 − k)
827
823
  const e = Math.exp(-Number(x) / 1e18) * (1 - k);
828
824
  return (Lj * BigInt(Math.round(e * 1e18))) / 10n ** 18n;
829
825
  }
830
826
  /**
831
- * The seed's cap constant k = e^{Q0/L0 − d} (decisions 061): every leg's phantom is c_j = r_j·k/(1 − k).
832
- * 0 on an uncapped pool. Throws when the seed would be priced at or above its cap (Q0/L0 ≥ d), which
833
- * the manager refuses.
827
+ * The cap constant k = e^{−lnCapOverSeed} (decisions 061, 075): every leg's phantom is c_j = r_j·k/(1 − k), and the
828
+ * generation's liquidity is its base value over 1 − k. 0 on an uncapped pool. It no longer depends on the bid:
829
+ * the cap is a ratio of the cap price to each asset's own seed price.
834
830
  */
835
- export function fPoolCapK(lnCapOverFloor, Q0, L0) {
836
- if (lnCapOverFloor === 0)
837
- return 0;
838
- const e = Number((Q0 * WAD) / L0) / 1e18 - lnCapOverFloor / 1e6;
839
- if (e >= 0)
840
- throw new Error(`logswap: a seed with Q0/L0 = ${Number((Q0 * WAD) / L0) / 1e18} is at or above its cap, ln(cap/floor) = ${lnCapOverFloor / 1e6}`);
841
- return Math.exp(e);
831
+ export function fPoolCapK(lnCapOverSeed) {
832
+ return lnCapOverSeed === 0 ? 0 : Math.exp(-lnCapOverSeed / 1e6);
842
833
  }
843
834
  /**
844
- * The key's `lnCapOverFloor` = ln(cap/floor) (1e-6 log units) for a leverage λ at the floor: ln(λ/(λ − 1))
845
- * (decisions 061), so λ = 1/(1 − floor/cap) and the cap sits λ/(λ − 1) × the floor — λ = 2 puts it at twice.
846
- * **λ = 1 is uncapped**: cap ∞, `lnCapOverFloor` 0. A λ under 1, or one so close to
835
+ * The pool's `lnCapOverSeed` = ln(cap price / seed price) (1e-6 log units) for a leverage λ: ln(λ/(λ − 1))
836
+ * (decisions 061), so λ = 1/(1 − seed/cap) = L / (base value) and the cap sits λ/(λ − 1) × the seed price — λ = 2
837
+ * puts it at twice. **λ = 1 is uncapped**: cap ∞, `lnCapOverSeed` 0. A λ under 1, or one so close to
847
838
  * 1 (or so large) that d leaves a uint24 of 1e-6 units, is refused.
848
839
  */
849
840
  export function fPoolCapOfLeverage(lambda) {
@@ -856,85 +847,141 @@ export function fPoolCapOfLeverage(lambda) {
856
847
  throw new Error(`logswap: leverage ${lambda} needs a cap outside a uint24 of 1e-6 units`);
857
848
  return d;
858
849
  }
859
- /** The leverage at the floor λ = 1/(1 − e^{−x}) for x = `lnCapOverFloor` (1e-6 log units); 1 for an uncapped pool (cap ∞). */
860
- export function fPoolLeverageOfCap(lnCapOverFloor) {
861
- return lnCapOverFloor === 0 ? 1 : 1 / (1 - Math.exp(-lnCapOverFloor / 1e6));
850
+ /** The leverage λ = 1/(1 − e^{−x}) for x = `lnCapOverSeed` (1e-6 log units); 1 for an uncapped pool (cap ∞). */
851
+ export function fPoolLeverageOfCap(lnCapOverSeed) {
852
+ return lnCapOverSeed === 0 ? 1 : 1 / (1 - Math.exp(-lnCapOverSeed / 1e6));
862
853
  }
863
854
  /**
864
- * The leverage tag of a pool from its key's `lnCapOverFloor` (decisions 061): `1×` means no cap — the only way a tag
855
+ * The leverage tag of a pool from its `lnCapOverSeed` (decisions 061): `1×` means no cap — the only way a tag
865
856
  * reads 1× — and a capped pool always reads above it, so the two can never be confused on screen.
866
857
  */
867
- export function fPoolLeverage(lnCapOverFloor) {
868
- if (lnCapOverFloor === 0)
869
- return { lambda: 1, capped: false, capOverFloor: Infinity, label: "1×" };
870
- const lambda = fPoolLeverageOfCap(lnCapOverFloor);
858
+ export function fPoolLeverage(lnCapOverSeed) {
859
+ if (lnCapOverSeed === 0)
860
+ return { lambda: 1, capped: false, capOverSeed: Infinity, label: "1×" };
861
+ const lambda = fPoolLeverageOfCap(lnCapOverSeed);
871
862
  const rounded = Math.round(lambda * 100) / 100;
872
863
  const label = rounded <= 1 ? "≈1×" : `${String(rounded)}×`;
873
- return { lambda, capped: true, capOverFloor: Math.exp(lnCapOverFloor / 1e6), label };
864
+ return { lambda, capped: true, capOverSeed: Math.exp(lnCapOverSeed / 1e6), label };
874
865
  }
875
- /** The key's `lnCapOverFloor` from creation args: as given, else from `leverage`, else 0 (uncapped, cap ∞). Both given and disagreeing is refused. */
866
+ /** The `lnCapOverSeed` from deployment args: as given, else from `leverage`, else 0 (uncapped, cap ∞). Both given and disagreeing is refused. */
876
867
  export function fPoolCapOfArgs(a) {
877
868
  const fromLeverage = a.leverage === undefined ? undefined : fPoolCapOfLeverage(a.leverage);
878
- if (a.lnCapOverFloor !== undefined && fromLeverage !== undefined && a.lnCapOverFloor !== fromLeverage)
879
- throw new Error(`logswap: lnCapOverFloor ${a.lnCapOverFloor} and leverage ${a.leverage} (${fromLeverage}) disagree — pass one`);
880
- return a.lnCapOverFloor ?? fromLeverage ?? 0;
869
+ if (a.lnCapOverSeed !== undefined && fromLeverage !== undefined && a.lnCapOverSeed !== fromLeverage)
870
+ throw new Error(`logswap: lnCapOverSeed ${a.lnCapOverSeed} and leverage ${a.leverage} (${fromLeverage}) disagree — pass one`);
871
+ return a.lnCapOverSeed ?? fromLeverage ?? 0;
881
872
  }
882
873
  /**
883
- * Arm the pool: deposit `r0[j]` of each base plus `Q0` of quote against exposure `L0`. Pass either
884
- * the reserves outright (`r0`) or the marks the pool should open at (`x0`, converted here with
885
- * {@link fPoolReserveAt} against the key's weights). Authority-only on-chain (an open seed lets
886
- * anyone front-run the creator for the strike). Arrays align with the SORTED bases — use
887
- * {@link sortFPoolLegs} on (bases, weights, x0) together when building forms.
874
+ * The `baseAssets` (and cap) a deployment sends for a wanted book — what the old seed did with reserves and
875
+ * marks, as the amounts and prices the manager takes now. Per asset: the reserve `r_j` (given as `r0`, or
876
+ * {@link fPoolReserveAt} the wanted mark `x0`) and the price that makes its value `L_j · (1 − k)`:
877
+ * `priceX36 = ceil(L_j(1 − k) · 1e36 / r_j)`. A zero weight is an asset left out. Sorted by base address, the
878
+ * key's order, with the companions carried along.
888
879
  */
889
- export async function fPoolSeed(c, a) {
890
- let r0;
891
- if ("r0" in a)
892
- r0 = a.r0;
893
- else {
894
- const k = fPoolCapK(Number((await rawFPool(c, a.poolId)).lnCapOverFloor), a.Q0, a.L0);
895
- r0 = a.x0.map((x, j) => fPoolReserveAt((a.weights[j] * a.L0) / 10n ** 18n, x, k));
896
- }
897
- return writeFPool(c, a.poolId, "seed", [a.L0, r0, a.Q0], a.account);
880
+ export function fPoolBook(a) {
881
+ const sum = a.weights.reduce((x, y) => x + y, 0n);
882
+ if (sum !== WAD)
883
+ throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
884
+ if (a.weights.length !== a.bases.length)
885
+ throw new Error(`logswap: ${a.weights.length} weights for ${a.bases.length} assets`);
886
+ const lnCapOverSeed = fPoolCapOfArgs(a);
887
+ const k = fPoolCapK(lnCapOverSeed);
888
+ const oneMinusK = BigInt(Math.round((1 - k) * 1e18));
889
+ const rows = a.bases.map((base, j) => {
890
+ const w = a.weights[j];
891
+ if (w === 0n)
892
+ return { base, amount: 0n, priceX36: 0n };
893
+ const Lj = (w * a.L0) / WAD;
894
+ const amount = "r0" in a ? a.r0[j] : fPoolReserveAt(Lj, a.x0[j], k);
895
+ if (amount === 0n)
896
+ throw new Error(`logswap: asset ${base} has weight ${w} but a zero reserve`);
897
+ const value = (Lj * oneMinusK) / WAD;
898
+ return { base, amount, priceX36: (value * 10n ** 36n + amount - 1n) / amount };
899
+ });
900
+ const { companions } = sortFPoolLegs(a.bases, rows);
901
+ return { baseAssets: companions[0], lnCapOverSeed };
898
902
  }
899
903
  /**
900
- * Retire the live generation — the raw entry (`dissolve` before F
901
- * version 14). Allowed only at an empty bid, Q ≤ L/1e9, on every pool: the market took it, or the
902
- * operator harvested it out first ({@link fPoolRetire} does both in one transaction). The live
903
- * (S, Q, R_j) become a frozen bundle every share of this generation redeems ({@link fPoolRedeem})
904
- * or rolls ({@link fPoolRollIn}), forever; the pool is unseeded until the next {@link fPoolSeed},
905
- * which opens generation `gen + 1` under the same id, policy, roles, gates and lists.
904
+ * The allocation a `deployLiquidity` book implies: asset `j`'s value `amount_j · priceX36_j / 1e36` over the sum,
905
+ * normalized as the manager does it (cumulative shares, floored), so the weights sum to exactly 1e18. A zero-value
906
+ * book has no allocation (`[]`). What an indexer derives from `LiquidityDeployed` instead of reading the weights.
906
907
  */
907
- export async function fPoolRetireRaw(c, a) {
908
- return writeFPool(c, a.poolId, "retire", [], a.account);
908
+ export function fPoolBookWeights(baseAssets) {
909
+ const values = baseAssets.map((x) => (x.amount * x.priceX36) / 10n ** 36n);
910
+ const total = values.reduce((x, y) => x + y, 0n);
911
+ if (total === 0n)
912
+ return [];
913
+ let cumulative = 0n;
914
+ let previous = 0n;
915
+ return values.map((v) => {
916
+ cumulative += v;
917
+ const next = (cumulative * WAD) / total;
918
+ const w = next - previous;
919
+ previous = next;
920
+ return w;
921
+ });
909
922
  }
910
923
  /**
911
- * Retire the live generation as ONE transaction: the harvest that empties the bid
924
+ * The book's total liquidity `L` from a `LiquidityDeployed` input: the values' sum over `1 − k`, `k = e^{−cap}`.
925
+ * Exact when uncapped; with a cap it carries the float error of `k` (~1e-16 relative) — read the pool for the wei.
926
+ */
927
+ export function fPoolBookL(baseAssets, lnCapOverSeed) {
928
+ const total = baseAssets.reduce((x, a) => x + (a.amount * a.priceX36) / 10n ** 36n, 0n);
929
+ if (lnCapOverSeed === 0)
930
+ return total;
931
+ const oneMinusK = BigInt(Math.round((1 - fPoolCapK(lnCapOverSeed)) * 1e18));
932
+ return (total * WAD) / oneMinusK;
933
+ }
934
+ /**
935
+ * Put liquidity into the pool, the authority's: `deployLiquidity` (F 38, decisions 083, 084). It SETS THE BOOK:
936
+ * `baseAssets[j].amount` is the total base reserve of asset `j` after the call (0 removes it), `quoteAmount` the
937
+ * total bid, and the manager settles each figure against what the pool holds — a larger total is pulled from the
938
+ * caller, a smaller one pushed to `to` — so one call can replace an asset by another. Pass the book outright
939
+ * (`baseAssets`, `lnCapOverSeed`) or the sponsor's terms ({@link fPoolBook}: `weights`, `L0` and marks `x0` or
940
+ * reserves `r0`, in any order). On an UNFUNDED pool (new, or after {@link fPoolClose}) it funds the first or the next
941
+ * generation. On a LIVE pool it is a regeneration that sets the book: income settles to `to`, the policy picks the
942
+ * carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
943
+ * carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
944
+ */
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
+ /**
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.
955
+ */
956
+ export async function fPoolCloseRaw(c, a) {
957
+ return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
958
+ }
959
+ /**
960
+ * Close the pool as ONE transaction: the harvest that empties the bid
912
961
  * ({@link fPoolEmptyingHarvests} — a dividend to every share; none when it is already empty),
913
- * then `retire` — the manager's `multicall`, the operator as sender. What a sponsor's
914
- * "retire" button should call. Throws before sending on a pad: a pad never retires (F version 21).
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.
915
964
  */
916
- export async function fPoolRetire(c, a) {
965
+ export async function fPoolClose(c, a) {
917
966
  const harvests = await fPoolEmptyingHarvests(c, a.poolId);
918
967
  if (harvests.length === 0)
919
- return fPoolRetireRaw(c, a);
968
+ return fPoolCloseRaw(c, a);
920
969
  const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
921
- const calls = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("retire", [a.poolId])];
970
+ const calls = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("close", [a.poolId, a.to ?? a.account])];
922
971
  return writeFPool0(c, "multicall", [calls], a.account);
923
972
  }
924
973
  /**
925
- * The harvests that empty an unlocked pool's bid, in order — what a relaunch sends before its
926
- * `retire` (a retire needs an empty bid on every pool). Since F version 14 one
927
- * `harvest(Q)` does it: the protocol's cut leaves the pool with the amount (with no treasury
928
- * there is no cut). `[]` when the bid is already empty. Throws on a pad (F version 21: a pad
929
- * never retires, whatever its bid), and when the pool's policy keeps a floor on the bid
930
- * (`PolPolicy.keepQuote`): a `retire` under that policy waits for the market.
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.
931
979
  */
932
980
  export async function fPoolEmptyingHarvests(c, poolId) {
933
981
  const s = await getFPool(c, poolId);
934
- // F version 21: `PadPolicy` refuses `retire` at any bid — a pad graduates (regenerate), it
935
- // never closes; a fresh start is a new pad with a new id
982
+ // `PadPolicy` refuses `close` at any bid — a pad graduates (regenerate), it never closes; a fresh start is a new pad
936
983
  if (s.kind === "pad")
937
- throw new Error("logswap: a pad never retires (F version 21) — it graduates by regenerate; a fresh start is a new pad");
984
+ throw new Error("logswap: a pad never closes — it graduates by regenerate; a fresh start is a new pad");
938
985
  if (s.Q === 0n)
939
986
  return [];
940
987
  const { maxHarvest } = await getFPoolRoles(c, poolId, s);
@@ -943,56 +990,27 @@ export async function fPoolEmptyingHarvests(c, poolId) {
943
990
  return [s.Q];
944
991
  }
945
992
  /**
946
- * The GENERATION STEP (F version 21) — on a pad, its graduation. The manager harvests the
947
- * generation's income first, releases the dead shares' pot, and asks the policy
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
948
995
  * (`onRegenerate`), whose {@link FPolicyTerms} name a `carried` holder. Then, for live
949
996
  * generation `g`:
950
997
  *
951
998
  * - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
952
999
  * as the pool;
953
- * - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`Retired(g, …)`)
1000
+ * - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`GenerationRetired`)
954
1001
  * and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
955
1002
  * dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
956
1003
  * lists them;
957
- * - the pot, all in quote (decisions 057): `toPayee` to the payee, `protocolCut` to the treasury,
958
- * `burn` spent buying base at the curve and burning it (the price up, the floor held), and the
959
- * rest into the bid (the floor down). No share is minted; L does not move.
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.
960
1006
  *
961
1007
  * A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and private carry the
962
- * authority and send it the whole pot; a public pool refuses (`Refused`). A carried holder with no
963
- * share is `BadTerms`. Whoever runs the pool.
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}.
964
1010
  */
965
1011
  export async function fPoolRegenerate(c, a) {
966
1012
  return writeFPool(c, a.poolId, "regenerate", [a.to ?? a.account], a.account);
967
1013
  }
968
- /**
969
- * The relaunch as ONE transaction: `harvest` the bid out — a
970
- * dividend to every share, {@link fPoolEmptyingHarvests} — `retire` the live generation at the
971
- * empty bid, `redeem` the caller's own shares of it (when `shares` > 0), optionally `setLegs` the
972
- * next generation's composition (`legs`: a private pool's reshape — retire, admit, reweight), and
973
- * `seed` it with what came back — the manager's `multicall`, one sender throughout, the same
974
- * pool. The operator's when one is appointed and the seed's inventory is its own; by default the
975
- * authority's. The policy, its roles, gates, allowlist and the name carry over; anything else goes
976
- * in `extra`, pre-encoded against {@link fPoolManagerAbi}. The seed names reserves (decisions
977
- * 029): `r0` outright — one per leg of the NEXT table, 0 for a retired leg — or `x0` marks
978
- * against the next table's `weights`.
979
- */
980
- export async function fPoolRelaunch(c, a) {
981
- const [raw, harvests] = await Promise.all([rawFPool(c, a.poolId), fPoolEmptyingHarvests(c, a.poolId)]);
982
- const gen = Number(raw.gen);
983
- const k = "r0" in a ? 0 : fPoolCapK(Number(raw.lnCapOverFloor), a.Q0, a.L0);
984
- const r0 = "r0" in a ? a.r0 : a.x0.map((x, j) => (a.weights[j] === 0n ? 0n : fPoolReserveAt((a.weights[j] * a.L0) / WAD, x, k)));
985
- const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
986
- const calls = [
987
- ...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])),
988
- enc("retire", [a.poolId]),
989
- ...(a.shares > 0n ? [enc("redeem", [a.poolId, BigInt(gen), a.account, a.shares])] : []),
990
- ...(a.legs ? [enc("setLegs", [a.poolId, a.legs.weights, a.legs.newBases ?? []])] : []),
991
- enc("seed", [a.poolId, a.L0, r0, a.Q0]),
992
- ...(a.extra ?? []),
993
- ];
994
- return writeFPool0(c, "multicall", [calls], a.account);
995
- }
996
1014
  /** Where a pad's seed lives: `seed` mints every share of a pad here itself. */
997
1015
  export const DEAD_ADDRESS = "0x000000000000000000000000000000000000dEaD";
998
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. */
@@ -1004,24 +1022,26 @@ export const F_MIN_SHARES = 1000n;
1004
1022
  * checked here, where the message is readable.
1005
1023
  */
1006
1024
  export function fPoolLaunchCalls(poolId, a) {
1007
- const sum = a.weights.reduce((x, y) => x + y, 0n);
1008
- if (sum !== WAD)
1009
- throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
1010
- const k = "r0" in a ? 0 : fPoolCapK(fPoolCapOfArgs(a), a.Q0, a.L0);
1011
- const given = "r0" in a ? a.r0 : a.x0.map((x, j) => fPoolReserveAt((a.weights[j] * a.L0) / WAD, x, k));
1012
- if (given.length !== a.bases.length)
1013
- throw new Error(`logswap: ${given.length} reserves for ${a.bases.length} legs`);
1014
- const { bases, companions } = sortFPoolLegs(a.bases, a.weights, given);
1015
1025
  if (!a.policy)
1016
1026
  throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
1017
- const key = { quote: a.quote, bases, weights: companions[0], swapFee: a.swapFee, policy: a.policy, creator: a.creator, salt: a.salt ?? ZERO_SALT, lnCapOverFloor: fPoolCapOfArgs(a) };
1027
+ const { baseAssets, lnCapOverSeed } = fPoolBook(a);
1028
+ 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
+ };
1018
1038
  const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
1019
1039
  const calls = [];
1020
1040
  if (!a.initialized)
1021
- calls.push(enc("initialize", [key, a.mintFee ?? presetMintFee(a.swapFee)]));
1022
- calls.push(enc("seed", [poolId, a.L0, companions[1], a.Q0]));
1023
- // gen 0 by construction: a launch is the pool's FIRST seed — a relaunch is `fPoolRelaunch`.
1024
- // No transfer to 0xdead: on a pad `seed` mints every share there itself.
1041
+ 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.
1044
+ // No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
1025
1045
  for (const row of fPoolGenesisRows(a)) {
1026
1046
  const j = bases.indexOf(a.bases[row.j]);
1027
1047
  if (j < 0)
@@ -1057,7 +1077,7 @@ export async function fPoolGenesisOutputs(c, poolId, a) {
1057
1077
  account: signerFor(c, a.account),
1058
1078
  });
1059
1079
  const results = result;
1060
- const first = (a.initialized ? 0 : 1) + 1; // [initialize] · seed · rows
1080
+ const first = (a.initialized ? 0 : 1) + 1; // [initialize] · deployLiquidity · rows
1061
1081
  return rows.map((_, i) => decodeAbiParameters([{ type: "uint256" }], results[first + i])[0]);
1062
1082
  }
1063
1083
  /**
@@ -1116,7 +1136,7 @@ export async function fPoolWalletBatchesAtomically(c, account) {
1116
1136
  export async function fPoolDeskOpening(c, a) {
1117
1137
  const policy = a.policy ?? fPoolPolicyFor(c, "private");
1118
1138
  return [
1119
- await fPoolSetGates(c, { poolId: a.poolId, gateMint: true, gateSwap: false, account: a.account, policy }),
1139
+ await fPoolSetMintGate(c, { poolId: a.poolId, gated: true, account: a.account, policy }),
1120
1140
  await fPoolSetMinters(c, { poolId: a.poolId, who: [a.account], allowed: true, account: a.account, policy }),
1121
1141
  ];
1122
1142
  }
@@ -1211,9 +1231,17 @@ export async function fPoolAcceptAuthority(c, a) {
1211
1231
  return writePolicy(c, fPolicyBaseAbi, a, "acceptAuthority", []);
1212
1232
  }
1213
1233
  // ─── the desk's controls (PrivatePolicy) ───────────────────────────────
1214
- /** Turn the mint / swap gates on or off (the authority, on the desk's policy). `burn` is never gated. */
1215
- export async function fPoolSetGates(c, a) {
1216
- return writePolicy(c, privatePolicyAbi, a, "setGates", [a.gateMint, a.gateSwap]);
1234
+ /**
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.
1238
+ */
1239
+ 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]);
1217
1245
  }
1218
1246
  /**
1219
1247
  * Add to or remove from the pool's MINTERS — who may mint, and swap (a zap in is both under one
@@ -1285,32 +1313,17 @@ async function registryAddress(c) {
1285
1313
  throw new Error("logswap: this deployment carries no policy registry");
1286
1314
  return registry;
1287
1315
  }
1288
- /** Who runs the pool: the appointed operator, or the authority until one is. */
1289
- export function fPoolOperatorOf(s) {
1290
- return s.operator === ZERO_ADDRESS ? s.authority : s.operator;
1316
+ /** Who may run the pool (decision 073): the authority always, and the optional delegate. */
1317
+ export function fPoolRunners(s) {
1318
+ return s.operator === ZERO_ADDRESS ? [s.authority] : [s.authority, s.operator];
1291
1319
  }
1292
1320
  /**
1293
- * Propose the operator (the authority, on the desk's policy) — the hot key that runs the pool:
1294
- * `harvest`, `retire`, `regenerate`, `setLegs`. Two-step: the proposed address takes the role with
1295
- * {@link fPoolAcceptOperator}. The zero address clears at once — the role returns to the authority.
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.
1296
1324
  */
1297
- export async function fPoolAppointOperator(c, a) {
1298
- return writePolicy(c, privatePolicyAbi, a, "appointOperator", [a.operator]);
1299
- }
1300
- /** The proposed operator takes the role. */
1301
- export async function fPoolAcceptOperator(c, a) {
1302
- return writePolicy(c, privatePolicyAbi, a, "acceptOperator", []);
1303
- }
1304
- /**
1305
- * The next generation's composition (operator; private pools only; ONLY while the pool is
1306
- * unseeded — between a retire and the seed that prices it). `weights` has one
1307
- * entry per leg the pool has ever had, in index order (0 retires a leg; indices are never reused),
1308
- * then one per base in `newBases`, appended; they sum to 1e18 exactly. No value moves: the
1309
- * following {@link fPoolSeed} names every reserve. A live reshape is {@link fPoolRelaunch} with
1310
- * `legs` set.
1311
- */
1312
- export async function fPoolSetLegs(c, a) {
1313
- return writeFPool(c, a.poolId, "setLegs", [a.weights, a.newBases ?? []], a.account);
1325
+ export async function fPoolSetPoolOperator(c, a) {
1326
+ return writePolicy(c, privatePolicyAbi, a, "setPoolOperator", [a.operator]);
1314
1327
  }
1315
1328
  /**
1316
1329
  * Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
@@ -1331,8 +1344,8 @@ export async function fPoolTransferShares(c, a) {
1331
1344
  }
1332
1345
  /**
1333
1346
  * Every F pool ever created, from `PoolCreated` logs alone — plus one `kind()` read per distinct
1334
- * policy, cached. Possible only because the event carries the full key preimage (bases,
1335
- * weights, swapFee, policy, lnCapOverFloor) — the poolId is a hash and could never be inverted; contracts PR #17
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
1336
1349
  * exists for exactly this call. With `indexer`, the logs come from it (the node when it fails):
1337
1350
  * a scan from block 0 per call is what made the first load wait on the node.
1338
1351
  */
@@ -1340,34 +1353,38 @@ export async function discoverFPools(c, opts = {}) {
1340
1353
  const ev = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
1341
1354
  if (!ev)
1342
1355
  throw new Error("logswap: F PoolCreated event missing from the generated ABI");
1343
- const seedEv = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "GenerationSeeded");
1356
+ const deployEv = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "LiquidityDeployed");
1344
1357
  const range = { indexer: opts.indexer, address: c.addresses.fPoolManager, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
1345
- const [{ logs }, { logs: seeds }] = await Promise.all([
1358
+ const [{ logs }, { logs: deploys }] = await Promise.all([
1346
1359
  getEventLogs(c, { ...range, event: ev }),
1347
- seedEv ? getEventLogs(c, { ...range, event: seedEv }) : Promise.resolve({ logs: [] }),
1360
+ deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
1348
1361
  ]);
1349
- const q0Of = new Map();
1350
- for (const l of seeds) {
1362
+ // the pool's first deployment (generation 0) names its allocation, cap and opening bid
1363
+ const first = new Map();
1364
+ for (const l of deploys) {
1351
1365
  const a = l.args;
1352
- q0Of.set(a.poolId.toLowerCase(), a.Q0);
1366
+ if (BigInt(a.gen) !== 0n)
1367
+ continue;
1368
+ first.set(a.poolId.toLowerCase(), { weights: fPoolBookWeights(a.baseAssets), lnCapOverSeed: Number(a.lnCapOverSeed), q0: a.quoteAmount });
1353
1369
  }
1354
1370
  return Promise.all(logs.map(async (l) => {
1355
1371
  const a = l.args;
1356
- const q0 = q0Of.get(a.poolId.toLowerCase());
1372
+ const g0 = first.get(a.poolId.toLowerCase());
1357
1373
  const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
1358
1374
  return {
1359
1375
  poolId: a.poolId,
1360
1376
  quote: a.quote,
1361
1377
  bases: [...a.bases],
1362
- weights: [...a.weights],
1378
+ weights: g0?.weights ?? [],
1363
1379
  swapFee: a.swapFee,
1364
- lnCapOverFloor: Number(a.lnCapOverFloor ?? a.cap ?? 0), // `cap` before F version 27
1380
+ mintFee: a.mintFee,
1381
+ lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
1365
1382
  kind,
1366
1383
  policy: a.policy,
1367
1384
  creator: a.creator,
1368
1385
  block: l.blockNumber,
1369
- seeded: q0 !== undefined,
1370
- q0: q0 ?? 0n,
1386
+ seeded: g0 !== undefined,
1387
+ q0: g0?.q0 ?? 0n,
1371
1388
  shape: kind === "pad" ? "launch" : "basket", // the policy's word, not n = 1: a mono POL is a pool
1372
1389
  };
1373
1390
  }));
@@ -1376,7 +1393,7 @@ const MAX_U64 = (1n << 64n) - 1n;
1376
1393
  const MAX_U128 = (1n << 128n) - 1n;
1377
1394
  /**
1378
1395
  * The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
1379
- * bits (a WAD fraction of the pot), zero in the next 64 — the burn share's place before F version 28, refused by the policy if
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
1380
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
1381
1398
  * chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
1382
1399
  */
@@ -1402,29 +1419,27 @@ export async function getFPoolRules(c, s, roles) {
1402
1419
  case "pad": {
1403
1420
  // the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
1404
1421
  const gen = s.gen;
1405
- const [split, pot, threshold, protocolNow, creatorShareMin, creatorShareMax] = await Promise.all([
1406
- rd(padPolicyAbi, "splitOf", [s.poolId]),
1422
+ const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
1423
+ rd(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
1407
1424
  fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
1408
1425
  rd(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
1409
- rd(padPolicyAbi, "protocolShare"),
1426
+ rd(padPolicyAbi, "incomeTaxRate"),
1410
1427
  rd(padPolicyAbi, "creatorShareMin"),
1411
1428
  rd(padPolicyAbi, "creatorShareMax"),
1412
1429
  ]);
1413
- const [creatorShare, protocolShare] = split;
1414
- const ranges = { protocolShare: protocolNow, creatorShareMin, creatorShareMax };
1415
- return { kind: "pad", gen, rung: gen, threshold, pot, creatorShare, protocolShare, ranges };
1430
+ const ranges = { creatorShareMin, creatorShareMax };
1431
+ return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
1416
1432
  }
1417
1433
  case "pol": {
1418
- const [keepQuote, minQuoteAtSeed] = await Promise.all([rd(polPolicyAbi, "keepQuote"), rd(polPolicyAbi, "minQuoteAtSeed")]);
1419
- return { kind: "pol", keepQuote, minQuoteAtSeed };
1434
+ const [minQuoteRatio, incomeTaxRate] = await Promise.all([rd(polPolicyAbi, "minQuoteRatio"), rd(polPolicyAbi, "incomeTaxRate")]);
1435
+ return { kind: "pol", minQuoteRatio, incomeTaxRate };
1420
1436
  }
1421
1437
  case "public": {
1422
- const curated = await rd(publicPolicyAbi, "curated");
1423
- return { kind: "public", curated };
1438
+ return { kind: "public" };
1424
1439
  }
1425
1440
  case "private": {
1426
1441
  const r = roles ?? (await getFPoolRoles(c, s.poolId, s));
1427
- return { kind: "private", gateMint: r.gateMint, gateSwap: r.gateSwap, operator: fPoolOperatorOf(r) };
1442
+ return { kind: "private", gateMint: r.gateMint, swapMode: r.swapMode, swapExecutor: r.swapExecutor, operator: r.operator };
1428
1443
  }
1429
1444
  }
1430
1445
  }
@@ -1489,7 +1504,7 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
1489
1504
  .map(([holder, shares]) => ({ holder: holder, shares }))
1490
1505
  .sort((a, b) => (b.shares > a.shares ? 1 : -1));
1491
1506
  }
1492
- /** Every F pool's raw state in one lens call (the manager's `Pool` struct: quote, swapFee, policy, seeded, gen, n, restructureTime, asks, lnCapOverFloor, Q, bigSigma, L, shares, refLogFloor). */
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). */
1493
1508
  export async function getFPoolsRaw(c, poolIds) {
1494
1509
  const { logswapLensAbi } = await import("./generated.js");
1495
1510
  return (await c.public.readContract({ address: c.addresses.lens, abi: logswapLensAbi, functionName: "getFPools", args: [poolIds] }));