@logswap/sdk 0.5.80 → 0.5.82

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,7 +102,7 @@ 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
+ lnCapOverSeed: Number(p.lnCapOverSeed),
105
106
  realizedVariance: p.realizedVariance,
106
107
  policy: p.policy,
107
108
  asks: Number(p.asks),
@@ -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"];
@@ -178,18 +179,18 @@ export async function getFPoolRoles(c, poolId, state) {
178
179
  return { policy: s.policy, creator, authority, pendingAuthority, operator, gateMint, swapMode: SWAP_MODES[Number(mode)] ?? "open", swapExecutor, maxHarvest };
179
180
  }
180
181
  export async function describeFPool(c, s) {
181
- // 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
182
183
  // manager's ceiling (`harvestable()` until F version 21, which cut the getter): Q once seeded.
183
184
  const harvestable = s.L > 0n ? s.Q : 0n;
184
185
  const unharvested = s.L > 0n ? s.unharvested : 0n;
185
- 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;
186
187
  return {
187
188
  shape: s.kind === "pad" ? "launch" : "basket", // the kind, not n = 1
188
189
  legs: s.bases.length,
189
190
  atFloor: s.Q === 0n,
190
191
  unharvested,
191
192
  harvestable,
192
- pot,
193
+ income,
193
194
  };
194
195
  }
195
196
  /** `p_j = e^{x_j}`, lossy the way any float conversion is. Compare in log space when it matters. */
