@logswap/sdk 0.5.76 → 0.5.77

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
@@ -45,6 +45,7 @@ export { fPoolManagerAbi, padPolicyAbi, polPolicyAbi, privatePolicyAbi, publicPo
45
45
  * in for the base — a call through it to any of the four policies decodes the base's functions.
46
46
  */
47
47
  export const fPolicyBaseAbi = polPolicyAbi;
48
+ import { clientChainId } from "./client.js";
48
49
  import { fallBackUnlessRejected, signerFor } from "./write.js";
49
50
  import { getEventLogs } from "./history.js";
50
51
  import { poolHolders } from "./views.js";
@@ -100,12 +101,12 @@ export async function getFPool(c, poolId) {
100
101
  logFloor: v.logFloor,
101
102
  compositeX: v.compositeX,
102
103
  unharvested: v.unharvested,
103
- cap: Number(p.cap),
104
+ lnCapOverFloor: Number(p.lnCapOverFloor),
104
105
  bigSigma: p.bigSigma,
105
106
  policy: p.policy,
106
107
  asks: Number(p.asks),
107
108
  name,
108
- restructureBlock: Number(p.restructureBlock),
109
+ restructureTime: Number(p.restructureTime),
109
110
  kind,
110
111
  seeded: p.seeded,
111
112
  gen: Number(p.gen),
@@ -124,8 +125,9 @@ const kindCache = new Map();
124
125
  * chain: a pool's kind is its policy's word, never the manager's. An unknown tag
125
126
  * (a policy that is not one of the protocol's four shapes) throws; the app has no screen for it.
126
127
  */
127
- export function fPoolKindOfPolicy(c, policy) {
128
- const key = `${c.public.chain?.id ?? 0}:${policy.toLowerCase()}`;
128
+ export async function fPoolKindOfPolicy(c, policy) {
129
+ // the chain id is part of the key: the policies sit at one address on every release chain
130
+ const key = `${await clientChainId(c)}:${policy.toLowerCase()}`;
129
131
  let hit = kindCache.get(key);
130
132
  if (!hit) {
131
133
  hit = c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "kind" }).then((word) => {
@@ -206,7 +208,7 @@ export function fPoolShareValue(s) {
206
208
  if (s.totalSupply === 0n)
207
209
  return 0n;
208
210
  let v = s.L + s.Q;
209
- if (s.cap !== 0) {
211
+ if (s.lnCapOverFloor !== 0) {
210
212
  v = s.Q;
211
213
  for (let j = 0; j < s.reserves.length; j++) {
212
214
  const rv = s.virtualReserves[j];
@@ -722,7 +724,7 @@ const F_POOL_KEY_ABI = [
722
724
  { name: "policy", type: "address" },
723
725
  { name: "creator", type: "address" },
724
726
  { name: "salt", type: "bytes32" },
725
- { name: "cap", type: "uint24" },
727
+ { name: "lnCapOverFloor", type: "uint24" },
726
728
  ],
727
729
  },
728
730
  ];
@@ -745,7 +747,7 @@ export function fPoolKeyOf(c, a) {
745
747
  policy: a.policy ?? fPoolPolicyFor(c, a.kind),
746
748
  creator: a.creator,
747
749
  salt: a.salt ?? ZERO_SALT,
748
- cap: a.cap ?? 0,
750
+ lnCapOverFloor: fPoolCapOfArgs(a),
749
751
  };
750
752
  }
751
753
  /** Create the pool (no funds move — `seed` arms it). Returns the tx hash; read the id with `fPoolIdOf`. */
@@ -780,7 +782,7 @@ export async function fPoolIdOf(c, a) {
780
782
  */
781
783
  export async function fPoolKeyOfPool(c, poolId, opts = {}) {
782
784
  const ev = fPoolManagerAbi.find((x) => x.type === "event" && x.name === "FInitialize");
783
- const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.fPoolManager, event: ev, args: { poolId }, fromBlock: opts.fromBlock ?? 0n });
785
+ const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.fPoolManager, event: ev, args: { poolId }, fromBlock: opts.fromBlock });
784
786
  const l = logs[0];
785
787
  if (!l)
786
788
  throw new Error(`logswap: no FInitialize for F pool ${poolId}`);
@@ -793,13 +795,13 @@ export async function fPoolKeyOfPool(c, poolId, opts = {}) {
793
795
  policy: a.policy,
794
796
  creator: a.creator,
795
797
  salt: opts.salt ?? ZERO_SALT,
796
- cap: Number(a.cap),
798
+ lnCapOverFloor: Number(a.lnCapOverFloor ?? a.cap ?? 0), // `cap` before F version 27
797
799
  };
798
800
  if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
799
801
  // a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
800
802
  try {
801
- const [creatorShare, burnShare] = (await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "splitOf", args: [poolId] }));
802
- const padKey = { ...key, salt: padSalt({ creatorShare, burnShare }) };
803
+ const [creatorShare] = (await c.public.readContract({ address: a.policy, abi: padPolicyAbi, functionName: "splitOf", args: [poolId] }));
804
+ const padKey = { ...key, salt: padSalt({ creatorShare }) };
803
805
  if (fPoolIdOfKey(padKey).toLowerCase() === poolId.toLowerCase())
804
806
  return padKey;
805
807
  }
@@ -830,26 +832,52 @@ export function fPoolReserveAt(Lj, x, k = 0) {
830
832
  * 0 on an uncapped pool. Throws when the seed would be priced at or above its cap (Q0/L0 ≥ d), which
831
833
  * the manager refuses.
832
834
  */
833
- export function fPoolCapK(cap, Q0, L0) {
834
- if (cap === 0)
835
+ export function fPoolCapK(lnCapOverFloor, Q0, L0) {
836
+ if (lnCapOverFloor === 0)
835
837
  return 0;
836
- const e = Number((Q0 * WAD) / L0) / 1e18 - cap / 1e6;
838
+ const e = Number((Q0 * WAD) / L0) / 1e18 - lnCapOverFloor / 1e6;
837
839
  if (e >= 0)
838
- throw new Error(`logswap: a seed with Q0/L0 = ${Number((Q0 * WAD) / L0) / 1e18} is at or above its cap d = ${cap / 1e6}`);
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}`);
839
841
  return Math.exp(e);
840
842
  }
841
- /** The cap d (1e-6 log units) for a leverage λ > 1 at the floor: d = ln(λ/(λ − 1)) (decisions 061). λ = 2 puts the cap at twice the floor. */
843
+ /**
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
847
+ * 1 (or so large) that d leaves a uint24 of 1e-6 units, is refused.
848
+ */
842
849
  export function fPoolCapOfLeverage(lambda) {
843
- if (!(lambda > 1))
844
- throw new Error("logswap: leverage must exceed 1 (1 is uncapped: cap 0)");
850
+ if (lambda === 1)
851
+ return 0;
852
+ if (!(lambda > 1) || !Number.isFinite(lambda))
853
+ throw new Error(`logswap: leverage must be 1 (uncapped) or a finite number above 1, got ${lambda}`);
845
854
  const d = Math.round(Math.log(lambda / (lambda - 1)) * 1e6);
846
855
  if (d < 1 || d > 0xffffff)
847
856
  throw new Error(`logswap: leverage ${lambda} needs a cap outside a uint24 of 1e-6 units`);
848
857
  return d;
849
858
  }
850
- /** The leverage at the floor λ = 1/(1 − e^{−d}) for a cap d in 1e-6 log units; Infinity is impossible, 1 is uncapped. */
851
- export function fPoolLeverageOfCap(cap) {
852
- return cap === 0 ? 1 : 1 / (1 - Math.exp(-cap / 1e6));
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));
862
+ }
863
+ /**
864
+ * The leverage tag of a pool from its key's `lnCapOverFloor` (decisions 061): `1×` means no cap — the only way a tag
865
+ * reads 1× — and a capped pool always reads above it, so the two can never be confused on screen.
866
+ */
867
+ export function fPoolLeverage(lnCapOverFloor) {
868
+ if (lnCapOverFloor === 0)
869
+ return { lambda: 1, capped: false, capOverFloor: Infinity, label: "1×" };
870
+ const lambda = fPoolLeverageOfCap(lnCapOverFloor);
871
+ const rounded = Math.round(lambda * 100) / 100;
872
+ const label = rounded <= 1 ? "≈1×" : `${String(rounded)}×`;
873
+ return { lambda, capped: true, capOverFloor: Math.exp(lnCapOverFloor / 1e6), label };
874
+ }
875
+ /** The key's `lnCapOverFloor` from creation args: as given, else from `leverage`, else 0 (uncapped, cap ∞). Both given and disagreeing is refused. */
876
+ export function fPoolCapOfArgs(a) {
877
+ 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;
853
881
  }
854
882
  /**
855
883
  * Arm the pool: deposit `r0[j]` of each base plus `Q0` of quote against exposure `L0`. Pass either
@@ -863,7 +891,7 @@ export async function fPoolSeed(c, a) {
863
891
  if ("r0" in a)
864
892
  r0 = a.r0;
865
893
  else {
866
- const k = fPoolCapK(Number((await rawFPool(c, a.poolId)).cap), a.Q0, a.L0);
894
+ const k = fPoolCapK(Number((await rawFPool(c, a.poolId)).lnCapOverFloor), a.Q0, a.L0);
867
895
  r0 = a.x0.map((x, j) => fPoolReserveAt((a.weights[j] * a.L0) / 10n ** 18n, x, k));
868
896
  }
869
897
  return writeFPool(c, a.poolId, "seed", [a.L0, r0, a.Q0], a.account);
@@ -896,7 +924,7 @@ export async function fPoolRetire(c, a) {
896
924
  /**
897
925
  * The harvests that empty an unlocked pool's bid, in order — what a relaunch sends before its
898
926
  * `retire` (a retire needs an empty bid on every pool). Since F version 14 one
899
- * `harvest(Q)` does it: the protocol's cut leaves the pool with the amount (with no collector
927
+ * `harvest(Q)` does it: the protocol's cut leaves the pool with the amount (with no treasury
900
928
  * there is no cut). `[]` when the bid is already empty. Throws on a pad (F version 21: a pad
901
929
  * never retires, whatever its bid), and when the pool's policy keeps a floor on the bid
902
930
  * (`PolPolicy.keepQuote`): a `retire` under that policy waits for the market.
@@ -926,11 +954,11 @@ export async function fPoolEmptyingHarvests(c, poolId) {
926
954
  * and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
927
955
  * dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
928
956
  * lists them;
929
- * - the pot, all in quote (decisions 057): `toPayee` to the payee, `protocolCut` to the collector,
957
+ * - the pot, all in quote (decisions 057): `toPayee` to the payee, `protocolCut` to the treasury,
930
958
  * `burn` spent buying base at the curve and burning it (the price up, the floor held), and the
931
959
  * rest into the bid (the floor down). No share is minted; L does not move.
932
960
  *
933
- * A pad's gate is `threshold(gen)` (`PadPolicy.NotGraduated` below it); POL and private carry the
961
+ * A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and private carry the
934
962
  * authority and send it the whole pot; a public pool refuses (`Refused`). A carried holder with no
935
963
  * share is `BadTerms`. Whoever runs the pool.
936
964
  */
@@ -952,7 +980,7 @@ export async function fPoolRegenerate(c, a) {
952
980
  export async function fPoolRelaunch(c, a) {
953
981
  const [raw, harvests] = await Promise.all([rawFPool(c, a.poolId), fPoolEmptyingHarvests(c, a.poolId)]);
954
982
  const gen = Number(raw.gen);
955
- const k = "r0" in a ? 0 : fPoolCapK(Number(raw.cap), a.Q0, a.L0);
983
+ const k = "r0" in a ? 0 : fPoolCapK(Number(raw.lnCapOverFloor), a.Q0, a.L0);
956
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)));
957
985
  const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
958
986
  const calls = [
@@ -979,14 +1007,14 @@ export function fPoolLaunchCalls(poolId, a) {
979
1007
  const sum = a.weights.reduce((x, y) => x + y, 0n);
980
1008
  if (sum !== WAD)
981
1009
  throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
982
- const k = "r0" in a ? 0 : fPoolCapK(a.cap ?? 0, a.Q0, a.L0);
1010
+ const k = "r0" in a ? 0 : fPoolCapK(fPoolCapOfArgs(a), a.Q0, a.L0);
983
1011
  const given = "r0" in a ? a.r0 : a.x0.map((x, j) => fPoolReserveAt((a.weights[j] * a.L0) / WAD, x, k));
984
1012
  if (given.length !== a.bases.length)
985
1013
  throw new Error(`logswap: ${given.length} reserves for ${a.bases.length} legs`);
986
1014
  const { bases, companions } = sortFPoolLegs(a.bases, a.weights, given);
987
1015
  if (!a.policy)
988
1016
  throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
989
- const key = { quote: a.quote, bases, weights: companions[0], swapFee: a.swapFee, policy: a.policy, creator: a.creator, salt: a.salt ?? ZERO_SALT, cap: a.cap ?? 0 };
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) };
990
1018
  const enc = (functionName, args) => encodeFunctionData({ abi: fPoolManagerAbi, functionName, args });
991
1019
  const calls = [];
992
1020
  if (!a.initialized)
@@ -1304,7 +1332,7 @@ export async function fPoolTransferShares(c, a) {
1304
1332
  /**
1305
1333
  * Every F pool ever created, from `Initialize` logs alone — plus one `kind()` read per distinct
1306
1334
  * policy, cached. Possible only because the event carries the full key preimage (bases,
1307
- * weights, swapFee, policy, cap) — the poolId is a hash and could never be inverted; contracts PR #17
1335
+ * weights, swapFee, policy, lnCapOverFloor) — the poolId is a hash and could never be inverted; contracts PR #17
1308
1336
  * exists for exactly this call. With `indexer`, the logs come from it (the node when it fails):
1309
1337
  * a scan from block 0 per call is what made the first load wait on the node.
1310
1338
  */
@@ -1333,7 +1361,7 @@ export async function discoverFPools(c, opts = {}) {
1333
1361
  bases: [...a.bases],
1334
1362
  weights: [...a.weights],
1335
1363
  swapFee: a.swapFee,
1336
- cap: Number(a.cap ?? 0),
1364
+ lnCapOverFloor: Number(a.lnCapOverFloor ?? a.cap ?? 0), // `cap` before F version 27
1337
1365
  kind,
1338
1366
  policy: a.policy,
1339
1367
  creator: a.creator,
@@ -1347,19 +1375,22 @@ export async function discoverFPools(c, opts = {}) {
1347
1375
  const MAX_U64 = (1n << 64n) - 1n;
1348
1376
  const MAX_U128 = (1n << 128n) - 1n;
1349
1377
  /**
1350
- * The salt that carries a pad's split (`PadPolicy.pack`, decisions 056, 057): `creatorShare` in the top 64 bits, `burnShare` in
1351
- * the next 64 (WAD fractions of the pot), a nonce in the low 128 that tells two otherwise identical pads apart. It is part of the pool's
1352
- * identity, so it is chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a split outside its ranges.
1378
+ * 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
1380
+ * 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
+ * chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
1353
1382
  */
1354
1383
  export function padSalt(s) {
1355
1384
  const nonce = s.nonce ?? 0n;
1356
- if (s.creatorShare < 0n || s.creatorShare > MAX_U64 || s.burnShare < 0n || s.burnShare > MAX_U64)
1357
- throw new Error("logswap: a pad's split is a WAD fraction that fits 64 bits");
1385
+ if (s.burnShare !== undefined && s.burnShare !== 0n)
1386
+ throw new Error("logswap: a pad has no burn share since F version 28 (decision 067)");
1387
+ if (s.creatorShare < 0n || s.creatorShare > MAX_U64)
1388
+ throw new Error("logswap: a pad's creator share is a WAD fraction that fits 64 bits");
1358
1389
  if (nonce < 0n || nonce > MAX_U128)
1359
1390
  throw new Error("logswap: a pad salt's nonce fits 128 bits");
1360
- return `0x${((s.creatorShare << 192n) | (s.burnShare << 128n) | nonce).toString(16).padStart(64, "0")}`;
1391
+ return `0x${((s.creatorShare << 192n) | nonce).toString(16).padStart(64, "0")}`;
1361
1392
  }
1362
- /** The inverse of {@link padSalt}. */
1393
+ /** The inverse of {@link padSalt}. `burnShare` is the old field's bits, nonzero only on a salt the F version 28 policy refuses. */
1363
1394
  export function padSplitOfSalt(salt) {
1364
1395
  const v = BigInt(salt);
1365
1396
  return { creatorShare: v >> 192n, burnShare: (v >> 128n) & MAX_U64, nonce: v & MAX_U128 };
@@ -1371,19 +1402,17 @@ export async function getFPoolRules(c, s, roles) {
1371
1402
  case "pad": {
1372
1403
  // the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
1373
1404
  const gen = s.gen;
1374
- const [split, pot, threshold, protocolNow, creatorShareMin, creatorShareMax, burnMin, burnMax] = await Promise.all([
1405
+ const [split, pot, threshold, protocolNow, creatorShareMin, creatorShareMax] = await Promise.all([
1375
1406
  rd(padPolicyAbi, "splitOf", [s.poolId]),
1376
1407
  fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
1377
- rd(padPolicyAbi, "threshold", [BigInt(gen)]),
1408
+ rd(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
1378
1409
  rd(padPolicyAbi, "protocolShare"),
1379
1410
  rd(padPolicyAbi, "creatorShareMin"),
1380
1411
  rd(padPolicyAbi, "creatorShareMax"),
1381
- rd(padPolicyAbi, "burnMin"),
1382
- rd(padPolicyAbi, "burnMax"),
1383
1412
  ]);
1384
- const [creatorShare, burnShare, protocolShare] = split;
1385
- const ranges = { protocolShare: protocolNow, creatorShareMin, creatorShareMax, burnMin, burnMax };
1386
- return { kind: "pad", gen, rung: gen, threshold, pot, creatorShare, protocolShare, burnShare, ranges };
1413
+ const [creatorShare, protocolShare] = split;
1414
+ const ranges = { protocolShare: protocolNow, creatorShareMin, creatorShareMax };
1415
+ return { kind: "pad", gen, rung: gen, threshold, pot, creatorShare, protocolShare, ranges };
1387
1416
  }
1388
1417
  case "pol": {
1389
1418
  const [keepQuote, minQuoteAtSeed] = await Promise.all([rd(polPolicyAbi, "keepQuote"), rd(polPolicyAbi, "minQuoteAtSeed")]);
@@ -1432,9 +1461,10 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
1432
1461
  if (!ev)
1433
1462
  throw new Error("logswap: 6909 Transfer event missing from the generated ABI");
1434
1463
  const gen = opts.gen ?? (await fPoolGen(c, poolIdHex));
1435
- if (opts.indexer) {
1464
+ const indexer = opts.indexer ?? c.indexerUrl;
1465
+ if (indexer) {
1436
1466
  try {
1437
- const rows = await poolHolders(opts.indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.fPoolManager.toLowerCase() } });
1467
+ const rows = await poolHolders(indexer, { condition: { side: "F", poolId: poolIdHex.toLowerCase(), gen: Number(gen), manager: c.addresses.fPoolManager.toLowerCase() } });
1438
1468
  return rows
1439
1469
  .filter((r) => r.balance > 0n)
1440
1470
  .map((r) => ({ holder: r.holder, shares: r.balance }))
@@ -1459,7 +1489,7 @@ export async function fPoolShareHolders(c, poolIdHex, opts = {}) {
1459
1489
  .map(([holder, shares]) => ({ holder: holder, shares }))
1460
1490
  .sort((a, b) => (b.shares > a.shares ? 1 : -1));
1461
1491
  }
1462
- /** Every F pool's raw state in one lens call (the manager's `Pool` struct: quote, swapFee, policy, seeded, gen, n, restructureBlock, asks, cap, Q, bigSigma, L, shares, refLogFloor). */
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). */
1463
1493
  export async function getFPoolsRaw(c, poolIds) {
1464
1494
  const { logswapLensAbi } = await import("./generated.js");
1465
1495
  return (await c.public.readContract({ address: c.addresses.lens, abi: logswapLensAbi, functionName: "getFPools", args: [poolIds] }));