@logswap/sdk 0.5.80 → 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/README.md +35 -14
- package/dist/admin.d.ts +18 -47
- package/dist/admin.js +13 -31
- package/dist/client.d.ts +2 -2
- package/dist/client.js +13 -2
- package/dist/fpool.d.ts +174 -270
- package/dist/fpool.js +191 -175
- package/dist/generated.d.ts +484 -734
- package/dist/generated.js +251 -476
- package/dist/indexer.d.ts +1 -1
- package/dist/indexer.js +3 -2
- package/dist/keys.d.ts +17 -1
- package/dist/keys.js +16 -0
- package/dist/liquidity.d.ts +0 -5
- package/dist/liquidity.js +1 -2
- package/dist/pools.d.ts +5 -8
- package/dist/pools.js +7 -7
- package/dist/positions.d.ts +4 -5
- package/dist/positions.js +6 -7
- package/dist/views.d.ts +6 -10
- package/dist/views.js +6 -6
- package/package.json +1 -1
- package/src/admin.ts +14 -36
- package/src/client.ts +13 -2
- package/src/fpool.ts +267 -245
- package/src/generated.ts +251 -476
- package/src/indexer.ts +4 -3
- package/src/keys.ts +26 -1
- package/src/liquidity.ts +1 -7
- package/src/pools.ts +9 -11
- package/src/positions.ts +6 -7
- package/src/views.ts +12 -16
package/src/fpool.ts
CHANGED
|
@@ -52,6 +52,7 @@ import { fallBackUnlessRejected, signerFor } from "./write.js";
|
|
|
52
52
|
import { getEventLogs } from "./history.js";
|
|
53
53
|
import { poolHolders } from "./views.js";
|
|
54
54
|
import { presetMintFee } from "./positions.js";
|
|
55
|
+
import { isValidMintFee, MINT_FEE_MAX } from "./keys.js";
|
|
55
56
|
|
|
56
57
|
const WAD = 10n ** 18n;
|
|
57
58
|
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" as const;
|
|
@@ -76,7 +77,7 @@ export interface FPoolState {
|
|
|
76
77
|
L: bigint;
|
|
77
78
|
/** The swap fee, WAD (`phi` before F version 25, decisions 059). 0 is no fee (F version 26, decisions 065), admitted only if the policy lists it. */
|
|
78
79
|
swapFee: bigint;
|
|
79
|
-
/** The pool's mint fee, WAD of newly-minted L:
|
|
80
|
+
/** The pool's mint fee, WAD of newly-minted L: the creator-selected key field, fixed for life (F 38, decision 078): `2 * swapFee <= mintFee <= MINT_FEE_MAX`. */
|
|
80
81
|
mintFee: bigint;
|
|
81
82
|
/** θ₀, the reference log floor: where the floor stood at the seed (re-based by a capital harvest and at each step); income is counted from it. `theta0` before F version 25. */
|
|
82
83
|
refLogFloor: bigint;
|
|
@@ -87,11 +88,11 @@ export interface FPoolState {
|
|
|
87
88
|
/** This generation's income still in the pool, quote: L·(θ₀ − θ). */
|
|
88
89
|
unharvested: bigint;
|
|
89
90
|
/**
|
|
90
|
-
* The
|
|
91
|
-
*
|
|
92
|
-
* {@link fPoolLeverageOfCap}.
|
|
91
|
+
* The pool's one cap as a log ratio (decisions 061, 075): ln(cap price / seed price) in 1e-6 log units, set by the
|
|
92
|
+
* generation's `deployLiquidity`; each asset's maximum price is its own seed price times it. 0 is uncapped (cap ∞).
|
|
93
|
+
* The liquidity per unit of base value is 1/(1 − e^{−value}): {@link fPoolLeverageOfCap}.
|
|
93
94
|
*/
|
|
94
|
-
|
|
95
|
+
lnCapOverSeed: number;
|
|
95
96
|
/** Σ = ∫ Σ_j w_j (dx_j)², accrued even though the fee is fixed — the kernel stays calculable. */
|
|
96
97
|
realizedVariance: bigint;
|
|
97
98
|
/**
|
|
@@ -108,12 +109,13 @@ export interface FPoolState {
|
|
|
108
109
|
restructureTime: number;
|
|
109
110
|
/** What the pool is — its POLICY's self-description; see {@link FPoolKind}. */
|
|
110
111
|
kind: FPoolKind;
|
|
111
|
-
/** False before the first
|
|
112
|
+
/** False before the first `deployLiquidity` — and between a `close` and the next one. */
|
|
112
113
|
seeded: boolean;
|
|
113
114
|
/**
|
|
114
|
-
* The live GENERATION. Every
|
|
115
|
-
* ({@link fPoolRedeem}) and opens the next;
|
|
116
|
-
* (the generation step, {@link fPoolRegenerate})
|
|
115
|
+
* The live GENERATION. Every `close` freezes one into a bundle its shares redeem
|
|
116
|
+
* ({@link fPoolRedeem}) and opens the next; so does every `regenerate`
|
|
117
|
+
* (the generation step, {@link fPoolRegenerate}) and every live-pool `deployLiquidity`
|
|
118
|
+
* ({@link fPoolDeploy}): the carried holder and the dead shares go on
|
|
117
119
|
* as `gen + 1`, every other holder of `gen` is frozen out into its bundle. The share id carries
|
|
118
120
|
* it ({@link fPoolShareId}), so generations `0 … gen-1` are claims ({@link fPoolClaimsOf}) and
|
|
119
121
|
* `gen` is the pool. On a pad, `gen` is the graduation count — the rung.
|
|
@@ -162,9 +164,9 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
|
|
|
162
164
|
return {
|
|
163
165
|
poolId,
|
|
164
166
|
quote: p.quote,
|
|
165
|
-
bases: v.
|
|
166
|
-
weights: v.
|
|
167
|
-
x: v.
|
|
167
|
+
bases: v.baseLegs.map((l) => l.base),
|
|
168
|
+
weights: v.baseLegs.map((l) => l.weight),
|
|
169
|
+
x: v.baseLegs.map((l) => l.x), // derived by the manager: x_j = ln(w_j·L / R̃_j)
|
|
168
170
|
Q: p.Q,
|
|
169
171
|
L: p.L,
|
|
170
172
|
swapFee: p.swapFee,
|
|
@@ -173,7 +175,7 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
|
|
|
173
175
|
logFloor: v.logFloor,
|
|
174
176
|
compositeX: v.compositeX,
|
|
175
177
|
unharvested: v.unharvested,
|
|
176
|
-
|
|
178
|
+
lnCapOverSeed: Number(p.lnCapOverSeed),
|
|
177
179
|
realizedVariance: p.realizedVariance,
|
|
178
180
|
policy: p.policy,
|
|
179
181
|
asks: Number(p.asks),
|
|
@@ -183,9 +185,9 @@ export async function getFPool(c: LogswapClient, poolId: Hex): Promise<FPoolStat
|
|
|
183
185
|
seeded: p.seeded,
|
|
184
186
|
gen: Number(p.gen),
|
|
185
187
|
totalSupply: p.shares,
|
|
186
|
-
reserves: v.
|
|
187
|
-
virtualReserves: v.
|
|
188
|
-
kappa: v.
|
|
188
|
+
reserves: v.baseLegs.map((l) => l.reserve), // the state
|
|
189
|
+
virtualReserves: v.baseLegs.map((l) => l.virtualReserve),
|
|
190
|
+
kappa: v.baseLegs.map((l) => l.kappa),
|
|
189
191
|
};
|
|
190
192
|
}
|
|
191
193
|
|
|
@@ -316,23 +318,23 @@ export interface FPoolDescription {
|
|
|
316
318
|
* {@link FPoolRoles.maxHarvest}.
|
|
317
319
|
*/
|
|
318
320
|
harvestable: bigint;
|
|
319
|
-
/** The dead shares' banked dividend — a pad's
|
|
320
|
-
|
|
321
|
+
/** The dead shares' banked dividend — a pad's income, the creator's until a rung is climbed (decision 085: formerly the pot). */
|
|
322
|
+
income: bigint;
|
|
321
323
|
}
|
|
322
324
|
|
|
323
325
|
export async function describeFPool(c: LogswapClient, s: FPoolState): Promise<FPoolDescription> {
|
|
324
|
-
// an
|
|
326
|
+
// an unfunded pool has no L: nothing earned, nothing to harvest, no income. The bid is the
|
|
325
327
|
// manager's ceiling (`harvestable()` until F version 21, which cut the getter): Q once seeded.
|
|
326
328
|
const harvestable = s.L > 0n ? s.Q : 0n;
|
|
327
329
|
const unharvested = s.L > 0n ? s.unharvested : 0n;
|
|
328
|
-
const
|
|
330
|
+
const income = s.L > 0n ? await fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, s.gen) : 0n;
|
|
329
331
|
return {
|
|
330
332
|
shape: s.kind === "pad" ? "launch": "basket", // the kind, not n = 1
|
|
331
333
|
legs: s.bases.length,
|
|
332
334
|
atFloor: s.Q === 0n,
|
|
333
335
|
unharvested,
|
|
334
336
|
harvestable,
|
|
335
|
-
|
|
337
|
+
income,
|
|
336
338
|
};
|
|
337
339
|
}
|
|
338
340
|
|
|
@@ -349,7 +351,7 @@ export function fPoolPriceOf(x: bigint, scale = 1): number {
|
|
|
349
351
|
export function fPoolShareValue(s: FPoolState): bigint {
|
|
350
352
|
if (s.totalSupply === 0n) return 0n;
|
|
351
353
|
let v = s.L + s.Q;
|
|
352
|
-
if (s.
|
|
354
|
+
if (s.lnCapOverSeed !== 0) {
|
|
353
355
|
v = s.Q;
|
|
354
356
|
for (let j = 0; j < s.reserves.length; j++) {
|
|
355
357
|
const rv = s.virtualReserves[j]!;
|
|
@@ -600,7 +602,7 @@ export async function fPoolPreviewRollIn(
|
|
|
600
602
|
|
|
601
603
|
/**
|
|
602
604
|
* Remove quote, lifting θ — price-neutral, no base moves, and a DIVIDEND to
|
|
603
|
-
* every share: the amount goes into the pool's
|
|
605
|
+
* every share: the amount goes into the pool's held income and each holder's slice is settled lazily on
|
|
604
606
|
* their next transfer, mint or burn, or pulled with {@link fPoolClaim}. The sponsor's own slice —
|
|
605
607
|
* its shares' and the locked seed's at 0xdead — is pushed to `to` at once. On a pad
|
|
606
608
|
* the lift stops at the seed floor θ₀ (income only); nothing else bounds it — an
|
|
@@ -1000,28 +1002,16 @@ function findQuoteResult(err: unknown): bigint | null {
|
|
|
1000
1002
|
|
|
1001
1003
|
export interface FPoolCreateArgs {
|
|
1002
1004
|
quote: Address;
|
|
1003
|
-
/**
|
|
1005
|
+
/** The pool's assets, in any order; sorted into the key's canonical order before the call. The set is fixed for the pool's life. */
|
|
1004
1006
|
bases: Address[];
|
|
1005
|
-
/** WAD
|
|
1006
|
-
weights: bigint[];
|
|
1007
|
-
/** The swap fee, WAD (`phi` before F version 25). The base-for-base fee is pinned at 2φ on-chain. A curated policy admits only its listed tiers (decisions 059). */
|
|
1007
|
+
/** The swap fee, WAD. The base-for-base fee is pinned at 2φ on-chain. A curated policy admits only its listed tiers (decisions 059). */
|
|
1008
1008
|
swapFee: bigint;
|
|
1009
1009
|
/**
|
|
1010
|
-
* The pool's mint fee, WAD of newly-minted L — the creator's pick
|
|
1011
|
-
*
|
|
1012
|
-
* {@link presetMintFee}: twice the swap fee
|
|
1010
|
+
* The pool's mint fee, WAD of newly-minted L — the creator's pick, a key field fixed for life (F 38, decision
|
|
1011
|
+
* 078): `2 * swapFee <= mintFee <= MINT_FEE_MAX`, checked by the manager (`BadParam`). Defaults to
|
|
1012
|
+
* {@link presetMintFee}: twice the swap fee.
|
|
1013
1013
|
*/
|
|
1014
1014
|
mintFee?: bigint;
|
|
1015
|
-
/**
|
|
1016
|
-
* The common cap as a log distance (decisions 061): ln(cap price / floor price) in 1e-6 log units,
|
|
1017
|
-
* the key's `lnCapOverFloor`; 0 or absent is uncapped (cap ∞). Pass `lnCapOverFloor` or `leverage`, not both.
|
|
1018
|
-
*/
|
|
1019
|
-
lnCapOverFloor?: number;
|
|
1020
|
-
/**
|
|
1021
|
-
* The leverage at the floor λ (decisions 061), converted to `lnCapOverFloor` by {@link fPoolCapOfLeverage}:
|
|
1022
|
-
* 1 is uncapped (cap ∞, `lnCapOverFloor` 0), 2 puts the cap at twice the floor price.
|
|
1023
|
-
*/
|
|
1024
|
-
leverage?: number;
|
|
1025
1015
|
/**
|
|
1026
1016
|
* Which of the protocol's four the pool is — see {@link FPoolKind}. NOT a key field (decisions
|
|
1027
1017
|
* 049: the manager knows no kind): it selects the deployment's policy of that kind when `policy`
|
|
@@ -1069,25 +1059,23 @@ export function sortFPoolLegs<T>(bases: Address[], ...companions: T[][]): { base
|
|
|
1069
1059
|
return { bases: idx.map((i) => bases[i]!), companions: companions.map((arr) => idx.map((i) => arr[i]!)) };
|
|
1070
1060
|
}
|
|
1071
1061
|
|
|
1072
|
-
/** The key as the manager hashes it: legs sorted, the kind's policy filled in when none is named; no kind in it (049). */
|
|
1073
1062
|
/**
|
|
1074
1063
|
* The tuple an F pool's id hashes — `src/types/FPoolKey.sol`, field order load-bearing (it is
|
|
1075
1064
|
* the ABI encoding order). Stored by the manager at `initialize` and never in calldata again,
|
|
1076
|
-
* except `PolicyRegistry.migrate
|
|
1065
|
+
* except `PolicyRegistry.migrate`, which is handed it to check against the id. Since F 38 it holds no weights and no
|
|
1066
|
+
* cap: those belong to a generation's `deployLiquidity` (decision 075), and the mint fee is part of identity (078).
|
|
1077
1067
|
*/
|
|
1078
1068
|
export interface FPoolKey {
|
|
1079
1069
|
quote: Address;
|
|
1080
|
-
/** Sorted ascending, unique. */
|
|
1070
|
+
/** Sorted ascending, unique; fixed for the pool's life. */
|
|
1081
1071
|
bases: Address[];
|
|
1082
|
-
/** WAD, aligned with `bases`, summing to 1e18. */
|
|
1083
|
-
weights: bigint[];
|
|
1084
1072
|
swapFee: bigint;
|
|
1085
1073
|
/** The policy AT BIRTH — not the live one after a move. */
|
|
1086
1074
|
policy: Address;
|
|
1087
1075
|
creator: Address;
|
|
1088
1076
|
salt: Hex;
|
|
1089
|
-
/** The
|
|
1090
|
-
|
|
1077
|
+
/** The creator-selected mint fee, WAD, fixed for life: `2 * swapFee <= mintFee <= MINT_FEE_MAX`. */
|
|
1078
|
+
mintFee: bigint;
|
|
1091
1079
|
}
|
|
1092
1080
|
|
|
1093
1081
|
const F_POOL_KEY_ABI = [
|
|
@@ -1096,12 +1084,11 @@ const F_POOL_KEY_ABI = [
|
|
|
1096
1084
|
components: [
|
|
1097
1085
|
{ name: "quote", type: "address" },
|
|
1098
1086
|
{ name: "bases", type: "address[]" },
|
|
1099
|
-
{ name: "weights", type: "uint256[]" },
|
|
1100
1087
|
{ name: "swapFee", type: "uint256" },
|
|
1101
1088
|
{ name: "policy", type: "address" },
|
|
1102
1089
|
{ name: "creator", type: "address" },
|
|
1103
1090
|
{ name: "salt", type: "bytes32" },
|
|
1104
|
-
{ name: "
|
|
1091
|
+
{ name: "mintFee", type: "uint256" },
|
|
1105
1092
|
],
|
|
1106
1093
|
},
|
|
1107
1094
|
] as const;
|
|
@@ -1110,37 +1097,38 @@ const F_POOL_KEY_ABI = [
|
|
|
1110
1097
|
* An F pool's id: `keccak256(abi.encode(key))`, offline — what `initialize` computes inline. The
|
|
1111
1098
|
* manager's `idOf(FPoolKey)` getter was cut in F version 21; this is the same hash (checked
|
|
1112
1099
|
* against Foundry's encoder and the local deployment's pools in the tests). The key must be the
|
|
1113
|
-
* one the pool was initialized with:
|
|
1100
|
+
* one the pool was initialized with: bases sorted ({@link fPoolKeyOf} sorts them), the birth policy.
|
|
1114
1101
|
*/
|
|
1115
1102
|
export function fPoolIdOfKey(key: FPoolKey): Hex {
|
|
1116
1103
|
return keccak256(encodeAbiParameters(F_POOL_KEY_ABI, [key]));
|
|
1117
1104
|
}
|
|
1118
1105
|
|
|
1106
|
+
/** 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). */
|
|
1119
1107
|
export function fPoolKeyOf(c: LogswapClient, a: Omit<FPoolCreateArgs, "account">): FPoolKey {
|
|
1120
|
-
const { bases
|
|
1108
|
+
const { bases } = sortFPoolLegs(a.bases);
|
|
1121
1109
|
return {
|
|
1122
1110
|
quote: a.quote,
|
|
1123
1111
|
bases,
|
|
1124
|
-
weights: companions[0]!,
|
|
1125
1112
|
swapFee: a.swapFee,
|
|
1126
1113
|
policy: a.policy ?? fPoolPolicyFor(c, a.kind),
|
|
1127
1114
|
creator: a.creator,
|
|
1128
1115
|
salt: a.salt ?? ZERO_SALT,
|
|
1129
|
-
|
|
1116
|
+
mintFee: a.mintFee ?? presetMintFee(a.swapFee),
|
|
1130
1117
|
};
|
|
1131
1118
|
}
|
|
1132
1119
|
|
|
1133
|
-
/** Create the pool (no funds move — `
|
|
1120
|
+
/** Create the pool (no funds move — `deployLiquidity` funds it). Returns the tx hash; read the id with `fPoolIdOf`. */
|
|
1134
1121
|
export async function fPoolInitialize(c: LogswapClient, a: FPoolCreateArgs) {
|
|
1135
|
-
const sum = a.weights.reduce((x, y) => x + y, 0n);
|
|
1136
|
-
if (sum !== 10n ** 18n) throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
|
|
1137
1122
|
const key = fPoolKeyOf(c, a);
|
|
1123
|
+
if (!isValidMintFee(key.swapFee, key.mintFee)) {
|
|
1124
|
+
throw new Error(`logswap: mint fee ${key.mintFee} is outside 2 × the swap fee (${2n * key.swapFee}) … ${MINT_FEE_MAX}`);
|
|
1125
|
+
}
|
|
1138
1126
|
const wallet = requireWallet(c);
|
|
1139
1127
|
const { request } = await c.public.simulateContract({
|
|
1140
1128
|
address: c.addresses.fPoolManager!,
|
|
1141
1129
|
abi: fPoolManagerAbi,
|
|
1142
1130
|
functionName: "initialize",
|
|
1143
|
-
args: [key
|
|
1131
|
+
args: [key],
|
|
1144
1132
|
account: wallet.account,
|
|
1145
1133
|
} as never);
|
|
1146
1134
|
return c.wallet!.writeContract(request as never);
|
|
@@ -1167,16 +1155,15 @@ export async function fPoolKeyOfPool(c: LogswapClient, poolId: Hex, opts: { salt
|
|
|
1167
1155
|
const { logs } = await getEventLogs(c, { indexer: opts.indexer, address: c.addresses.fPoolManager!, event: ev as never, args: { poolId }, fromBlock: opts.fromBlock });
|
|
1168
1156
|
const l = logs[0];
|
|
1169
1157
|
if (!l) throw new Error(`logswap: no PoolCreated for F pool ${poolId}`);
|
|
1170
|
-
const a = l.args as unknown as { quote: Address; creator: Address; bases: readonly Address[];
|
|
1158
|
+
const a = l.args as unknown as { quote: Address; creator: Address; bases: readonly Address[]; swapFee: bigint; policy: Address; mintFee: bigint };
|
|
1171
1159
|
const key: FPoolKey = {
|
|
1172
1160
|
quote: a.quote,
|
|
1173
1161
|
bases: [...a.bases],
|
|
1174
|
-
weights: [...a.weights],
|
|
1175
1162
|
swapFee: a.swapFee,
|
|
1176
1163
|
policy: a.policy,
|
|
1177
1164
|
creator: a.creator,
|
|
1178
1165
|
salt: opts.salt ?? ZERO_SALT,
|
|
1179
|
-
|
|
1166
|
+
mintFee: a.mintFee,
|
|
1180
1167
|
};
|
|
1181
1168
|
if (fPoolIdOfKey(key).toLowerCase() !== poolId.toLowerCase() && opts.salt === undefined) {
|
|
1182
1169
|
// a pad's salt carries its split (decisions 056): rebuild it from the policy's record with the default nonce
|
|
@@ -1195,35 +1182,32 @@ export async function fPoolKeyOfPool(c: LogswapClient, poolId: Hex, opts: { salt
|
|
|
1195
1182
|
}
|
|
1196
1183
|
|
|
1197
1184
|
/**
|
|
1198
|
-
* The reserve a leg holds at a mark: `R = Lj·e^{−x}`, WAD math.
|
|
1199
|
-
* the
|
|
1200
|
-
* the one conversion from a
|
|
1201
|
-
* precision (~1e-16 relative) is what a
|
|
1185
|
+
* The reserve a leg holds at a mark: `R = Lj·e^{−x}`, WAD math. A deployment names the TOTAL base
|
|
1186
|
+
* reserve and the price that values it, and the price follows from the pair, `p = Lj / R` — so this is
|
|
1187
|
+
* the one conversion from a wanted mark to what the pool will hold, done here, on the way in. Float
|
|
1188
|
+
* precision (~1e-16 relative) is what a deployment needs: any reserve is legal, and the mark
|
|
1202
1189
|
* the pool derives from it is the one the sponsor meant to within that.
|
|
1203
1190
|
*/
|
|
1204
1191
|
export function fPoolReserveAt(Lj: bigint, x: bigint, k = 0): bigint {
|
|
1205
|
-
// on a capped pool (decisions 061) the mark reads the virtual reserve R̃ = R + c, and the
|
|
1206
|
-
// puts c = R·k/(1 − k): so the REAL reserve for a mark is L_j·e^{−x}·(1 − k)
|
|
1192
|
+
// on a capped pool (decisions 061) the mark reads the virtual reserve R̃ = R + c, and the
|
|
1193
|
+
// deployment puts c = R·k/(1 − k): so the REAL reserve for a mark is L_j·e^{−x}·(1 − k)
|
|
1207
1194
|
const e = Math.exp(-Number(x) / 1e18) * (1 - k);
|
|
1208
1195
|
return (Lj * BigInt(Math.round(e * 1e18))) / 10n ** 18n;
|
|
1209
1196
|
}
|
|
1210
1197
|
|
|
1211
1198
|
/**
|
|
1212
|
-
* The
|
|
1213
|
-
*
|
|
1214
|
-
* the
|
|
1199
|
+
* The cap constant k = e^{−lnCapOverSeed} (decisions 061, 075): every leg's phantom is c_j = r_j·k/(1 − k), and the
|
|
1200
|
+
* generation's liquidity is its base value over 1 − k. 0 on an uncapped pool. It no longer depends on the bid:
|
|
1201
|
+
* the cap is a ratio of the cap price to each asset's own seed price.
|
|
1215
1202
|
*/
|
|
1216
|
-
export function fPoolCapK(
|
|
1217
|
-
|
|
1218
|
-
const e = Number((Q0 * WAD) / L0) / 1e18 - lnCapOverFloor / 1e6;
|
|
1219
|
-
if (e >= 0) 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}`);
|
|
1220
|
-
return Math.exp(e);
|
|
1203
|
+
export function fPoolCapK(lnCapOverSeed: number): number {
|
|
1204
|
+
return lnCapOverSeed === 0 ? 0 : Math.exp(-lnCapOverSeed / 1e6);
|
|
1221
1205
|
}
|
|
1222
1206
|
|
|
1223
1207
|
/**
|
|
1224
|
-
* The
|
|
1225
|
-
* (decisions 061), so λ = 1/(1 −
|
|
1226
|
-
* **λ = 1 is uncapped**: cap ∞, `
|
|
1208
|
+
* The pool's `lnCapOverSeed` = ln(cap price / seed price) (1e-6 log units) for a leverage λ: ln(λ/(λ − 1))
|
|
1209
|
+
* (decisions 061), so λ = 1/(1 − seed/cap) = L / (base value) and the cap sits λ/(λ − 1) × the seed price — λ = 2
|
|
1210
|
+
* puts it at twice. **λ = 1 is uncapped**: cap ∞, `lnCapOverSeed` 0. A λ under 1, or one so close to
|
|
1227
1211
|
* 1 (or so large) that d leaves a uint24 of 1e-6 units, is refused.
|
|
1228
1212
|
*/
|
|
1229
1213
|
export function fPoolCapOfLeverage(lambda: number): number {
|
|
@@ -1234,102 +1218,182 @@ export function fPoolCapOfLeverage(lambda: number): number {
|
|
|
1234
1218
|
return d;
|
|
1235
1219
|
}
|
|
1236
1220
|
|
|
1237
|
-
/** The leverage
|
|
1238
|
-
export function fPoolLeverageOfCap(
|
|
1239
|
-
return
|
|
1221
|
+
/** The leverage λ = 1/(1 − e^{−x}) for x = `lnCapOverSeed` (1e-6 log units); 1 for an uncapped pool (cap ∞). */
|
|
1222
|
+
export function fPoolLeverageOfCap(lnCapOverSeed: number): number {
|
|
1223
|
+
return lnCapOverSeed === 0 ? 1 : 1 / (1 - Math.exp(-lnCapOverSeed / 1e6));
|
|
1240
1224
|
}
|
|
1241
1225
|
|
|
1242
|
-
/** A pool's leverage, ready to tag: `capped` false and `
|
|
1226
|
+
/** A pool's leverage, ready to tag: `capped` false and `capOverSeed` Infinity for an uncapped pool. */
|
|
1243
1227
|
export interface FPoolLeverage {
|
|
1244
|
-
/** λ at the
|
|
1228
|
+
/** λ at the seed; exactly 1 when uncapped. */
|
|
1245
1229
|
lambda: number;
|
|
1246
1230
|
capped: boolean;
|
|
1247
|
-
/** The cap's price over the
|
|
1248
|
-
|
|
1231
|
+
/** The cap's price over the seed's, e^d = λ/(λ − 1): 2 at λ = 2; Infinity when uncapped. */
|
|
1232
|
+
capOverSeed: number;
|
|
1249
1233
|
/** "1×" uncapped; otherwise λ to two decimals, trailing zeros dropped ("2×", "1.5×"), never "1×" for a capped pool ("1.01×" at least shown as "≈1×"). */
|
|
1250
1234
|
label: string;
|
|
1251
1235
|
}
|
|
1252
1236
|
|
|
1253
1237
|
/**
|
|
1254
|
-
* The leverage tag of a pool from its
|
|
1238
|
+
* The leverage tag of a pool from its `lnCapOverSeed` (decisions 061): `1×` means no cap — the only way a tag
|
|
1255
1239
|
* reads 1× — and a capped pool always reads above it, so the two can never be confused on screen.
|
|
1256
1240
|
*/
|
|
1257
|
-
export function fPoolLeverage(
|
|
1258
|
-
if (
|
|
1259
|
-
const lambda = fPoolLeverageOfCap(
|
|
1241
|
+
export function fPoolLeverage(lnCapOverSeed: number): FPoolLeverage {
|
|
1242
|
+
if (lnCapOverSeed === 0) return { lambda: 1, capped: false, capOverSeed: Infinity, label: "1×" };
|
|
1243
|
+
const lambda = fPoolLeverageOfCap(lnCapOverSeed);
|
|
1260
1244
|
const rounded = Math.round(lambda * 100) / 100;
|
|
1261
1245
|
const label = rounded <= 1 ? "≈1×" : `${String(rounded)}×`;
|
|
1262
|
-
return { lambda, capped: true,
|
|
1246
|
+
return { lambda, capped: true, capOverSeed: Math.exp(lnCapOverSeed / 1e6), label };
|
|
1263
1247
|
}
|
|
1264
1248
|
|
|
1265
|
-
/** The
|
|
1266
|
-
export function fPoolCapOfArgs(a: {
|
|
1249
|
+
/** The `lnCapOverSeed` from deployment args: as given, else from `leverage`, else 0 (uncapped, cap ∞). Both given and disagreeing is refused. */
|
|
1250
|
+
export function fPoolCapOfArgs(a: { lnCapOverSeed?: number; leverage?: number }): number {
|
|
1267
1251
|
const fromLeverage = a.leverage === undefined ? undefined : fPoolCapOfLeverage(a.leverage);
|
|
1268
|
-
if (a.
|
|
1269
|
-
throw new Error(`logswap:
|
|
1270
|
-
return a.
|
|
1252
|
+
if (a.lnCapOverSeed !== undefined && fromLeverage !== undefined && a.lnCapOverSeed !== fromLeverage)
|
|
1253
|
+
throw new Error(`logswap: lnCapOverSeed ${a.lnCapOverSeed} and leverage ${a.leverage} (${fromLeverage}) disagree — pass one`);
|
|
1254
|
+
return a.lnCapOverSeed ?? fromLeverage ?? 0;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
/**
|
|
1258
|
+
* One entry of `deployLiquidity`'s input (F 38, decision 084): the TOTAL base reserve the asset has after the call
|
|
1259
|
+
* (0 leaves it out) and the price that values it, quote atomic units per base atomic unit, 1e36-scaled.
|
|
1260
|
+
*/
|
|
1261
|
+
export interface BaseAsset {
|
|
1262
|
+
base: Address;
|
|
1263
|
+
amount: bigint;
|
|
1264
|
+
priceX36: bigint;
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/** The book a deployment names, from the sponsor's terms: weights, total liquidity `L0`, and either the wanted marks `x0` or the reserves `r0`. */
|
|
1268
|
+
export type FPoolBookSpec = {
|
|
1269
|
+
/** The pool's assets, in any order; the result is sorted into the key's order. */
|
|
1270
|
+
bases: Address[];
|
|
1271
|
+
/** WAD, one per asset, summing to 1e18; 0 leaves the asset out (not in generation 0). `L_j = w_j · L0`. */
|
|
1272
|
+
weights: bigint[];
|
|
1273
|
+
/** The book's total liquidity, quote units. */
|
|
1274
|
+
L0: bigint;
|
|
1275
|
+
/** The pool's one cap, or the leverage it stands for; absent is uncapped. */
|
|
1276
|
+
lnCapOverSeed?: number;
|
|
1277
|
+
leverage?: number;
|
|
1278
|
+
} & ({ x0: bigint[] } | { r0: bigint[] });
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* The `baseAssets` (and cap) a deployment sends for a wanted book — what the old seed did with reserves and
|
|
1282
|
+
* marks, as the amounts and prices the manager takes now. Per asset: the reserve `r_j` (given as `r0`, or
|
|
1283
|
+
* {@link fPoolReserveAt} the wanted mark `x0`) and the price that makes its value `L_j · (1 − k)`:
|
|
1284
|
+
* `priceX36 = ceil(L_j(1 − k) · 1e36 / r_j)`. A zero weight is an asset left out. Sorted by base address, the
|
|
1285
|
+
* key's order, with the companions carried along.
|
|
1286
|
+
*/
|
|
1287
|
+
export function fPoolBook(a: FPoolBookSpec): { baseAssets: BaseAsset[]; lnCapOverSeed: number } {
|
|
1288
|
+
const sum = a.weights.reduce((x, y) => x + y, 0n);
|
|
1289
|
+
if (sum !== WAD) throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
|
|
1290
|
+
if (a.weights.length !== a.bases.length) throw new Error(`logswap: ${a.weights.length} weights for ${a.bases.length} assets`);
|
|
1291
|
+
const lnCapOverSeed = fPoolCapOfArgs(a);
|
|
1292
|
+
const k = fPoolCapK(lnCapOverSeed);
|
|
1293
|
+
const oneMinusK = BigInt(Math.round((1 - k) * 1e18));
|
|
1294
|
+
const rows = a.bases.map((base, j): BaseAsset => {
|
|
1295
|
+
const w = a.weights[j]!;
|
|
1296
|
+
if (w === 0n) return { base, amount: 0n, priceX36: 0n };
|
|
1297
|
+
const Lj = (w * a.L0) / WAD;
|
|
1298
|
+
const amount = "r0" in a ? a.r0[j]! : fPoolReserveAt(Lj, a.x0[j]!, k);
|
|
1299
|
+
if (amount === 0n) throw new Error(`logswap: asset ${base} has weight ${w} but a zero reserve`);
|
|
1300
|
+
const value = (Lj * oneMinusK) / WAD;
|
|
1301
|
+
return { base, amount, priceX36: (value * 10n ** 36n + amount - 1n) / amount };
|
|
1302
|
+
});
|
|
1303
|
+
const { companions } = sortFPoolLegs(a.bases, rows);
|
|
1304
|
+
return { baseAssets: companions[0]!, lnCapOverSeed };
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/**
|
|
1308
|
+
* The allocation a `deployLiquidity` book implies: asset `j`'s value `amount_j · priceX36_j / 1e36` over the sum,
|
|
1309
|
+
* normalized as the manager does it (cumulative shares, floored), so the weights sum to exactly 1e18. A zero-value
|
|
1310
|
+
* book has no allocation (`[]`). What an indexer derives from `LiquidityDeployed` instead of reading the weights.
|
|
1311
|
+
*/
|
|
1312
|
+
export function fPoolBookWeights(baseAssets: readonly BaseAsset[]): bigint[] {
|
|
1313
|
+
const values = baseAssets.map((x) => (x.amount * x.priceX36) / 10n ** 36n);
|
|
1314
|
+
const total = values.reduce((x, y) => x + y, 0n);
|
|
1315
|
+
if (total === 0n) return [];
|
|
1316
|
+
let cumulative = 0n;
|
|
1317
|
+
let previous = 0n;
|
|
1318
|
+
return values.map((v) => {
|
|
1319
|
+
cumulative += v;
|
|
1320
|
+
const next = (cumulative * WAD) / total;
|
|
1321
|
+
const w = next - previous;
|
|
1322
|
+
previous = next;
|
|
1323
|
+
return w;
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* The book's total liquidity `L` from a `LiquidityDeployed` input: the values' sum over `1 − k`, `k = e^{−cap}`.
|
|
1329
|
+
* Exact when uncapped; with a cap it carries the float error of `k` (~1e-16 relative) — read the pool for the wei.
|
|
1330
|
+
*/
|
|
1331
|
+
export function fPoolBookL(baseAssets: readonly BaseAsset[], lnCapOverSeed: number): bigint {
|
|
1332
|
+
const total = baseAssets.reduce((x, a) => x + (a.amount * a.priceX36) / 10n ** 36n, 0n);
|
|
1333
|
+
if (lnCapOverSeed === 0) return total;
|
|
1334
|
+
const oneMinusK = BigInt(Math.round((1 - fPoolCapK(lnCapOverSeed)) * 1e18));
|
|
1335
|
+
return (total * WAD) / oneMinusK;
|
|
1271
1336
|
}
|
|
1272
1337
|
|
|
1273
1338
|
/**
|
|
1274
|
-
*
|
|
1275
|
-
* the
|
|
1276
|
-
*
|
|
1277
|
-
*
|
|
1278
|
-
* {@link
|
|
1339
|
+
* Put liquidity into the pool, the authority's: `deployLiquidity` (F 38, decisions 083, 084). It SETS THE BOOK:
|
|
1340
|
+
* `baseAssets[j].amount` is the total base reserve of asset `j` after the call (0 removes it), `quoteAmount` the
|
|
1341
|
+
* total bid, and the manager settles each figure against what the pool holds — a larger total is pulled from the
|
|
1342
|
+
* caller, a smaller one pushed to `to` — so one call can replace an asset by another. Pass the book outright
|
|
1343
|
+
* (`baseAssets`, `lnCapOverSeed`) or the sponsor's terms ({@link fPoolBook}: `weights`, `L0` and marks `x0` or
|
|
1344
|
+
* reserves `r0`, in any order). On an UNFUNDED pool (new, or after {@link fPoolClose}) it funds the first or the next
|
|
1345
|
+
* generation. On a LIVE pool it is a regeneration that sets the book: income settles to `to`, the policy picks the
|
|
1346
|
+
* carried holder, every other holder is frozen into the closing generation's bundle ({@link fPoolRedeem}), and the
|
|
1347
|
+
* carried book becomes the one named, at the supplied prices. A pad is forward-only ({@link fPoolRegenerate}).
|
|
1279
1348
|
*/
|
|
1280
|
-
export async function
|
|
1349
|
+
export async function fPoolDeploy(
|
|
1281
1350
|
c: LogswapClient,
|
|
1282
|
-
a: { poolId: Hex;
|
|
1351
|
+
a: { poolId: Hex; quoteAmount: bigint; to?: Address; account: Address } & (
|
|
1352
|
+
| { baseAssets: BaseAsset[]; lnCapOverSeed: number }
|
|
1353
|
+
| FPoolBookSpec
|
|
1354
|
+
),
|
|
1283
1355
|
) {
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
else {
|
|
1287
|
-
const k = fPoolCapK(Number((await rawFPool(c, a.poolId)).lnCapOverFloor), a.Q0, a.L0);
|
|
1288
|
-
r0 = a.x0.map((x, j) => fPoolReserveAt((a.weights[j]! * a.L0) / 10n ** 18n, x, k));
|
|
1289
|
-
}
|
|
1290
|
-
return writeFPool(c, a.poolId, "seed", [a.L0, r0, a.Q0], a.account);
|
|
1356
|
+
const { baseAssets, lnCapOverSeed } = "baseAssets" in a ? a : fPoolBook(a);
|
|
1357
|
+
return writeFPool(c, a.poolId, "deployLiquidity", [baseAssets, a.quoteAmount, lnCapOverSeed, a.to ?? a.account], a.account);
|
|
1291
1358
|
}
|
|
1292
1359
|
|
|
1293
1360
|
/**
|
|
1294
|
-
*
|
|
1295
|
-
*
|
|
1296
|
-
*
|
|
1297
|
-
* (
|
|
1298
|
-
*
|
|
1299
|
-
* which opens generation `gen + 1` under the same id, policy, roles, gates and lists.
|
|
1361
|
+
* Close the pool — the raw entry (`retire` before F 38). Allowed only at an empty bid, Q ≤ L/1e9, on every pool but a
|
|
1362
|
+
* pad: the market took it, or the operator harvested it out first ({@link fPoolClose} does both in one transaction).
|
|
1363
|
+
* Income settles to `to` first. The live (S, Q, R_j) become a frozen bundle every share of this generation redeems
|
|
1364
|
+
* ({@link fPoolRedeem}), forever; the pool is unfunded until the next {@link fPoolDeploy}, which opens generation
|
|
1365
|
+
* `gen + 1` under the same id, policy, roles, gates and lists. Whoever runs the pool.
|
|
1300
1366
|
*/
|
|
1301
|
-
export async function
|
|
1302
|
-
return writeFPool(c, a.poolId, "
|
|
1367
|
+
export async function fPoolCloseRaw(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address }) {
|
|
1368
|
+
return writeFPool(c, a.poolId, "close", [a.to ?? a.account], a.account);
|
|
1303
1369
|
}
|
|
1304
1370
|
|
|
1305
1371
|
/**
|
|
1306
|
-
*
|
|
1372
|
+
* Close the pool as ONE transaction: the harvest that empties the bid
|
|
1307
1373
|
* ({@link fPoolEmptyingHarvests} — a dividend to every share; none when it is already empty),
|
|
1308
|
-
* then `
|
|
1309
|
-
*
|
|
1374
|
+
* then `close` — the manager's `multicall`, the operator as sender. What a sponsor's "close" button
|
|
1375
|
+
* should call. Throws before sending on a pad: a pad never closes.
|
|
1310
1376
|
*/
|
|
1311
|
-
export async function
|
|
1377
|
+
export async function fPoolClose(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address }) {
|
|
1312
1378
|
const harvests = await fPoolEmptyingHarvests(c, a.poolId);
|
|
1313
|
-
if (harvests.length === 0) return
|
|
1379
|
+
if (harvests.length === 0) return fPoolCloseRaw(c, a);
|
|
1314
1380
|
const enc = (functionName: string, args: unknown[]) =>
|
|
1315
1381
|
encodeFunctionData({ abi: fPoolManagerAbi, functionName, args } as never) as Hex;
|
|
1316
|
-
const calls: Hex[] = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("
|
|
1382
|
+
const calls: Hex[] = [...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])), enc("close", [a.poolId, a.to ?? a.account])];
|
|
1317
1383
|
return writeFPool0(c, "multicall", [calls], a.account);
|
|
1318
1384
|
}
|
|
1319
1385
|
|
|
1320
1386
|
/**
|
|
1321
|
-
* The harvests that empty an unlocked pool's bid, in order — what a
|
|
1322
|
-
* `
|
|
1323
|
-
*
|
|
1324
|
-
*
|
|
1325
|
-
*
|
|
1326
|
-
* (`PolPolicy.minQuoteRatio`): a `retire` under that policy waits for the market.
|
|
1387
|
+
* The harvests that empty an unlocked pool's bid, in order — what a close sends before its
|
|
1388
|
+
* `close` (a close needs an empty bid on every pool). One `harvest(Q)` does it: the income tax leaves the pool with
|
|
1389
|
+
* the income part (with no treasury there is none). `[]` when the bid is already empty. Throws on a pad (a pad
|
|
1390
|
+
* never closes, whatever its bid), and when the pool's policy keeps a floor on the bid
|
|
1391
|
+
* (`PolPolicy.minQuoteRatio`): a `close` under that policy waits for the market.
|
|
1327
1392
|
*/
|
|
1328
1393
|
export async function fPoolEmptyingHarvests(c: LogswapClient, poolId: Hex): Promise<bigint[]> {
|
|
1329
1394
|
const s = await getFPool(c, poolId);
|
|
1330
|
-
//
|
|
1331
|
-
|
|
1332
|
-
if (s.kind === "pad") throw new Error("logswap: a pad never retires (F version 21) — it graduates by regenerate; a fresh start is a new pad");
|
|
1395
|
+
// `PadPolicy` refuses `close` at any bid — a pad graduates (regenerate), it never closes; a fresh start is a new pad
|
|
1396
|
+
if (s.kind === "pad") throw new Error("logswap: a pad never closes — it graduates by regenerate; a fresh start is a new pad");
|
|
1333
1397
|
if (s.Q === 0n) return [];
|
|
1334
1398
|
const { maxHarvest } = await getFPoolRoles(c, poolId, s);
|
|
1335
1399
|
if (maxHarvest < s.Q) throw new Error("logswap: the pool's policy keeps a floor on the bid — it cannot be harvested empty");
|
|
@@ -1337,72 +1401,28 @@ export async function fPoolEmptyingHarvests(c: LogswapClient, poolId: Hex): Prom
|
|
|
1337
1401
|
}
|
|
1338
1402
|
|
|
1339
1403
|
/**
|
|
1340
|
-
* The GENERATION STEP
|
|
1341
|
-
* generation's income first, releases the dead shares'
|
|
1404
|
+
* The GENERATION STEP — on a pad, its graduation (F 38: `deployLiquidity` with nothing changed). The manager
|
|
1405
|
+
* harvests the generation's income first, releases the dead shares' income, and asks the policy
|
|
1342
1406
|
* (`onRegenerate`), whose {@link FPolicyTerms} name a `carried` holder. Then, for live
|
|
1343
1407
|
* generation `g`:
|
|
1344
1408
|
*
|
|
1345
1409
|
* - the carried holder's and the dead shares' `g` shares are re-minted 1:1 as `g + 1`: they go on
|
|
1346
1410
|
* as the pool;
|
|
1347
|
-
* - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`
|
|
1411
|
+
* - every OTHER holder of `g` is frozen out pro rata into generation `g`'s bundle (`GenerationRetired`)
|
|
1348
1412
|
* and redeems it with {@link fPoolRedeem} / rolls it with {@link fPoolRollIn} (`gen: g`); their
|
|
1349
1413
|
* dividends on `g` stay claimable ({@link fPoolClaim} with `gen: g`). {@link fPoolClaimsOf}
|
|
1350
1414
|
* lists them;
|
|
1351
|
-
* - the
|
|
1352
|
-
*
|
|
1353
|
-
* rest into the bid (the floor down). No share is minted; L does not move.
|
|
1415
|
+
* - the income released (`IncomeReleased`), all in quote: `toPayee` to the payee and the rest into the bid
|
|
1416
|
+
* (the floor down). No share is minted; L does not move. The book keeps its reserves, marks and cap.
|
|
1354
1417
|
*
|
|
1355
1418
|
* A pad's gate is `threshold(poolId, gen)`, in its quote (`PadPolicy.NotGraduated` below it); POL and private carry the
|
|
1356
|
-
* authority and send it the whole
|
|
1357
|
-
* share is `BadTerms`. Whoever runs the pool.
|
|
1419
|
+
* authority and send it the whole income; a public pool refuses (`Refused`). A carried holder with no
|
|
1420
|
+
* share is `BadTerms`. Whoever runs the pool. To change the book (reserves, prices, cap) use {@link fPoolDeploy}.
|
|
1358
1421
|
*/
|
|
1359
1422
|
export async function fPoolRegenerate(c: LogswapClient, a: { poolId: Hex; to?: Address; account: Address }) {
|
|
1360
1423
|
return writeFPool(c, a.poolId, "regenerate", [a.to ?? a.account], a.account);
|
|
1361
1424
|
}
|
|
1362
1425
|
|
|
1363
|
-
/**
|
|
1364
|
-
* The relaunch as ONE transaction: `harvest` the bid out — a
|
|
1365
|
-
* dividend to every share, {@link fPoolEmptyingHarvests} — `retire` the live generation at the
|
|
1366
|
-
* empty bid, `redeem` the caller's own shares of it (when `shares` > 0), optionally `setLegs` the
|
|
1367
|
-
* next generation's composition (`legs`: a private pool's reshape — retire, admit, reweight), and
|
|
1368
|
-
* `seed` it with what came back — the manager's `multicall`, one sender throughout, the same
|
|
1369
|
-
* pool. The operator's when one is appointed and the seed's inventory is its own; by default the
|
|
1370
|
-
* authority's. The policy, its roles, gates, allowlist and the name carry over; anything else goes
|
|
1371
|
-
* in `extra`, pre-encoded against {@link fPoolManagerAbi}. The seed names reserves (decisions
|
|
1372
|
-
* 029): `r0` outright — one per leg of the NEXT table, 0 for a retired leg — or `x0` marks
|
|
1373
|
-
* against the next table's `weights`.
|
|
1374
|
-
*/
|
|
1375
|
-
export async function fPoolRelaunch(
|
|
1376
|
-
c: LogswapClient,
|
|
1377
|
-
a: {
|
|
1378
|
-
poolId: Hex;
|
|
1379
|
-
/** the caller's shares of the retiring generation to redeem inside the batch — its whole balance, usually; 0 to keep the claim */
|
|
1380
|
-
shares: bigint;
|
|
1381
|
-
L0: bigint;
|
|
1382
|
-
Q0: bigint;
|
|
1383
|
-
/** the next generation's composition: one weight per existing leg (0 retires it), then one per new base */
|
|
1384
|
-
legs?: { weights: bigint[]; newBases?: Address[] };
|
|
1385
|
-
extra?: Hex[];
|
|
1386
|
-
account: Address;
|
|
1387
|
-
} & ({ r0: bigint[] } | { x0: bigint[]; weights: bigint[] }),
|
|
1388
|
-
) {
|
|
1389
|
-
const [raw, harvests] = await Promise.all([rawFPool(c, a.poolId), fPoolEmptyingHarvests(c, a.poolId)]);
|
|
1390
|
-
const gen = Number(raw.gen);
|
|
1391
|
-
const k = "r0" in a ? 0 : fPoolCapK(Number(raw.lnCapOverFloor), a.Q0, a.L0);
|
|
1392
|
-
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)));
|
|
1393
|
-
const enc = (functionName: string, args: unknown[]) =>
|
|
1394
|
-
encodeFunctionData({ abi: fPoolManagerAbi, functionName, args } as never) as Hex;
|
|
1395
|
-
const calls: Hex[] = [
|
|
1396
|
-
...harvests.map((amount) => enc("harvest", [a.poolId, amount, a.account])),
|
|
1397
|
-
enc("retire", [a.poolId]),
|
|
1398
|
-
...(a.shares > 0n ? [enc("redeem", [a.poolId, BigInt(gen), a.account, a.shares])] : []),
|
|
1399
|
-
...(a.legs ? [enc("setLegs", [a.poolId, a.legs.weights, a.legs.newBases ?? []])] : []),
|
|
1400
|
-
enc("seed", [a.poolId, a.L0, r0, a.Q0]),
|
|
1401
|
-
...(a.extra ?? []),
|
|
1402
|
-
];
|
|
1403
|
-
return writeFPool0(c, "multicall", [calls], a.account);
|
|
1404
|
-
}
|
|
1405
|
-
|
|
1406
1426
|
/** Where a pad's seed lives: `seed` mints every share of a pad here itself. */
|
|
1407
1427
|
export const DEAD_ADDRESS: Address = "0x000000000000000000000000000000000000dEaD";
|
|
1408
1428
|
/** 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. */
|
|
@@ -1432,9 +1452,15 @@ export interface FPoolGenesisTransfer {
|
|
|
1432
1452
|
}
|
|
1433
1453
|
|
|
1434
1454
|
export interface FPoolLaunchArgs extends Omit<FPoolCreateArgs, "account"> {
|
|
1455
|
+
/** WAD, one per asset (in `bases` order), summing to 1e18; `L_j = w_j · L0`. The generation's allocation (F 38: not in the key). */
|
|
1456
|
+
weights: bigint[];
|
|
1457
|
+
/** The generation's total liquidity, quote units. */
|
|
1435
1458
|
L0: bigint;
|
|
1436
|
-
/**
|
|
1437
|
-
|
|
1459
|
+
/** The pool's one cap as ln(cap price / seed price), 1e-6 log units, or the leverage it stands for; absent is uncapped. A pad is always uncapped (`PadUncapped`). */
|
|
1460
|
+
lnCapOverSeed?: number;
|
|
1461
|
+
leverage?: number;
|
|
1462
|
+
/** The bid the deployment pulls (`quoteAmount`). A pad deploys at 0 — pure float, a resting ask, nothing raised. */
|
|
1463
|
+
quoteAmount: bigint;
|
|
1438
1464
|
/**
|
|
1439
1465
|
* An opening buy of leg `j` (an index into `bases` AS GIVEN) for `amountIn` of quote, ON THE
|
|
1440
1466
|
* MANAGER — the same sender, a plain allowance to the manager, the router nowhere near it. A
|
|
@@ -1478,21 +1504,25 @@ export function fPoolLaunchCalls(
|
|
|
1478
1504
|
poolId: Hex,
|
|
1479
1505
|
a: FPoolLaunchArgs & ({ r0: bigint[] } | { x0: bigint[] }),
|
|
1480
1506
|
): Hex[] {
|
|
1481
|
-
const sum = a.weights.reduce((x, y) => x + y, 0n);
|
|
1482
|
-
if (sum !== WAD) throw new Error(`logswap: weights sum to ${sum}, expected 1e18`);
|
|
1483
|
-
const k = "r0" in a ? 0 : fPoolCapK(fPoolCapOfArgs(a), a.Q0, a.L0);
|
|
1484
|
-
const given = "r0" in a ? a.r0 : a.x0.map((x, j) => fPoolReserveAt((a.weights[j]! * a.L0) / WAD, x, k));
|
|
1485
|
-
if (given.length !== a.bases.length) throw new Error(`logswap: ${given.length} reserves for ${a.bases.length} legs`);
|
|
1486
|
-
const { bases, companions } = sortFPoolLegs(a.bases, a.weights, given);
|
|
1487
1507
|
if (!a.policy) throw new Error("logswap: fPoolLaunchCalls needs the key's policy — fPoolLaunch fills it from the deployment");
|
|
1488
|
-
const
|
|
1508
|
+
const { baseAssets, lnCapOverSeed } = fPoolBook(a);
|
|
1509
|
+
const bases = baseAssets.map((x) => x.base);
|
|
1510
|
+
const key: FPoolKey = {
|
|
1511
|
+
quote: a.quote,
|
|
1512
|
+
bases,
|
|
1513
|
+
swapFee: a.swapFee,
|
|
1514
|
+
policy: a.policy,
|
|
1515
|
+
creator: a.creator,
|
|
1516
|
+
salt: a.salt ?? ZERO_SALT,
|
|
1517
|
+
mintFee: a.mintFee ?? presetMintFee(a.swapFee),
|
|
1518
|
+
};
|
|
1489
1519
|
const enc = (functionName: string, args: unknown[]) =>
|
|
1490
1520
|
encodeFunctionData({ abi: fPoolManagerAbi, functionName, args } as never) as Hex;
|
|
1491
1521
|
const calls: Hex[] = [];
|
|
1492
|
-
if (!a.initialized) calls.push(enc("initialize", [key
|
|
1493
|
-
calls.push(enc("
|
|
1494
|
-
// gen 0 by construction: a launch is the pool's FIRST
|
|
1495
|
-
// No transfer to 0xdead: on a pad `
|
|
1522
|
+
if (!a.initialized) calls.push(enc("initialize", [key]));
|
|
1523
|
+
calls.push(enc("deployLiquidity", [poolId, baseAssets, a.quoteAmount, lnCapOverSeed, a.account]));
|
|
1524
|
+
// gen 0 by construction: a launch is the pool's FIRST deployment — a later one is `fPoolDeploy` on the live pool.
|
|
1525
|
+
// No transfer to 0xdead: on a pad `deployLiquidity` mints every share there itself.
|
|
1496
1526
|
for (const row of fPoolGenesisRows(a)) {
|
|
1497
1527
|
const j = bases.indexOf(a.bases[row.j]!);
|
|
1498
1528
|
if (j < 0) throw new Error(`logswap: genesis row j = ${row.j} is not a leg`);
|
|
@@ -1532,7 +1562,7 @@ export async function fPoolGenesisOutputs(
|
|
|
1532
1562
|
account: signerFor(c, a.account),
|
|
1533
1563
|
} as never);
|
|
1534
1564
|
const results = result as readonly Hex[];
|
|
1535
|
-
const first = (a.initialized ? 0 : 1) + 1; // [initialize] ·
|
|
1565
|
+
const first = (a.initialized ? 0 : 1) + 1; // [initialize] · deployLiquidity · rows
|
|
1536
1566
|
return rows.map((_, i) => decodeAbiParameters([{ type: "uint256" }], results[first + i]!)[0] as bigint);
|
|
1537
1567
|
}
|
|
1538
1568
|
|
|
@@ -1811,21 +1841,6 @@ export async function fPoolSetPoolOperator(c: LogswapClient, a: { poolId: Hex; o
|
|
|
1811
1841
|
return writePolicy(c, privatePolicyAbi, a, "setPoolOperator", [a.operator]);
|
|
1812
1842
|
}
|
|
1813
1843
|
|
|
1814
|
-
/**
|
|
1815
|
-
* The next generation's composition (operator; private pools only; ONLY while the pool is
|
|
1816
|
-
* unseeded — between a retire and the seed that prices it). `weights` has one
|
|
1817
|
-
* entry per leg the pool has ever had, in index order (0 retires a leg; indices are never reused),
|
|
1818
|
-
* then one per base in `newBases`, appended; they sum to 1e18 exactly. No value moves: the
|
|
1819
|
-
* following {@link fPoolSeed} names every reserve. A live reshape is {@link fPoolRelaunch} with
|
|
1820
|
-
* `legs` set.
|
|
1821
|
-
*/
|
|
1822
|
-
export async function fPoolSetLegs(
|
|
1823
|
-
c: LogswapClient,
|
|
1824
|
-
a: { poolId: Hex; weights: bigint[]; newBases?: Address[]; account: Address },
|
|
1825
|
-
) {
|
|
1826
|
-
return writeFPool(c, a.poolId, "setLegs", [a.weights, a.newBases ?? []], a.account);
|
|
1827
|
-
}
|
|
1828
|
-
|
|
1829
1844
|
/**
|
|
1830
1845
|
* Move shares (ERC-6909 `transfer`) — to another holder, or to `0xdead` to lock them for good.
|
|
1831
1846
|
* Burning to the dead address is a sponsor's way to make its liquidity permanent: the shares can
|
|
@@ -1853,10 +1868,13 @@ export interface DiscoveredFPool {
|
|
|
1853
1868
|
poolId: Hex;
|
|
1854
1869
|
quote: Address;
|
|
1855
1870
|
bases: Address[];
|
|
1871
|
+
/** The generation-0 allocation, from the pool's first `LiquidityDeployed` ({@link fPoolBookWeights}); `[]` until it is deployed — F 38 keeps no weights in the key. */
|
|
1856
1872
|
weights: bigint[];
|
|
1857
1873
|
swapFee: bigint;
|
|
1858
|
-
/** The
|
|
1859
|
-
|
|
1874
|
+
/** The creator-selected mint fee, fixed for life (F 38, decision 078). */
|
|
1875
|
+
mintFee: bigint;
|
|
1876
|
+
/** The generation-0 cap as ln(cap price / seed price), in 1e-6 log units; 0 uncapped, cap ∞ (decisions 061); 0 until deployed. */
|
|
1877
|
+
lnCapOverSeed: number;
|
|
1860
1878
|
kind: FPoolKind;
|
|
1861
1879
|
/** The pool's policy AT BIRTH — the contract the key names. The LIVE one is {@link getFPool}'s `policy`: the registry's owner may have moved the pool (046, `PolicyMigrated`). */
|
|
1862
1880
|
policy: Address;
|
|
@@ -1864,7 +1882,7 @@ export interface DiscoveredFPool {
|
|
|
1864
1882
|
creator: Address;
|
|
1865
1883
|
/** The block the pool was initialized in — its age, for annualising realized income. */
|
|
1866
1884
|
block: bigint;
|
|
1867
|
-
/** Whether `
|
|
1885
|
+
/** Whether `deployLiquidity` has run; an unfunded pool has no floor and no float, so nothing to show. */
|
|
1868
1886
|
seeded: boolean;
|
|
1869
1887
|
/** The quote the pool was born with. Zero is the launchpad's signature. */
|
|
1870
1888
|
q0: bigint;
|
|
@@ -1879,8 +1897,8 @@ export interface DiscoveredFPool {
|
|
|
1879
1897
|
|
|
1880
1898
|
/**
|
|
1881
1899
|
* Every F pool ever created, from `PoolCreated` logs alone — plus one `kind()` read per distinct
|
|
1882
|
-
* policy, cached. Possible only because the event carries the full key preimage (bases,
|
|
1883
|
-
*
|
|
1900
|
+
* policy, cached. Possible only because the event carries the full key preimage (quote, creator, bases,
|
|
1901
|
+
* swapFee, policy, mintFee) — the poolId is a hash and could never be inverted; contracts PR #17
|
|
1884
1902
|
* exists for exactly this call. With `indexer`, the logs come from it (the node when it fails):
|
|
1885
1903
|
* a scan from block 0 per call is what made the first load wait on the node.
|
|
1886
1904
|
*/
|
|
@@ -1891,39 +1909,42 @@ export async function discoverFPools(
|
|
|
1891
1909
|
type Ev = Extract<(typeof fPoolManagerAbi)[number], { type: "event"; name: "PoolCreated" }>;
|
|
1892
1910
|
const ev = fPoolManagerAbi.find((x): x is Ev => x.type === "event" && x.name === "PoolCreated");
|
|
1893
1911
|
if (!ev) throw new Error("logswap: F PoolCreated event missing from the generated ABI");
|
|
1894
|
-
type
|
|
1895
|
-
const
|
|
1912
|
+
type DeployEv = Extract<(typeof fPoolManagerAbi)[number], { type: "event"; name: "LiquidityDeployed" }>;
|
|
1913
|
+
const deployEv = fPoolManagerAbi.find((x): x is DeployEv => x.type === "event" && x.name === "LiquidityDeployed");
|
|
1896
1914
|
const range = { indexer: opts.indexer, address: c.addresses.fPoolManager!, fromBlock: opts.fromBlock, toBlock: opts.toBlock };
|
|
1897
|
-
const [{ logs }, { logs:
|
|
1915
|
+
const [{ logs }, { logs: deploys }] = await Promise.all([
|
|
1898
1916
|
getEventLogs(c, { ...range, event: ev }),
|
|
1899
|
-
|
|
1917
|
+
deployEv ? getEventLogs(c, { ...range, event: deployEv }) : Promise.resolve({ logs: [] }),
|
|
1900
1918
|
]);
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1919
|
+
// the pool's first deployment (generation 0) names its allocation, cap and opening bid
|
|
1920
|
+
const first = new Map<string, { weights: bigint[]; lnCapOverSeed: number; q0: bigint }>();
|
|
1921
|
+
for (const l of deploys) {
|
|
1922
|
+
const a = l.args as { poolId: Hex; gen: bigint | number; quoteAmount: bigint; baseAssets: readonly BaseAsset[]; lnCapOverSeed: number | bigint };
|
|
1923
|
+
if (BigInt(a.gen) !== 0n) continue;
|
|
1924
|
+
first.set(a.poolId.toLowerCase(), { weights: fPoolBookWeights(a.baseAssets), lnCapOverSeed: Number(a.lnCapOverSeed), q0: a.quoteAmount });
|
|
1905
1925
|
}
|
|
1906
1926
|
return Promise.all(
|
|
1907
1927
|
logs.map(async (l) => {
|
|
1908
1928
|
const a = l.args as {
|
|
1909
1929
|
poolId: Hex; quote: Address; creator: Address; bases: readonly Address[];
|
|
1910
|
-
|
|
1930
|
+
swapFee: bigint; policy: Address; mintFee: bigint;
|
|
1911
1931
|
};
|
|
1912
|
-
const
|
|
1932
|
+
const g0 = first.get(a.poolId.toLowerCase());
|
|
1913
1933
|
const kind = await fPoolKindOfPolicy(c, a.policy); // one read per distinct policy, cached
|
|
1914
1934
|
return {
|
|
1915
1935
|
poolId: a.poolId,
|
|
1916
1936
|
quote: a.quote,
|
|
1917
1937
|
bases: [...a.bases],
|
|
1918
|
-
weights: [
|
|
1938
|
+
weights: g0?.weights ?? [],
|
|
1919
1939
|
swapFee: a.swapFee,
|
|
1920
|
-
|
|
1940
|
+
mintFee: a.mintFee,
|
|
1941
|
+
lnCapOverSeed: g0?.lnCapOverSeed ?? 0,
|
|
1921
1942
|
kind,
|
|
1922
1943
|
policy: a.policy,
|
|
1923
1944
|
creator: a.creator,
|
|
1924
1945
|
block: l.blockNumber,
|
|
1925
|
-
seeded:
|
|
1926
|
-
q0: q0 ?? 0n,
|
|
1946
|
+
seeded: g0 !== undefined,
|
|
1947
|
+
q0: g0?.q0 ?? 0n,
|
|
1927
1948
|
shape: kind === "pad" ? "launch": "basket", // the policy's word, not n = 1: a mono POL is a pool
|
|
1928
1949
|
};
|
|
1929
1950
|
}),
|
|
@@ -1953,21 +1974,22 @@ export type FPoolRules =
|
|
|
1953
1974
|
gen: number;
|
|
1954
1975
|
/** @deprecated Equal to {@link gen} since F version 21, kept for callers; read `gen`. */
|
|
1955
1976
|
rung: number;
|
|
1956
|
-
/** The
|
|
1977
|
+
/** The income the next graduation needs, in the pad's quote: `PadPolicy.threshold(poolId, gen)` (T(0) is per quote, decision 070). */
|
|
1957
1978
|
threshold: bigint;
|
|
1958
|
-
|
|
1959
|
-
|
|
1979
|
+
/** The dead shares' income held for the next graduation, in the pad's quote. */
|
|
1980
|
+
income: bigint;
|
|
1981
|
+
/** This pad's creator share, recorded at its birth from the key's salt and never changed (decisions 056, 057, 067): a fraction of the income released. The rest deepens the bid; nothing is bought or burnt (067). */
|
|
1960
1982
|
creatorShare: bigint;
|
|
1961
|
-
/** The income
|
|
1962
|
-
|
|
1983
|
+
/** The income tax the dead shares pay on their own new income dividend (decisions 073, 085), WAD. */
|
|
1984
|
+
incomeTaxRate: bigint;
|
|
1963
1985
|
/** The ranges the LOG Authority set on the policy NOW for the pads born after this read: what a new creator may choose. */
|
|
1964
1986
|
ranges: PadRanges;
|
|
1965
1987
|
}
|
|
1966
|
-
| { kind: "pol"; /** The reserve a harvest leaves in the bid and a
|
|
1988
|
+
| { kind: "pol"; /** The reserve a harvest leaves in the bid and a redeployment must keep, a multiple of L (WAD). */ minQuoteRatio: bigint; /** The income tax the pool's authority pays on its own new income dividend (decisions 073, 085), WAD. */ incomeTaxRate: bigint }
|
|
1967
1989
|
| { kind: "public" }
|
|
1968
1990
|
| { kind: "private"; gateMint: boolean; swapMode: FPoolSwapMode; swapExecutor: Address; operator: Address };
|
|
1969
1991
|
|
|
1970
|
-
/** The LOG Authority's range on a pad's creator choice (`PadPolicy`, decisions 056, 067), WAD fractions of the
|
|
1992
|
+
/** The LOG Authority's range on a pad's creator choice (`PadPolicy`, decisions 056, 067), WAD fractions of the income released. */
|
|
1971
1993
|
export interface PadRanges {
|
|
1972
1994
|
creatorShareMin: bigint;
|
|
1973
1995
|
/** At most the F manager's `PAYEE_CUT_MAX` (50%), which bounds a pad's payee whatever the policy (067). */
|
|
@@ -1979,7 +2001,7 @@ const MAX_U128 = (1n << 128n) - 1n;
|
|
|
1979
2001
|
|
|
1980
2002
|
/**
|
|
1981
2003
|
* The salt that carries a pad's split (`PadPolicy.pack(creatorShare, nonce)`, decisions 056, 067): `creatorShare` in the top 64
|
|
1982
|
-
* bits (a WAD fraction of the
|
|
2004
|
+
* 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
|
|
1983
2005
|
* 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
|
|
1984
2006
|
* chosen at launch (`FPoolLaunchArgs.salt`) and never changes; the policy refuses a cut outside its range.
|
|
1985
2007
|
*/
|
|
@@ -2005,20 +2027,20 @@ export async function getFPoolRules(c: LogswapClient, s: Pick<FPoolState, "poolI
|
|
|
2005
2027
|
case "pad": {
|
|
2006
2028
|
// the rung is the manager's generation (F version 21): a move carries it, nothing to ask the policy
|
|
2007
2029
|
const gen = s.gen;
|
|
2008
|
-
const [creatorShare,
|
|
2030
|
+
const [creatorShare, income, threshold, incomeTaxRate, creatorShareMin, creatorShareMax] = await Promise.all([
|
|
2009
2031
|
rd<bigint | number>(padPolicyAbi, "creatorShareOf", [s.poolId]).then(BigInt),
|
|
2010
2032
|
fPoolDividendOf(c, s.poolId, DEAD_ADDRESS, gen),
|
|
2011
2033
|
rd<bigint>(padPolicyAbi, "threshold", [s.poolId, BigInt(gen)]),
|
|
2012
|
-
rd<bigint>(padPolicyAbi, "
|
|
2034
|
+
rd<bigint>(padPolicyAbi, "incomeTaxRate"),
|
|
2013
2035
|
rd<bigint>(padPolicyAbi, "creatorShareMin"),
|
|
2014
2036
|
rd<bigint>(padPolicyAbi, "creatorShareMax"),
|
|
2015
2037
|
]);
|
|
2016
2038
|
const ranges: PadRanges = { creatorShareMin, creatorShareMax };
|
|
2017
|
-
return { kind: "pad", gen, rung: gen, threshold,
|
|
2039
|
+
return { kind: "pad", gen, rung: gen, threshold, income, creatorShare, incomeTaxRate, ranges };
|
|
2018
2040
|
}
|
|
2019
2041
|
case "pol": {
|
|
2020
|
-
const [minQuoteRatio,
|
|
2021
|
-
return { kind: "pol", minQuoteRatio,
|
|
2042
|
+
const [minQuoteRatio, incomeTaxRate] = await Promise.all([rd<bigint>(polPolicyAbi, "minQuoteRatio"), rd<bigint>(polPolicyAbi, "incomeTaxRate")]);
|
|
2043
|
+
return { kind: "pol", minQuoteRatio, incomeTaxRate };
|
|
2022
2044
|
}
|
|
2023
2045
|
case "public": {
|
|
2024
2046
|
return { kind: "public" };
|
|
@@ -2105,7 +2127,7 @@ export async function fPoolShareHolders(
|
|
|
2105
2127
|
/**
|
|
2106
2128
|
* What a policy answers `onRegenerate` with: `IFPolicy.Terms` — four words, exactly 128 bytes since F version 28 (decision 067
|
|
2107
2129
|
* removed `burn`). `carried` is the holder the next generation carries beside the dead shares; on a pad the manager requires
|
|
2108
|
-
* `0xdead` and caps `toPayee` at `PAYEE_CUT_MAX` of the
|
|
2130
|
+
* `0xdead` and caps `toPayee` at `PAYEE_CUT_MAX` of the income.
|
|
2109
2131
|
*/
|
|
2110
2132
|
export interface FPolicyTerms {
|
|
2111
2133
|
payee: Address;
|
|
@@ -2114,7 +2136,7 @@ export interface FPolicyTerms {
|
|
|
2114
2136
|
carried: Address;
|
|
2115
2137
|
}
|
|
2116
2138
|
|
|
2117
|
-
/** Every F pool's raw state in one lens call (the manager's `Pool` struct: quote, swapFee, policy, seeded, gen, n, restructureTime, asks,
|
|
2139
|
+
/** 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). */
|
|
2118
2140
|
export async function getFPoolsRaw(c: LogswapClient, poolIds: Hex[]): Promise<readonly unknown[]> {
|
|
2119
2141
|
const { logswapLensAbi } = await import("./generated.js");
|
|
2120
2142
|
return (await c.public.readContract({ address: c.addresses.lens, abi: logswapLensAbi, functionName: "getFPools", args: [poolIds] } as never)) as readonly unknown[];
|