@@ -205,7 +206,7 @@ export function fPoolShareValue(s) {
205
206
  if (s.totalSupply === 0n)
206
207
  return 0n;
207
208
  let v = s.L + s.Q;
208
- if (s.lnCapOverFloor !== 0) {
209
+ if (s.lnCapOverSeed !== 0) {
209
210
  v = s.Q;
210
211
  for (let j = 0; j < s.reserves.length; j++) {
211
212
  const rv = s.virtualReserves[j];
@@ -365,7 +366,7 @@ export async function fPoolPreviewRollIn(c, poolId, gen, holder, shares) {
365
366
  // ─── the floor lever (authority only) ─────────────────────────────────────────
366
367
  /**
367
368
  * Remove quote, lifting θ — price-neutral, no base moves, and a DIVIDEND to
368
- * 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
369
370
  * their next transfer, mint or burn, or pulled with {@link fPoolClaim}. The sponsor's own slice —
370
371
  * its shares' and the locked seed's at 0xdead — is pushed to `to` at once. On a pad
371
372
  * the lift stops at the seed floor θ₀ (income only); nothing else bounds it — an
@@ -716,12 +717,11 @@ const F_POOL_KEY_ABI = [
716
717
  components: [
717
718
  { name: "quote", type: "address" },
718
719
  { name: "bases", type: "address[]" },
719
- { name: "weights", type: "uint256[]" },
720
720
  { name: "swapFee", type: "uint256" },
721
721
  { name: "policy", type: "address" },
722
722
  { name: "creator", type: "address" },
723
723
  { name: "salt", type: "bytes32" },
724
- { name: "lnCapOverFloor", type: "uint24" },
724
+ { name: "mintFee", type: "uint256" },
725
725
  ],
726
726
  },
727
727
  ];
@@ -729,36 +729,36 @@ const F_POOL_KEY_ABI = [
729
729
  * An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
730
730
  * manager's `idOf(FPoolKey)` getter was cut in F version 21; this is the same hash (checked
731
731
  * against Foundry's encoder and the local deployment's pools in the tests). The key must be the
732
- * one the pool was initialized with: 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.
733
733
  */
734
734
  export function fPoolIdOfKey(key) {
735
735
  return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
736
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). */
737
738
  export function fPoolKeyOf(c, a) {
738
- const { bases, companions } = sortFPoolLegs(a.bases, a.weights);
739
+ const { bases } = sortFPoolLegs(a.bases);
739
740
  return {
740
741
  quote: a.quote,
741
742
  bases,
742
- weights: companions[0],
743
743
  swapFee: a.swapFee,
744
744
  policy: a.policy ?? fPoolPolicyFor(c, a.kind),
745
745
  creator: a.creator,
746
746
  salt: a.salt ?? ZERO_SALT,
747
- lnCapOverFloor: fPoolCapOfArgs(a),
747
+ mintFee: a.mintFee ?? presetMintFee(a.swapFee),
748
748
  };
749
749
  }
750
- /** 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`. */
751
751
  export async function fPoolInitialize(c, a) {
752
- const sum = a.weights.reduce((x, y) => x + y, 0n);
753
- if (sum !== 10n ** 18n)
754
- throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
755
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
+ }
756
756
  const wallet = requireWallet(c);
757
757
  const { request } = await c.public.simulateContract({
758
758
  address: c.addresses.fPoolManager,
759
759
  abi: fPoolManagerAbi,
760
760
  functionName: "initialize",
761
- args: [key, a.mintFee ?? presetMintFee(a.swapFee)],
761
+ args: [key],
762
762
  account: wallet.account,
763
763
  });
764
764
  return c.wallet.writeContract(request);
@@ -787,12 +787,11 @@ export async function fPoolKeyOfPool(c, poolId, opts = {}) {
787
787
  const key = {
788
788
  quote: a.quote,
789
789
  bases: [...a.bases],
790
- weights: [...a.weights],
791
790
  swapFee: a.swapFee,
792
791
  policy: a.policy,
793
792
  creator: a.creator,
794
793
  salt: opts.salt ?? ZERO_SALT,
795
- lnCapOverFloor: Number(a.lnCapOverFloor ?? a.cap ?? 0), // `cap` before F version 27
794
+ mintFee: a.mintFee,
796
795
  };
797
796
  if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
798
797
  // a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
@@ -812,35 +811,30 @@ export async function fPoolKeyOfPool(c, poolId, opts = {}) {
812
811
  return key;
813
812
  }
814
813
  /**
815
- * The reserve a leg holds at a mark: `R = Lj·e^{−x}`, WAD math. The seed names RESERVES —
816
- * the sponsor states holdings and the price follows, `p = Lj / R` — so this is
817
- * the one conversion from a price to what the pool will hold, done here, on the way in. Float
818
- * 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
819
818
  * the pool derives from it is the one the sponsor meant to within that.
820
819
  */
821
820
  export function fPoolReserveAt(Lj, x, k = 0) {
822
- // on a capped pool (decisions 061) the mark reads the virtual reserve R̃ = R + c, and the seed
823
- // 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)
824
823
  const e = Math.exp(-Number(x) / 1e18) * (1 - k);
825
824
  return (Lj * BigInt(Math.round(e * 1e18))) / 10n ** 18n;
826
825
  }
827
826
  /**
828
- * The seed's cap constant k = e^{Q0/L0 − d} (decisions 061): every leg's phantom is c_j = r_j·k/(1 − k).
829
- * 0 on an uncapped pool. Throws when the seed would be priced at or above its cap (Q0/L0 ≥ d), which
830
- * 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.
831
830
  */
832
- export function fPoolCapK(lnCapOverFloor, Q0, L0) {
833
- if (lnCapOverFloor === 0)
834
- return 0;
835
- const e = Number((Q0 * WAD) / L0) / 1e18 - lnCapOverFloor / 1e6;
836
- if (e >= 0)
837
- 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}`);
838
- return Math.exp(e);
831
+ export function fPoolCapK(lnCapOverSeed) {
832
+ return lnCapOverSeed === 0 ? 0 : Math.exp(-lnCapOverSeed / 1e6);
839
833
  }
840
834
  /**
841
- * The key's `lnCapOverFloor` = ln(cap/floor) (1e-6 log units) for a leverage λ at the floor: ln(λ/(λ − 1))
842
- * (decisions 061), so λ = 1/(1 − floor/cap) and the cap sits λ/(λ − 1) × the floor — λ = 2 puts it at twice.
843
- * **λ = 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
844
838
  * 1 (or so large) that d leaves a uint24 of 1e-6 units, is refused.
845
839
  */
846
840
  export function fPoolCapOfLeverage(lambda) {
@@ -853,85 +847,141 @@ export function fPoolCapOfLeverage(lambda) {
853
847
  throw new Error(`logswap: leverage ${lambda} needs a cap outside a uint24 of 1e-6 units`);
854
848
  return d;
855
849
  }
856
- /** The leverage at the floor λ = 1/(1 − e^{−x}) for x = `lnCapOverFloor` (1e-6 log units); 1 for an uncapped pool (cap ∞). */
857
- export function fPoolLeverageOfCap(lnCapOverFloor) {
858
- 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));
859
853
  }
860
854
  /**
861
- * 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
862
856
  * reads 1× — and a capped pool always reads above it, so the two can never be confused on screen.
863
857
  */
864
- export function fPoolLeverage(lnCapOverFloor) {
865
- if (lnCapOverFloor === 0)
866
- return { lambda: 1, capped: false, capOverFloor: Infinity, label: "1×" };
867
- 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);
868
862
  const rounded = Math.round(lambda * 100) / 100;
869
863
  const label = rounded <= 1 ? "≈1×" : `${String(rounded)}×`;
870
- return { lambda, capped: true, capOverFloor: Math.exp(lnCapOverFloor / 1e6), label };
864
+ return { lambda, capped: true, capOverSeed: Math.exp(lnCapOverSeed / 1e6), label };
871
865
  }
872
- /** 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. */
873
867
  export function fPoolCapOfArgs(a) {
874
868
  const fromLeverage = a.leverage === undefined ? undefined : fPoolCapOfLeverage(a.leverage);
875
- if (a.lnCapOverFloor !== undefined && fromLeverage !== undefined && a.lnCapOverFloor !== fromLeverage)
876
- throw new Error(`logswap: lnCapOverFloor ${a.lnCapOverFloor} and leverage ${a.leverage} (${fromLeverage}) disagree — pass one`);
877
- 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;
878
872
  }
879
873
  /**
880
- * Arm the pool: deposit `r0[j]` of each base plus `Q0` of quote against exposure `L0`. Pass either
881
- * the reserves outright (`r0`) or the marks the pool should open at (`x0`, converted here with
882
- * {@link fPoolReserveAt} against the key's weights). Authority-only on-chain (an open seed lets
883
- * anyone front-run the creator for the strike). Arrays align with the SORTED bases — use
884
- * {@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.
885
879
  */
886
- export async function fPoolSeed(c, a) {
887
- let r0;
888
- if ("r0" in a)
889
- r0 = a.r0;
890
- else {
891
- const k = fPoolCapK(Number((await rawFPool(c, a.poolId)).lnCapOverFloor), a.Q0, a.L0);
892
- r0 = a.x0.map((x, j) => fPoolReserveAt((a.weights[j] * a.L0) / 10n ** 18n, x, k));
893
- }
894
- 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 };
902
+ }
903
+ /**
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.
907
+ */
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
+ });
922
+ }
923
+ /**
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);
895
948
  }
896
949
  /**
897
- * Retire the live generation — the raw entry (`dissolve` before F
898
- * version 14). Allowed only at an empty bid, Q ≤ L/1e9, on every pool: the market took it, or the
899
- * operator harvested it out first ({@link fPoolRetire} does both in one transaction). The live
900
- * (S, Q, R_j) become a frozen bundle every share of this generation redeems ({@link fPoolRedeem})
901
- * or rolls ({@link fPoolRollIn}), forever; the pool is unseeded until the next {@link fPoolSeed},
902
- * which opens generation `gen + 1` under the same id, policy, roles, gates and lists.
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.
903
955
  */
904
- export async function fPoolRetireRaw(c, a) {
905
- return writeFPool(c, a.poolId, "retire", [], a.account);
956
+ export async function fPoolCloseRaw(c, a) {
957
+ return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
906
958
  }
907
959
  /**
908
- * Retire the live generation as ONE transaction: the harvest that empties the bid
960
+ * Close the pool as ONE transaction: the harvest that empties the bid
909
961
  * ({@link fPoolEmptyingHarvests} — a dividend to every share; none when it is already empty),
910
- * then `retire` — the manager's `multicall`, the operator as sender. What a sponsor's
911
- * "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.
912
964
  */
913
- export async function fPoolRetire(c, a) {
965
+ export async function fPoolClose(c, a) {
914
966
  const harvests = await fPoolEmptyingHarvests(c, a.poolId);
915
967
  if (harvests.length === 0)
916
- return fPoolRetireRaw(c, a);
968
+ return fPoolCloseRaw(c, a);
917
969
  const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
918
- 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])];
919
971
  return writeFPool0(c, "multicall", [calls], a.account);
920
972
  }
921
973
  /**
922
- * The harvests that empty an unlocked pool's bid, in order — what a relaunch sends before its
923
- * `retire` (a retire needs an empty bid on every pool). Since F version 14 one
924
- * `harvest(Q)` does it: the protocol's cut leaves the pool with the amount (with no treasury
925
- * there is no cut). `[]` when the bid is already empty. Throws on a pad (F version 21: a pad
926
- * never retires, whatever its bid), and when the pool's policy keeps a floor on the bid
927
- * (`PolPolicy.minQuoteRatio`): 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.
928
979
  */
929
980
  export async function fPoolEmptyingHarvests(c, poolId) {
930
981
  const s = await getFPool(c, poolId);
931
- // F version 21: `PadPolicy` refuses `retire` at any bid — a pad graduates (regenerate), it
932
- // 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
933
983
  if (s.kind === "pad")
934
- 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");
935
985
  if (s.Q === 0n)
936
986
  return [];
937
987
  const { maxHarvest } = await getFPoolRoles(c, poolId, s);
@@ -940,56 +990,27 @@ export async function fPoolEmptyingHarvests(c, poolId) {
940
990
  return [s.Q];
941
991
  }
942
992
  /**
943
- * The GENERATION STEP (F version 21) — on a pad, its graduation. The manager harvests the
944
- * 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
945
995
  * (`onRegenerate`), whose {@link FPolicyTerms} name a `carried` holder. Then, for live
946
996
  * generation `g`:
947
997
  *
948
998
  * - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
949
999
  * as the pool;
950
- * - 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`)
951
1001
  * and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
952
1002
  * dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
953
1003
  * lists them;
954
- * - the pot, all in quote (decisions 057): `toPayee` to the payee, `protocolCut` to the treasury,
955
- * `burn` spent buying base at the curve and burning it (the price up, the floor held), and the
956
- * 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.
957
1006
  *
958
1007
  * A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and private carry the
959
- * authority and send it the whole pot; a public pool refuses (`Refused`). A carried holder with no
960
- * 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}.
961
1010
  */
962
1011
  export async function fPoolRegenerate(c, a) {
963
1012
  return writeFPool(c, a.poolId, "regenerate", [a.to ?? a.account], a.account);
964
1013
  }
965
- /**
966
- * The relaunch as ONE transaction: `harvest` the bid out — a
967
- * dividend to every share, {@link fPoolEmptyingHarvests} — `retire` the live generation at the
968
- * empty bid, `redeem` the caller's own shares of it (when `shares` > 0), optionally `setLegs` the
969
- * next generation's composition (`legs`: a private pool's reshape — retire, admit, reweight), and
970
- * `seed` it with what came back — the manager's `multicall`, one sender throughout, the same
971
- * pool. The operator's when one is appointed and the seed's inventory is its own; by default the
972
- * authority's. The policy, its roles, gates, allowlist and the name carry over; anything else goes
973
- * in `extra`, pre-encoded against {@link fPoolManagerAbi}. The seed names reserves (decisions
974
- * 029): `r0` outright — one per leg of the NEXT table, 0 for a retired leg — or `x0` marks
975
- * against the next table's `weights`.
976
- */
977
- export async function fPoolRelaunch(c, a) {
978
- const [raw, harvests] = await Promise.all([rawFPool(c, a.poolId), fPoolEmptyingHarvests(c, a.poolId)]);
979
- const gen = Number(raw.gen);
980
- const k = "r0" in a ? 0 : fPoolCapK(Number(raw.lnCapOverFloor), a.Q0, a.L0);
981
- 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)));
982
- const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
983
- const calls = [
984
- ...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])),
985
- enc("retire", [a.poolId]),
986
- ...(a.shares > 0n ? [enc("redeem", [a.poolId, BigInt(gen), a.account, a.shares])] : []),
987
- ...(a.legs ? [enc("setLegs", [a.poolId, a.legs.weights, a.legs.newBases ?? []])] : []),
988
- enc("seed", [a.poolId, a.L0, r0, a.Q0]),
989
- ...(a.extra ?? []),
990
- ];
991
- return writeFPool0(c, "multicall", [calls], a.account);
992
- }
993
1014
  /** Where a pad's seed lives: `seed` mints every share of a pad here itself. */
994
1015
  export const DEAD_ADDRESS = "0x000000000000000000000000000000000000dEaD";
995
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. */
@@ -1001,24 +1022,26 @@ export const F_MIN_SHARES = 1000n;
1001
1022
  * checked here, where the message is readable.
1002
1023
  */
1003
1024
  export function fPoolLaunchCalls(poolId, a) {
1004
- const sum = a.weights.reduce((x, y) => x + y, 0n);
1005
- if (sum !== WAD)
1006
- throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
1007
- const k = "r0" in a ? 0 : fPoolCapK(fPoolCapOfArgs(a), a.Q0, a.L0);
1008
- const given = "r0" in a ? a.r0 : a.x0.map((x, j) => fPoolReserveAt((a.weights[j] * a.L0) / WAD, x, k));
1009
- if (given.length !== a.bases.length)
1010
- throw new Error(`logswap: ${given.length} reserves for ${a.bases.length} legs`);
1011
- const { bases, companions } = sortFPoolLegs(a.bases, a.weights, given);
1012
1025
  if (!a.policy)
1013
1026
  throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
1014
- 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
+ };
1015
1038
  const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
1016
1039
  const calls = [];
1017
1040
  if (!a.initialized)
1018
- calls.push(enc("initialize", [key, a.mintFee ?? presetMintFee(a.swapFee)]));
1019
- calls.push(enc("seed", [poolId, a.L0, companions[1], a.Q0]));
1020
- // gen 0 by construction: a launch is the pool's FIRST seed — a relaunch is `fPoolRelaunch`.
1021
- // 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.
1022
1045
  for (const row of fPoolGenesisRows(a)) {
1023
1046
  const j = bases.indexOf(a.bases[row.j]);
1024
1047
  if (j < 0)
@@ -1054,7 +1077,7 @@ export async function fPoolGenesisOutputs(c, poolId, a) {
1054
1077
  account: signerFor(c, a.account),
1055
1078
  });
1056
1079
  const results = result;
1057
- const first = (a.initialized ? 0 : 1) + 1; // [initialize] · seed · rows
1080
+ const first = (a.initialized ? 0 : 1) + 1; // [initialize] · deployLiquidity · rows
1058
1081
  return rows.map((_, i) => decodeAbiParameters([{ type: "uint256" }], results[first + i])[0]);
1059
1082
  }
1060
1083
  /**
@@ -1302,17 +1325,6 @@ export function fPoolRunners(s) {
1302
1325
  export async function fPoolSetPoolOperator(c, a) {
1303
1326
  return writePolicy(c, privatePolicyAbi, a, "setPoolOperator", [a.operator]);
1304
1327
  }
1305
- /**
1306
- * The next generation's composition (operator; private pools only; ONLY while the pool is
1307
- * unseeded — between a retire and the seed that prices it). `weights` has one
1308
- * entry per leg the pool has ever had, in index order (0 retires a leg; indices are never reused),
1309
- * then one per base in `newBases`, appended; they sum to 1e18 exactly. No value moves: the
1310
- * following {@link fPoolSeed} names every reserve. A live reshape is {@link fPoolRelaunch} with
1311
- * `legs` set.
1312
- */
1313
- export async function fPoolSetLegs(c, a) {
1314
- return writeFPool(c, a.poolId, "setLegs", [a.weights, a.newBases ?? []], a.account);
1315
- }
1316
1328
  /**
1317
1329
  * Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
1318
1330
  * Burning to the dead address is a sponsor's way to make its liquidity permanent: the shares can
@@ -1332,8 +1344,8 @@ export async function fPoolTransferShares(c, a) {
1332
1344
  }
1333
1345
  /**
1334
1346
  * Every F pool ever created, from `PoolCreated` logs alone — plus one `kind()` read per distinct
1335
- * policy, cached. Possible only because the event carries the full key preimage (bases,
1336
- * 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
1337
1349
  * exists for exactly this call. With `indexer`, the logs come from it (the node when it fails):
1338
1350
  * a scan from block 0 per call is what made the first load wait on the node.
1339
1351
  */
@@ -1341,34 +1353,38 @@ export async function discoverFPools(c, opts = {}) {
1341
1353
  const ev = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "PoolCreated");
1342
1354
  if (!ev)
1343
1355
  throw new Error("logswap: F PoolCreated event missing from the generated ABI");
1344
- const seedEv = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "GenerationSeeded");
1356
+ const deployEv = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "LiquidityDeployed");
1345
1357
  const range = { indexer: opts.indexer, address: c.addresses.fPoolManager, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
1346
- const [{ logs }, { logs: seeds }] = await Promise.all([
1358
+ const [{ logs }, { logs: deploys }] = await Promise.all([
1347
1359
  getEventLogs(c, { ...range, event: ev }),
1348
- seedEv ? getEventLogs(c, { ...range, event: seedEv }) : Promise.resolve({ logs: [] }),
1360
+ deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
1349
1361
  ]);
1350
- const q0Of = new Map();
1351
- 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) {
1352
1365
  const a = l.args;
1353
- 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 });
1354
1369
  }
1355
1370
  return Promise.all(logs.map(async (l) => {
1356
1371
  const a = l.args;
1357
- const q0 = q0Of.get(a.poolId.toLowerCase());
1372
+ const g0 = first.get(a.poolId.toLowerCase());
1358
1373
  const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
1359
1374
  return {
1360
1375
  poolId: a.poolId,
1361
1376
  quote: a.quote,
1362
1377
  bases: [...a.bases],
1363
- weights: [...a.weights],
1378
+ weights: g0?.weights ?? [],
1364
1379
  swapFee: a.swapFee,
1365
- lnCapOverFloor: Number(a.lnCapOverFloor ?? a.cap ?? 0), // `cap` before F version 27
1380
+ mintFee: a.mintFee,
1381
+ lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
1366
1382
  kind,
1367
1383
  policy: a.policy,
1368
1384
  creator: a.creator,
1369
1385
  block: l.blockNumber,
1370
- seeded: q0 !== undefined,
1371
- q0: q0 ?? 0n,
1386
+ seeded: g0 !== undefined,
1387
+ q0: g0?.q0 ?? 0n,
1372
1388
  shape: kind === "pad" ? "launch" : "basket", // the policy's word, not n = 1: a mono POL is a pool
1373
1389
  };
1374
1390
  }));
@@ -1377,7 +1393,7 @@ const MAX_U64 = (1n << 64n) - 1n;
1377
1393
  const MAX_U128 = (1n << 128n) - 1n;
1378
1394
  /**
1379
1395
  * The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
1380
- * 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
1381
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
1382
1398
  * chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
1383
1399
  */
@@ -1403,20 +1419,20 @@ export async function getFPoolRules(c, s, roles) {
1403
1419
  case "pad": {
1404
1420
  // the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
1405
1421
  const gen = s.gen;
1406
- const [creatorShare, pot, threshold, incomeFeeRate, creatorShareMin, creatorShareMax] = await Promise.all([
1422
+ const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
1407
1423
  rd(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
1408
1424
  fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
1409
1425
  rd(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
1410
- rd(padPolicyAbi, "incomeFeeRate"),
1426
+ rd(padPolicyAbi, "incomeTaxRate"),
1411
1427
  rd(padPolicyAbi, "creatorShareMin"),
1412
1428
  rd(padPolicyAbi, "creatorShareMax"),
1413
1429
  ]);
1414
1430
  const ranges = { creatorShareMin, creatorShareMax };
1415
- return { kind: "pad", gen, rung: gen, threshold, pot, creatorShare, incomeFeeRate, ranges };
1431
+ return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
1416
1432
  }
1417
1433
  case "pol": {
1418
- const [minQuoteRatio, incomeFeeRate] = await Promise.all([rd(polPolicyAbi, "minQuoteRatio"), rd(polPolicyAbi, "incomeFeeRate")]);
1419
- return { kind: "pol", minQuoteRatio, incomeFeeRate };
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
1438
  return { kind: "public" };
@@ -1488,7 +1504,7 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
1488
1504
  .map(([holder, shares]) => ({ holder: holder, shares }))
1489
1505
  .sort((a, b) => (b.shares > a.shares ? 1 : -1));
1490
1506
  }
1491
- /** 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, realizedVariance, 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). */
1492
1508
  export async function getFPoolsRaw(c, poolIds) {
1493
1509
  const { logswapLensAbi } = await import("./generated.js");
1494
1510
  return (await c.public.readContract({ address: c.addresses.lens, abi: logswapLensAbi, functionName: "getFPools", args: [poolIds] }));